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/// Per-child restart policy.
1003///
1004/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
1005#[derive(
1006    Serialize,
1007    Deserialize,
1008    Debug,
1009    Clone,
1010    Copy,
1011    PartialEq,
1012    Eq,
1013    Hash,
1014    gen_platform::TypedDispatcher,
1015    gen_platform::Discriminant,
1016    gen_platform::IsVariant,
1017    gen_platform::FromStrKind,
1018)]
1019pub enum RestartPolicy {
1020    /// Always restart the child, regardless of how it died. Used for
1021    /// long-running services that must always be up.
1022    Permanent,
1023    /// Never restart. Used for one-shot work whose completion is
1024    /// itself the success signal (`oneShot` triggers map here).
1025    Temporary,
1026    /// Restart only when the child died *abnormally* (non-zero exit
1027    /// or unhandled exception). A clean exit completes the child.
1028    Transient,
1029}
1030
1031impl Default for RestartPolicy {
1032    fn default() -> Self {
1033        // Route the [`Default for RestartPolicy`] impl's return arm through
1034        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
1035        // `pub const` rather than a raw `Self::Permanent` arm — one source
1036        // of truth for the Erlang/OTP-canonical `permanent` worker-child
1037        // default across the two production consumers that currently
1038        // dispatch on it (this impl at the [`RestartPolicy::default`] call
1039        // and the serde-side `#[serde(default)]` on
1040        // [`ChildSpec::restart`] that resolves an author-omitted
1041        // `:children :restart` slot through `RestartPolicy::default()`).
1042        // Peer of the sibling per-`:supervisor` axis
1043        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1044        // route (95ffacc) — the two impls now share one substrate-primitive
1045        // lift discipline, so any future coherent rebrand of the OTP-shape
1046        // supervisor+child default set migrates through typed constants in
1047        // lockstep instead of splitting a lifted supervisor half against
1048        // an open-coded child half. Pinned by
1049        // `restart_policy_default_routes_through_lifted_default` +
1050        // `child_spec_serde_default_restart_routes_through_lifted_default`
1051        // in the tests module.
1052        SUPERVISOR_CHILD_RESTART_DEFAULT
1053    }
1054}
1055
1056impl RestartPolicy {
1057    /// Exhaustive iteration surface for every consumer that walks the
1058    /// closed three-arm [`RestartPolicy`] discriminator set (the future
1059    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1060    /// per-child admission-webhook rejection body naming the accepted-
1061    /// `:restart` list, a future `feira supervisor --restart …` CLI
1062    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
1063    /// over the slice, the future `feira app graph` per-child restart
1064    /// column, any future round-trip fuzz harness that sweeps every
1065    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
1066    /// theory
1067    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1068    /// might reach for once the three canonical OTP restart policies
1069    /// stop covering the substrate's discovered load-shape) extends
1070    /// this slice as one edit and every consumer picks up the new entry
1071    /// by construction; the compiler-checked exhaustiveness on the
1072    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
1073    /// is the build-time guarantee that no arm forgets to grow.
1074    ///
1075    /// Peer of the sibling closed-set typed enums'
1076    /// [`RestartStrategy::ALL`] (4eec29c) /
1077    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
1078    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
1079    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
1080    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
1081    /// surfaces — the sixth (and the third and final M2 OTP-shape)
1082    /// closed-set typed enum on the caixa surface to converge onto the
1083    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
1084    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
1085    /// sibling-restart-strategy axis; this closes the per-child
1086    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
1087    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
1088
1089    /// Canonical PascalCase discriminator scalar this variant serializes
1090    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
1091    /// arms return the paired
1092    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1093    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1094    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1095    /// constants so every substrate consumer that dispatches on the
1096    /// per-child restart-decision policy (the future wasm-operator's
1097    /// per-child post-exit restart-decision branch, the future M4
1098    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1099    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
1100    /// reconciliation scheduler's per-child-policy fan-out) reads the
1101    /// same byte-string the `Serialize` derive emits — the pin test in
1102    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1103    /// asserts the two paths agree, peer of the M2
1104    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
1105    /// sibling-restart-strategy axis and the M3
1106    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
1107    /// per-Aplicacao distribution-strategy axis — the third of three
1108    /// OTP-shaped closed-enum discriminator axes on the caixa typed
1109    /// surface to converge onto the same three-path-convergence
1110    /// (`Serialize` derive → `as_str` helper → lifted constant)
1111    /// drift-detection posture.
1112    #[must_use]
1113    pub const fn as_str(self) -> &'static str {
1114        match self {
1115            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1116            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1117            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1118        }
1119    }
1120
1121    /// Substrate-canonical reverse projection on the `:children :restart`
1122    /// closed-set axis — parses the `PascalCase` discriminator scalar
1123    /// back to the typed variant, or `None` when `s` is outside the
1124    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
1125    /// the same lifted
1126    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1127    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1128    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
1129    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
1130    /// of the round-trip migrate through one caixa-core edit on any
1131    /// future arm addition.
1132    ///
1133    /// Prior to this lift the substrate carried only the forward
1134    /// `Self → &str` projection on the OTP per-child restart-policy
1135    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
1136    /// impl routed through it, the `Serialize` derive that emits the
1137    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
1138    /// plus the kebab-case dispatcher-catalog identity via
1139    /// [`Self::discriminant`] — every non-serde consumer that wanted to
1140    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
1141    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
1142    /// "Transient" => …, _ => … }` cascade that expressed no
1143    /// compile-time link back to the typed variant's canonical lifted
1144    /// constant. A future variant rename or per-arm serde-attribute
1145    /// drift would silently split the wire byte-string one non-serde
1146    /// consumer parsed from the one the emitter wrote, with the failure
1147    /// surfacing at the operator's reconcile posture (a `:temporary`
1148    /// `oneShot` child being restarted on clean exit, treating the
1149    /// successful-completion signal as failure and re-running the
1150    /// completion-terminal one-shot indefinitely; a `:transient` child
1151    /// that clean-exited being restarted, masking the clean-completion
1152    /// contract) far from the rebrand commit and with no field naming
1153    /// the drift.
1154    ///
1155    /// Distinct axis from the [`std::str::FromStr`] impl the
1156    /// [`gen_platform::FromStrKind`] derive already installs on this
1157    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
1158    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
1159    /// `"transient"` — the inverse of [`Self::discriminant`]), while
1160    /// this method inverts the `PascalCase` wire byte-string
1161    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
1162    /// catalog identity live in kebab-case (where every peer catalog
1163    /// identifier already lives) without forcing a wire-format rename
1164    /// on the tatara-lisp author surface (`:restart Permanent`,
1165    /// `PascalCase`) — the same two-axis distinction the sibling
1166    /// [`RestartStrategy::from_wire`] (4eec29c) /
1167    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1168    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
1169    /// carry on their peer closed-set typed-enum wire round-trips.
1170    ///
1171    /// Same closed-set-reverse-projection discipline the sibling
1172    /// [`RestartStrategy::from_wire`] (4eec29c) /
1173    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1174    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
1175    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
1176    /// carry on the peer wire-side `str → Self` axes — extended onto
1177    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
1178    /// sixth substrate-side closed-set typed enum (and the third and
1179    /// final OTP-shape closed-enum discriminator axis) to converge on
1180    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
1181    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
1182    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
1183    /// derive already installs on the sibling kebab-case axis. Returns
1184    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
1185    /// shapes: the caller picks the diagnostic form appropriate for
1186    /// its use site.
1187    #[must_use]
1188    pub fn from_wire(s: &str) -> Option<Self> {
1189        match s {
1190            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
1191            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
1192            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
1193            _ => None,
1194        }
1195    }
1196}
1197
1198/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
1199/// pretty-printed byte-string every consumer that formats the policy as
1200/// user-facing text lands on (the future wasm-operator's per-child
1201/// post-exit restart-decision diagnostic line, the future `feira app
1202/// graph` per-child restart column, the future M4
1203/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1204/// admission-webhook rejection body) reaches for the same lifted
1205/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1206/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1207/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1208/// wire-format `Serialize` derive already emits under
1209/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
1210/// [`RestartPolicy::as_str`] helper already returns.
1211///
1212/// Pre-convergence the two paths structurally disagreed — the
1213/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1214/// route (now retired here) sent [`std::fmt::Display`] through the
1215/// gen-platform discriminant catalog string, which arrives kebab-case as
1216/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1217/// (whose variant names each collapse to their own lowercase form under
1218/// the kebab-case transform), while the wire format ran as `PascalCase`
1219/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1220/// serde derive. Every consumer that formatted the policy for a
1221/// diagnostic line, a graph column, or a rejection body under
1222/// `format!("{v}")` therefore landed under a different byte-string than
1223/// the wire format the operator's per-child-policy dispatch keyed off —
1224/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1225/// diagnostic quoting `"permanent"` while the wire scalar the operator
1226/// probed was `"Permanent"`) surfaced as a confused correlate at
1227/// operator-log time far from the two-declaration site.
1228///
1229/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1230/// path: every `format!("{v}")` call reaches the same lifted
1231/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1232/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1233/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1234/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1235/// byte-string per variant. A future variant rename or
1236/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1237/// exactly one place, structurally.
1238///
1239/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1240/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1241/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1242/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1243/// registration keys the catalog off the same kebab identity. The two
1244/// naming worlds now live on separate typed methods (`Display` /
1245/// `as_str` for the wire byte-string, `discriminant` for the catalog
1246/// identity) rather than sharing one `Display` route that structurally
1247/// disagrees with the wire format.
1248///
1249/// Pin tests
1250/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1251/// and
1252/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1253/// assert the three paths agree byte-for-byte on every variant, so a
1254/// future variant rename or per-arm serde attribute drift is a build
1255/// error visible at caixa-core test time, not a silent per-consumer
1256/// dispatch miss at apply / reconcile time.
1257///
1258/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1259/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1260/// and the sibling [`RestartStrategy`] `Display` impl on the
1261/// per-supervisor sibling-restart-strategy axis — same three-path-
1262/// convergence discipline, extended to close the third and final of
1263/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1264/// surface.
1265impl std::fmt::Display for RestartPolicy {
1266    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1267        f.write_str(self.as_str())
1268    }
1269}
1270
1271/// Substrate-canonical [`AsRef<str>`] projection on the M2
1272/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1273/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1274/// scalar accessor the paired [`std::fmt::Display`] impl and the
1275/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1276/// future consumer that binds a [`RestartPolicy`] through the
1277/// standard-library `impl AsRef<str>` bound (a future
1278/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1279/// composes the emitted `PascalCase` wire scalar into a
1280/// [`std::process::Command::arg`] shell-out of the future
1281/// wasm-operator's per-child admission gate, a per-child structured-
1282/// log recorder on the future `caixa-operator`'s hierarchical
1283/// reconciliation surface that accepts `impl AsRef<str>` at the
1284/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1285/// lookup keyed on the restart-policy wire byte through
1286/// `map.get::<str>(policy.as_ref())` on a future per-policy
1287/// dispatch table) reaches the paired
1288/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1289/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1290/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1291/// lifted-const through one substrate-primitive dispatch rather
1292/// than an open-coded `.as_str()` projection at every wire-up.
1293///
1294/// Peer of the sibling [`std::fmt::Display`] impl on the same
1295/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1296/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1297/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1298/// byte-string per instance by construction. A future variant rename
1299/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1300/// enum reaches every one of the three paths (plus the wire-format
1301/// `Serialize` derive that already routes through the same lifted
1302/// const) through exactly one caixa-core edit.
1303///
1304/// Same "route the trait impl through the substrate-primitive
1305/// accessor" discipline the sibling [`crate::CaixaVersion`]
1306/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1307/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1308/// the axis onto the paired per-child-restart-decision-policy
1309/// sibling on the same M2 `:supervisor` slot (the second M2
1310/// OTP-shape closed-set typed enum to converge onto the standard-
1311/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1312/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1313/// primitive so a caller who has one has both; before this lift,
1314/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1315/// [`AsRef<str>`] impl the convention names.
1316///
1317/// Pinned load-bearing by
1318/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1319/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1320/// three-arm closed set) and
1321/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1322/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1323/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1324/// arm) — any future silent detour that routes the impl through a
1325/// divergent projection (a per-arm inline `match self { … }`
1326/// re-inlining that opens a compile-time link to the un-lifted
1327/// arm-literal, a swap onto the kebab-case
1328/// [`gen_platform::Discriminant`] catalog identity that would
1329/// collide the wire axis with the dispatcher-catalog axis) trips at
1330/// caixa-core test time under `assert_eq!` rather than at a
1331/// downstream `impl AsRef<str>`-bound consumer's silent split.
1332impl AsRef<str> for RestartPolicy {
1333    fn as_ref(&self) -> &str {
1334        self.as_str()
1335    }
1336}
1337
1338/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1339/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1340/// byte-for-byte through the paired substrate-primitive
1341/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1342/// consumer that binds a `PascalCase` `:children :restart` wire
1343/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1344/// axis (a future [`caixa-feira`] `feira supervisor --restart
1345/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1346/// `let restart: RestartPolicy = s.try_into()?`, a future
1347/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1348/// `spec.children[*].restart: String` field through
1349/// `RestartPolicy::try_from(&s)?`, a generic
1350/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1351/// set typed enums) reaches the same three-arm accept-set the sibling
1352/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1353/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1354/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1355/// … }` cascade whose arm-set has no compile-time link back to the
1356/// substrate primitive.
1357///
1358/// Complements the pre-existing forward-projection triple
1359/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1360/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1361/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1362/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1363/// caller who can project *out to* a `&str` can also project *in from*
1364/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1365/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1366/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1367/// trigger under a `FromStr` impl and to avoid colliding with the
1368/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1369/// already installs on the paired *kebab-case dispatcher-catalog* axis
1370/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1371/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1372/// idiomatic reverse axis on the *`PascalCase` wire* half without
1373/// disturbing either the method-named `from_wire` shape every sibling
1374/// closed-set typed enum on the substrate already carries or the
1375/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1376/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1377///
1378/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1379/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1380/// caller picks the diagnostic form appropriate for its use site (a
1381/// future `feira supervisor --restart` arg-parse composes its own
1382/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1383/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1384/// wraps the `Err(())` outcome with the accepted-set enumeration for
1385/// operator diagnostics, a `Result::map_err` at the call site lifts the
1386/// unit-error to a per-verb error type). Same shape the peer
1387/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1388/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1389/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1390/// their peer closed-set typed enums' reverse projections.
1391///
1392/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1393/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1394/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1395/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1396/// might reach for once the three canonical OTP restart policies stop
1397/// covering the substrate's discovered load-shape) grows the trait-
1398/// idiomatic axis by construction — one caixa-core edit on
1399/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1400/// projection every existing consumer keys off and the trait-idiomatic
1401/// reverse projection this impl exposes, without a coordinated rewrite
1402/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1403///
1404/// Extends the substrate-wide closed-set-enum reverse-projection family
1405/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1406/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1407/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1408/// closed-enum discriminator axis on the caixa surface — the paired
1409/// per-child `:children :restart` closed set the future wasm-operator's
1410/// hierarchical reconciliation scheduler's per-child post-exit
1411/// restart-decision branch keys off end-to-end.
1412///
1413/// Pinned load-bearing by
1414/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1415/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1416/// three-arm accept-set),
1417/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1418/// (rejection witness against silent accept-set widening), and
1419/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1420/// (cross-axis partition pin locking the trait and method-named
1421/// projections onto one accept-set).
1422impl TryFrom<&str> for RestartPolicy {
1423    type Error = ();
1424
1425    fn try_from(s: &str) -> Result<Self, Self::Error> {
1426        Self::from_wire(s).ok_or(())
1427    }
1428}
1429
1430/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1431/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1432/// byte-for-byte through the paired substrate-primitive
1433/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1434/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1435/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1436/// &str` with `'static` lifetime, so the trait's return-type promise is
1437/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1438/// literal.
1439///
1440/// Every future consumer that specifically needs `&'static str` lifetime
1441/// bytes on the per-child restart-decision axis (a
1442/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1443/// arm's typing demands `&'static str`, a
1444/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1445/// on the future M4 admission-webhook rejection body where the
1446/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1447/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1448/// or error formatter that requires the `'static` bound) reaches the same
1449/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1450/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1451/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1452/// primitive dispatch rather than an open-coded per-arm literal cascade
1453/// whose arm-set has no compile-time link back to the substrate primitive.
1454///
1455/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1456/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1457/// the second (and second-of-two-in-M2) closed-set typed enum on the
1458/// caixa surface to converge onto the paired trait-idiomatic forward-
1459/// projection axis. With this lift the paired per-child
1460/// `:children :restart` closed-set typed enum carries the full sibling
1461/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1462/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1463/// lift) plus the round-trip witness through both the trait-idiomatic
1464/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1465/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1466/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1467/// (an OTP-`intrinsic` fourth arm the theory
1468/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1469/// might reach for once the three canonical OTP restart policies stop
1470/// covering the substrate's discovered load-shape) grows the trait-
1471/// idiomatic forward axis by construction: one caixa-core edit on
1472/// [`RestartPolicy::as_str`] extends every one of the five sibling
1473/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1474/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1475/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1476/// bytes) without a coordinated rewrite across every future
1477/// `Into<&'static str>`-bound consumer's arm-set.
1478///
1479/// Pinned load-bearing by
1480/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1481/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1482/// three-arm emit-set, plus a `const`-context materialization witness for
1483/// the `&'static str` lifetime promise) and
1484/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1485/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1486/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1487/// round-trip witness through the paired trait-idiomatic reverse-
1488/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1489/// `policy.into::<&'static str>()` output re-parses back through
1490/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1491/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1492impl From<RestartPolicy> for &'static str {
1493    fn from(policy: RestartPolicy) -> &'static str {
1494        policy.as_str()
1495    }
1496}
1497
1498/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
1499/// *borrowed* input onto the `&'static str` axis — the borrowed-input
1500/// companion to the paired owned-input [`From<RestartPolicy> for
1501/// &'static str`] impl immediately above. Routes byte-for-byte through
1502/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
1503/// fn` accessor so every consumer that binds a `&RestartPolicy`
1504/// through the standard-library `.into()` / [`From<&Self> for &'static
1505/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
1506/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
1507/// whose iterator over `&'static [RestartPolicy]` yields
1508/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
1509/// [`From<RestartPolicy>`] axis alone forces every call site through
1510/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
1511/// rather than the direct trait-idiomatic projection; a future generic
1512/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
1513/// that walks the `iter().map(Into::into)` shape verbatim across every
1514/// substrate-wide closed-set typed enum; the future wasm-operator's
1515/// per-child post-exit restart-decision diagnostic line that composes
1516/// the accepted-set enumeration from an iterated
1517/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1518/// per-arm `match p { … }` cascade; a future
1519/// `HashMap::<&'static str, RestartPolicy>::from_iter(
1520///     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
1521/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
1522/// cannot compose without this borrowed-input axis in place) reaches
1523/// the same three-arm lifted
1524/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1525/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1526/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1527/// paired owned-input [`From<RestartPolicy> for &'static str`], the
1528/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
1529/// [`RestartPolicy::as_str`] surfaces already return.
1530///
1531/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
1532/// forward-projection family opened on [`crate::dep::DepList`]
1533/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
1534/// [`crate::CaixaDialeto`] (807b0b5), and the paired
1535/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
1536/// (e941836). Rust's `From` trait does not auto-derive the
1537/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
1538/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
1539/// exist in `core`), so every closed-set typed enum that carries the
1540/// owned-input axis but not the borrowed-input axis forces every
1541/// borrowed-input call site through a `.copied()` /
1542/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
1543/// type bounds have no compile-time link to the substrate primitive.
1544/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
1545/// OTP-shape peer to converge onto this campaign — sibling of the
1546/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
1547/// with this lift both closed-set typed enums on the M2 `:supervisor`
1548/// slot now carry the full sibling quintet ([`std::fmt::Display`],
1549/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
1550/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
1551/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
1552/// forward-projection axis on the M2 OTP-shape slot as a unit.
1553///
1554/// Same three-path convergence discipline as the paired owned-input
1555/// impl (this borrowed-input axis, the paired owned-input
1556/// [`From<RestartPolicy> for &'static str`], and
1557/// [`RestartPolicy::as_str`] all route through the same lifted
1558/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
1559/// variant rename or per-arm serde-attribute drift reaches every one
1560/// of the six sibling forward-projection paths
1561/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1562/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
1563/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
1564/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
1565/// edit.
1566///
1567/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
1568/// parse share the same `PascalCase` vocabulary by construction, so
1569/// the borrowed-input forward axis and the reverse axis compose
1570/// directly — the round-trip witness pin below locks this direct
1571/// composition without the intermediate wire-vocab hop the peer
1572/// [`crate::CaixaKind`] axis pair requires.
1573///
1574/// Pinned load-bearing by
1575/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
1576/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1577/// three-arm emit-set via a borrowed input, plus a `const`-context
1578/// materialization witness for the `&'static str` lifetime promise,
1579/// plus a blanket `.into()` shape) and
1580/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
1581/// (cross-axis partition pin against the paired owned-input
1582/// [`From<RestartPolicy> for &'static str`] impl, plus a
1583/// `.iter().map(Into::into)` pipe witness over
1584/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1585/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
1586/// Self` round-trip without the wire-vocab intermediate the peer
1587/// [`crate::CaixaKind`] axis pair requires).
1588impl From<&RestartPolicy> for &'static str {
1589    fn from(policy: &RestartPolicy) -> &'static str {
1590        policy.as_str()
1591    }
1592}
1593
1594/// Trait-idiomatic *owned-`String`* forward projection on the second
1595/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
1596/// owned-heap-string companion to the paired `&'static str`-returning
1597/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
1598/// for &'static str`] impls immediately above. Routes byte-for-byte
1599/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
1600/// const fn` accessor (via [`str::to_owned`]) so every consumer that
1601/// binds a [`RestartPolicy`] through the standard-library `.into()` /
1602/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
1603/// future `serde_json::Value::String(policy.into())` structured-payload
1604/// composer where the `Value::String` arm typing demands an owned
1605/// [`String`] and the sibling [`&'static str`]-returning axis forces
1606/// an explicit `.to_owned()` / `String::from` restatement at every
1607/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
1608/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
1609/// lookup where the map's key type is owned [`String`] rather than
1610/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
1611/// composer on the future M4 admission-webhook rejection body's
1612/// owned-arm, the future wasm-operator's per-child post-exit
1613/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
1614/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
1615/// — reaches the same three-arm lifted
1616/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1617/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1618/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1619/// paired [`std::fmt::Display`], [`AsRef<str>`],
1620/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
1621/// forward-projection impls already return.
1622///
1623/// Extends the trait-idiomatic *owned-`String`* forward-projection
1624/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
1625/// the caixa surface — mirror of the first-mover
1626/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
1627/// axis on the sibling supervisor-level strategy enum. Rust's standard
1628/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
1629/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
1630/// every closed-set typed enum that carries the paired `AsRef<str>` /
1631/// `Display` / `From<Self> for &'static str` triple but not the
1632/// owned-[`String`] axis forces every owned-string call site through a
1633/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
1634/// detour whose type bounds have no compile-time link to the
1635/// substrate primitive.
1636///
1637/// Deliberately routes through the human-readable
1638/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1639/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1640/// the diagnostic byte-string share the same vocabulary by
1641/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1642/// two axes diverge), so the owned-[`String`] projection lands
1643/// byte-identically on both the wire vocabulary the paired
1644/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
1645/// [`RestartPolicy::as_str`] helper returns, and — because the paired
1646/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
1647/// axis parses the same `PascalCase` vocabulary — the direct two-way
1648/// `Self → String → Self` round-trip composes without the wire-vocab
1649/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
1650/// axis pair requires.
1651///
1652/// Pinned load-bearing by
1653/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
1654/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1655/// three-arm emit-set, plus a blanket `.into::<String>()` shape
1656/// witness) and
1657/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
1658/// (cross-axis partition pin against the paired owned-input
1659/// [`From<RestartPolicy> for &'static str`] impl and the sibling
1660/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
1661/// plus a `.iter().copied().map(String::from)` pipe witness over
1662/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1663/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
1664/// borrow that closes the two-way `Self → String → Self` round-trip
1665/// on the trait-idiomatic owned-[`String`] forward + reverse axis
1666/// pair).
1667impl From<RestartPolicy> for String {
1668    fn from(policy: RestartPolicy) -> String {
1669        policy.as_str().to_owned()
1670    }
1671}
1672
1673/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
1674/// projection on the second-of-two M2 OTP-shape closed-set typed enum
1675/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
1676/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1677/// projection family on this enum, mirror of the first-mover
1678/// [`From<&RestartStrategy> for String`] (579385f) that opened the
1679/// 2×2-completion corner on the sibling supervisor-level strategy
1680/// enum. Routes byte-for-byte through the substrate-primitive
1681/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
1682/// [`str::to_owned`]) so every consumer that holds a borrowed
1683/// [`&RestartPolicy`] and needs an owned [`String`] — a future
1684/// `serde_json::Value::String(String::from(&policy))` structured-payload
1685/// composer over a borrowed field, a future `Iterator::map` over
1686/// `&[RestartPolicy]` that projects to owned keys through
1687/// `.iter().map(String::from)`, a future `HashMap::<String,
1688/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
1689/// where dereferencing the policy would force an unnecessary `Copy` at
1690/// every step, the future wasm-operator's per-supervisor
1691/// `child_policies.iter().map(String::from).collect()` per-child post-
1692/// exit restart-decision diagnostic emit whose iteration axis is
1693/// borrowed by construction — reaches the same three-arm lifted
1694/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1695/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1696/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1697/// paired [`std::fmt::Display`], [`AsRef<str>`],
1698/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
1699/// forward-projection impls
1700/// ([`From<RestartPolicy> for &'static str`],
1701/// [`From<&RestartPolicy> for &'static str`],
1702/// [`From<RestartPolicy> for String`]) already return.
1703///
1704/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
1705/// owned-`String` output* forward-projection family opened on
1706/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
1707/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
1708/// both M2 OTP-shape sibling peers (the paired supervisor-level
1709/// sibling-restart-strategy axis and the per-child restart-decision-
1710/// policy axis), so the whole M2 OTP-shape axis pair now carries the
1711/// full four-corner family by construction. Rust's standard library
1712/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
1713/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
1714/// closed-set typed enum that carries the paired `AsRef<str>` /
1715/// `Display` / `From<Self> for &'static str` / `From<&Self> for
1716/// &'static str` / `From<Self> for String` quintuple but not the
1717/// borrowed-input owned-[`String`] axis forces every borrowed-input
1718/// owned-string call site through a `policy.as_str().to_owned()` /
1719/// `String::from(*policy)` (with a spurious `Copy`) /
1720/// `policy.to_string()` (through `Display`) detour whose type bounds
1721/// have no compile-time link to the substrate primitive.
1722///
1723/// Deliberately routes through the human-readable
1724/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1725/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1726/// the diagnostic byte-string share the same vocabulary by
1727/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1728/// two axes diverge), so the borrowed-input owned-[`String`]
1729/// projection lands byte-identically on both the wire vocabulary the
1730/// paired [`serde::Serialize`] derive emits and the diagnostic
1731/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
1732/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
1733/// reverse-projection axis parses the same `PascalCase` vocabulary —
1734/// the direct two-way `&Self → String → Self` round-trip composes
1735/// without the wire-vocab intermediate hop the peer
1736/// [`crate::CaixaKind`] axis pair requires.
1737///
1738/// The remaining thirteen closed-set typed enums on the caixa
1739/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
1740/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
1741/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
1742/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
1743/// of this 2×2-completion campaign — each carries the same paired
1744/// quintuple that this borrowed-input owned-[`String`] axis extends
1745/// onto.
1746///
1747/// Pinned load-bearing by
1748/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
1749/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1750/// three-arm emit-set through the borrowed-input surface) and
1751/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
1752/// (cross-axis partition pin against the paired owned-input owned-
1753/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
1754/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
1755/// &'static str`] impl, and the sibling [`ToString::to_string`]
1756/// surface routed through [`std::fmt::Display`], plus a direct round-
1757/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
1758/// [`String::as_str`] borrow that closes the two-way
1759/// `&Self → String → Self` round-trip on the trait-idiomatic
1760/// borrowed-input owned-[`String`] forward + reverse axis pair).
1761impl From<&RestartPolicy> for String {
1762    fn from(policy: &RestartPolicy) -> String {
1763        policy.as_str().to_owned()
1764    }
1765}
1766
1767/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
1768/// output* forward projection on the M2 OTP-shape per-child-restart
1769/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
1770/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
1771/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
1772/// borrowed-input) and first extended off it onto the sibling M2
1773/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
1774/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
1775/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
1776/// surface (`:children :restart`). Routes byte-for-byte through the
1777/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
1778/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
1779/// that binds a [`RestartPolicy`] through the trait-idiomatic
1780/// [`std::borrow::Cow<'static, str>`] axis — a future
1781/// `axum::response::IntoResponse` composer whose per-policy
1782/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
1783/// borrowed return, a future M4 admission-webhook rejection body
1784/// that composes the accepted-policy enumeration through the same
1785/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
1786/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
1787/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
1788/// emitter on a per-child-policy diagnostic column — reaches the same
1789/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
1790/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1791/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1792/// paired [`std::fmt::Display`], [`AsRef<str>`],
1793/// [`RestartPolicy::as_str`], and the four
1794/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1795/// forward-projection corners already return.
1796///
1797/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
1798/// [`std::borrow::Cow::Owned`] — the substrate-primitive
1799/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
1800/// str` lifetime by construction (each `match` arm resolves to a
1801/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
1802/// with static lifetime), so the zero-alloc borrowed arm is the
1803/// type-correct projection with no runtime allocation.
1804///
1805/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
1806/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
1807/// From<T> for Cow<'static, str>`), so the paired sibling
1808/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
1809/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
1810/// [`std::fmt::Display`] surfaces do not implicitly extend to a
1811/// [`Cow<'static, str>`]-bound call site — every such site is forced
1812/// through a `Cow::Borrowed(policy.as_str())` /
1813/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
1814/// no compile-time link back to the substrate primitive until this
1815/// lift.
1816///
1817/// Second peer to extend the substrate-wide trait-idiomatic
1818/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
1819/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
1820/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
1821/// tier of the campaign (both sibling peers, `RestartStrategy` and
1822/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
1823/// forward projection) so the remaining eleven peers
1824/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
1825/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
1826/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
1827/// `FerriteRuntime`) are the future targets. Every future arm addition
1828/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
1829/// might reach for once the three canonical OTP restart policies stop
1830/// covering the substrate's discovered load-shape) grows the
1831/// Cow<'static, str> axis by construction through one caixa-core edit
1832/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
1833/// across every future Cow<'static, str>-bound consumer site.
1834///
1835/// Pinned load-bearing by
1836/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
1837/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
1838/// against [`RestartPolicy::as_str`] across the three-arm
1839/// [`RestartPolicy::ALL`]) and
1840/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
1841/// (cross-axis partition pin against the paired [`From<RestartPolicy>
1842/// for &'static str`], [`From<RestartPolicy> for String`], and
1843/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
1844/// `.iter().copied().map(Cow::from)` pipe witness over
1845/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
1846/// through the [`Cow<'static, str>`] axis alone and pins the
1847/// zero-alloc discipline on every element).
1848impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
1849    fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
1850        std::borrow::Cow::Borrowed(policy.as_str())
1851    }
1852}
1853
1854/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
1855/// output* forward projection on the M2 OTP-shape per-child-restart
1856/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
1857/// companion to the paired owned-input
1858/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
1859/// immediately above (0612398). Routes byte-for-byte through the same
1860/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
1861/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
1862/// that holds a `&RestartPolicy` and needs a
1863/// [`std::borrow::Cow<'static, str>`] — a
1864/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
1865/// per-arm accept-set materializer (whose iterator over
1866/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
1867/// `RestartPolicy`, so the paired owned-input
1868/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
1869/// alone forces every call site through an explicit `.copied()` /
1870/// dereference / [`Copy`]-bound restatement rather than the direct
1871/// trait-idiomatic projection), a future generic
1872/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
1873/// on a per-child-policy diagnostic column that walks the
1874/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
1875/// webhook rejection body that composes the accepted-policy
1876/// enumeration from an iterated
1877/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1878/// per-arm `match p { … }` cascade — reaches the same three-arm
1879/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1880/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1881/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1882/// paired [`std::fmt::Display`], [`AsRef<str>`],
1883/// [`RestartPolicy::as_str`], the four
1884/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1885/// forward-projection corners, and the paired owned-input
1886/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
1887/// already return.
1888///
1889/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
1890/// [`std::borrow::Cow::Owned`] — the substrate-primitive
1891/// [`RestartPolicy::as_str`] accessor's return carries the
1892/// `&'static str` lifetime by construction (each `match` arm resolves
1893/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
1894/// with static lifetime), so the zero-alloc borrowed arm is the
1895/// type-correct projection with no runtime allocation.
1896///
1897/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
1898/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
1899/// one commit prior (0612398) on the paired owned-input
1900/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
1901/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
1902/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
1903/// which carries both {Self, &Self} × Cow<'static, str> corners since
1904/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
1905/// closed it on the top-level [`crate::CaixaKind`] one commit after
1906/// the owning half (99c1735) landed. This lift closes the whole M2
1907/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
1908/// forward-projection campaign on both input-shape corners
1909/// ({Self, &Self}) of both M2 OTP-shape sibling peers
1910/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
1911/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
1912/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
1913/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
1914/// `FerriteRuntime`) become the future targets of the campaign. Rust's
1915/// standard library does not carry a blanket
1916/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
1917/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
1918/// closed-set fieldless typed enum peer on the substrate that carries
1919/// the paired owned-input [`Cow<'static, str>`] axis but not the
1920/// borrowed-input axis forces every borrowed-input
1921/// [`Cow<'static, str>`]-parameterized call site through a spurious
1922/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
1923/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
1924/// bounds have no compile-time link to the substrate primitive.
1925///
1926/// Pinned load-bearing by
1927/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
1928/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
1929/// against [`RestartPolicy::as_str`] across the three-arm
1930/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
1931/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
1932/// (cross-axis partition pin against the paired owned-input
1933/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
1934/// paired borrowed-input owned-`&'static str`
1935/// [`From<&RestartPolicy> for &'static str`], and the paired
1936/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
1937/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
1938/// over [`RestartPolicy::ALL`] — whose iterator yields
1939/// `&RestartPolicy` by construction, so the borrowed-input
1940/// [`Cow<'static, str>`] axis is what routes the pipe through the
1941/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
1942/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
1943/// spurious [`Copy`] deref).
1944impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
1945    fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
1946        std::borrow::Cow::Borrowed(policy.as_str())
1947    }
1948}
1949
1950// Fleet-wide dispatcher-catalog registrations for caixa's OTP
1951// supervisor surface — two more typed shadows over Erlang/OTP
1952// primitives the substrate now mechanically tracks (see
1953// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
1954// theory/TYPED-ABSORPTION.md for the absorption arc).
1955gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
1956gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
1957
1958/// One child entry in the supervisor's `:children` list.
1959///
1960/// Every child references another caixa by `:caixa <nome>` + version
1961/// constraint. The supervisor materializes one ComputeUnit per entry.
1962#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1963#[serde(rename_all = "camelCase")]
1964pub struct ChildSpec {
1965    /// The child caixa's `:nome`. Must resolve via the same dependency
1966    /// resolution path as `:deps` (caixa-resolver).
1967    pub caixa: String,
1968
1969    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
1970    /// [`crate::dep::Dep::versao`].
1971    pub versao: String,
1972
1973    /// Restart policy — an author-omitted slot degrades onto the
1974    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
1975    /// (`permanent`, the Erlang/OTP worker-child default) through the
1976    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
1977    /// to.
1978    #[serde(default)]
1979    pub restart: RestartPolicy,
1980}
1981
1982impl ChildSpec {
1983    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
1984    /// accessor every consumer that reads the OTP-shape supervised
1985    /// child's identity keys off — returns the author-declared
1986    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
1987    /// from the typed slot's own [`String`] storage.
1988    ///
1989    /// The `:children :caixa` slot carries the DNS-1123 label — the
1990    /// child caixa's `:nome` — that every emitted cluster artifact
1991    /// derives its `metadata.name` from verbatim: the rendered
1992    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
1993    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
1994    /// identity, and the per-child K8s Service `metadata.name` the
1995    /// future wasm-operator (M3) provisions for inter-child supervision-
1996    /// tree wiring. Every downstream consumer that fans on the child's
1997    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
1998    /// per-child DNS-1123 gate at
1999    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
2000    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
2001    /// [`validate_no_self_supervision`] cross-slot equality check
2002    /// against the parent's `:nome`, every `SupervisorError` variant
2003    /// carrying the offending child caixa verbatim for `feira lint`
2004    /// rendering, the future wasm-operator's hierarchical reconciliation
2005    /// scheduler's per-child ComputeUnit-name projection, the future M4
2006    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2007    /// admission webhook).
2008    ///
2009    /// Prior to this lift the `.caixa` byte-string was accessed inline
2010    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
2011    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
2012    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
2013    /// carriers' `child.caixa.clone()`, the dedup key's
2014    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
2015    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
2016    /// field-accesses that expressed no compile-time link back to the
2017    /// typed slot. A future extension of the `:children :caixa` axis to
2018    /// a richer author surface (a per-cluster alias table the operator
2019    /// pins through a future `:placement`-scoped slot on the supervisor
2020    /// tree, a namespace-qualified rewrite the M4 CR materializer
2021    /// applies per-CR, a per-child overlay from the future `:children
2022    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2023    /// acknowledges) would have had to be threaded through every
2024    /// open-coded copy in lockstep or one consumer would silently
2025    /// disagree with the peers on which caixa a given child resolves to
2026    /// — a child-set lookup that treated the name as `"cart-worker"`
2027    /// while the peer duplicate-detector treated it as
2028    /// `"tenant-a/cart-worker"` would silently split the
2029    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
2030    /// self-supervision detector's parent-equality check, a two-consumer
2031    /// split at the validator far from the source `caixa.lisp` with no
2032    /// field naming the identity-drift root cause. Lifting the resolution
2033    /// rule to a typed method on the substrate primitive means every
2034    /// downstream consumer of the Supervisor's per-`:children` identity
2035    /// surface reaches for exactly one typed dispatch — the resolver's
2036    /// accept-set migrates as a unit on any future axis addition.
2037    ///
2038    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
2039    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
2040    /// mesh-slot surface — same "one typed dispatch on the substrate
2041    /// primitive, thin projections at each consumer" discipline extended
2042    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
2043    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
2044    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
2045    /// accessor discipline for the shared substrate concept "another
2046    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
2047    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
2048    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
2049    /// slot family's typed-accessor discipline now spans both the
2050    /// upgrade axis (`:upgrade-from`) and the supervision axis
2051    /// (`:children`), matching the closed M3 mesh-slot accessor family's
2052    /// shape. Named `nome()` to match the tatara-lisp author-surface
2053    /// term the field's docstring already reaches for ("The child
2054    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
2055    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
2056    /// discipline the substrate already carries — the accessor's name
2057    /// maps directly onto the canonical caixa-identity vocabulary rather
2058    /// than shadowing the field's storage-side `caixa` label.
2059    #[must_use]
2060    pub const fn nome(&self) -> &str {
2061        self.caixa.as_str()
2062    }
2063
2064    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
2065    /// requirement scalar accessor every consumer that reads the OTP-shape
2066    /// supervised child's version pin keys off — returns the author-declared
2067    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
2068    /// the typed slot's own [`String`] storage.
2069    ///
2070    /// The `:children :versao` slot carries the Cargo-shaped semver
2071    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
2072    /// which release of the supervised child caixa the OTP-shape supervisor
2073    /// tree materializes against — the same requirement grammar the peer
2074    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
2075    /// shared [`crate::render::require_valid_versao_requirement`] cascade
2076    /// and the shared [`crate::version::parse_requirement`] parser. Every
2077    /// downstream consumer that fans on the child's version pin keys off
2078    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
2079    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
2080    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
2081    /// for `feira lint` rendering, every future per-cluster version-lock
2082    /// overlay the caixa-operator's hierarchical reconciliation scheduler
2083    /// pins through a future `:placement`-scoped supervisor-tree slot, the
2084    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2085    /// per-child version resolver, the future wasm-operator's per-child
2086    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
2087    ///
2088    /// Prior to this lift the `.versao` byte-string was accessed inline at
2089    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
2090    /// [`SupervisorSpec::validate`] requirement-gate call
2091    /// `require_valid_versao_requirement(&child.versao, …)` and the
2092    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
2093    /// `versao: child.versao.clone()` — two open-coded field-accesses that
2094    /// expressed no compile-time link back to the typed slot. A future
2095    /// extension of the `:children :versao` axis to a richer author surface
2096    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2097    /// flow, a lacre-projected concrete-version rewrite the operator
2098    /// materializes at CR-admission time, a future `:children :versao-lock`
2099    /// per-cluster override slot the wasm-operator's hierarchical
2100    /// reconciliation scheduler authors per-CR) would have had to be
2101    /// threaded through both open-coded copies in lockstep or one consumer
2102    /// would silently disagree with the peer on which release constraint a
2103    /// given child resolves to — the requirement-gate call reading
2104    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
2105    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
2106    /// the actual gate rejection input, a two-consumer split at the
2107    /// validator far from the source `caixa.lisp` with no field naming the
2108    /// version-pin drift root cause. Lifting the resolution rule to a typed
2109    /// method on the substrate primitive means every downstream
2110    /// requirement-facing consumer of the Supervisor's per-`:children`
2111    /// version-pin surface reaches for exactly one typed dispatch — the
2112    /// resolver's accept-set migrates as a unit on any future axis addition.
2113    ///
2114    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
2115    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
2116    /// surface — same "one typed dispatch on the substrate primitive, thin
2117    /// projections at each consumer" discipline extended onto the M2
2118    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
2119    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
2120    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
2121    /// one accessor discipline for the shared substrate concept "another
2122    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
2123    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
2124    /// `:nome` scalar accessor — the pair
2125    /// `(nome(), versao_requirement())` jointly projects the
2126    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
2127    /// that fans on per-child identity + version pin keys off, closing the
2128    /// last unlifted per-`:children` `String`-carry axis so every downstream
2129    /// per-`:children` reader now routes through a typed dispatch on the
2130    /// substrate primitive. Named `versao_requirement()` rather than
2131    /// `versao()` because the field's storage-side `.versao` label is
2132    /// already the author-surface term (`:versao`); the accessor's name
2133    /// carries the semantic role — the semver *requirement* string the
2134    /// shared [`crate::version::parse_requirement`] entry-point consumes —
2135    /// so a raw field access and a typed dispatch read differently at every
2136    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
2137    /// naming discipline verbatim.
2138    #[must_use]
2139    pub const fn versao_requirement(&self) -> &str {
2140        self.versao.as_str()
2141    }
2142
2143    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
2144    /// per-child post-exit restart-decision policy scalar accessor every
2145    /// consumer that dispatches on the supervised child's post-exit
2146    /// reconcile posture keys off — returns the author-declared
2147    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
2148    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
2149    /// storage.
2150    ///
2151    /// The `:children :restart` slot carries the closed-set OTP-shaped
2152    /// per-child restart-decision policy discriminator
2153    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
2154    /// worker-child default; [`RestartPolicy::Transient`] — restart only
2155    /// on abnormal exit, the OTP `transient` clean-completion-aware
2156    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
2157    /// `temporary` one-shot default) that every downstream consumer of
2158    /// the Supervisor's per-child post-exit reconcile branch keys off.
2159    /// Every future downstream consumer that fans on the per-child
2160    /// restart-decision keys off this scalar (the future `feira app
2161    /// graph` per-child restart column, the future wasm-operator's
2162    /// per-child post-exit restart-decision branch, the future M4
2163    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2164    /// admission webhook, the `caixa-operator`'s hierarchical
2165    /// reconciliation scheduler's per-child post-exit reconcile branch,
2166    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
2167    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
2168    /// pin threads through).
2169    ///
2170    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
2171    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
2172    /// scalar accessor and the M3 mesh-slot
2173    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
2174    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
2175    /// — same "one typed dispatch on the substrate primitive,
2176    /// `Copy`-projected closed-set enum-arm discriminator that partitions
2177    /// the downstream renderer's per-arm fan-out" discipline extended
2178    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
2179    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
2180    /// [`ChildSpec`] type — companion to the sibling per-`:children`
2181    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
2182    /// and the per-`:children` [`ChildSpec::versao_requirement`]
2183    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
2184    /// on the sibling `String`-carry axes. The triple
2185    /// `(nome(), versao_requirement(), restart())` jointly projects the
2186    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
2187    /// tree consumer that fans on per-child identity + version pin +
2188    /// restart-decision keys off, closing the last unlifted per-`:children`
2189    /// axis so every downstream per-`:children` reader now routes through
2190    /// a typed dispatch on the substrate primitive. Named `restart()` to
2191    /// match the storage field's name and the author-surface
2192    /// `:children :restart` slot term verbatim; the accessor's identity
2193    /// name maps onto the canonical OTP-shape per-child restart-decision-
2194    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
2195    /// carries.
2196    ///
2197    /// Declared `pub const fn` to close the last non-`const`
2198    /// `Copy`-return raw-field-getter posture on the M2
2199    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
2200    /// of the sibling M2 per-`:supervisor`
2201    /// [`SupervisorSpec::estrategia`] (converted in this commit)
2202    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
2203    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2204    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
2205    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
2206    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
2207    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
2208    /// downstream substrate-side `const`-context consumer of the
2209    /// per-`:children` restart-decision-policy scalar (a future
2210    /// module-scope `const _:() = assert!(matches!(child.restart(),
2211    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
2212    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2213    /// admission-webhook `const fn` per-child restart-decision floor
2214    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
2215    /// composer over the substrate primitive that fans on the per-child
2216    /// restart-decision policy at compile time) now reaches through the
2217    /// same typed dispatch on the substrate primitive at const-eval
2218    /// time as at runtime. A future non-`Copy`-return promotion of the
2219    /// scalar (an `Option<RestartPolicy>`-shape migration on the
2220    /// per-child restart-decision axis once heterogeneous per-cluster
2221    /// restart-policy overlays land, a per-tenant restart-policy-alias
2222    /// table the M4 CR materializer resolves per-CR) that would drop
2223    /// the `const` qualifier fails the fail-before-pass-after pin
2224    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
2225    /// build time rather than surfacing as a downstream consumer
2226    /// regression.
2227    #[must_use]
2228    pub const fn restart(&self) -> RestartPolicy {
2229        self.restart
2230    }
2231}
2232
2233/// Supervisor-typed slots that live alongside the standard Caixa
2234/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
2235/// the manifest stays a single typed form; this struct exists for
2236/// validation + conversion.
2237#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2238#[serde(rename_all = "camelCase")]
2239pub struct SupervisorSpec {
2240    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
2241    #[serde(default)]
2242    pub estrategia: RestartStrategy,
2243
2244    /// Max restarts within [`Self::restart_window`] before the
2245    /// supervisor itself terminates (and its parent supervisor decides
2246    /// what to do). Default 5.
2247    #[serde(default = "default_max_restarts")]
2248    pub max_restarts: u32,
2249
2250    /// Sliding window for `max_restarts`. Authored as a duration
2251    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
2252    /// is rejected by [`Self::validate`] — Erlang/OTP's
2253    /// `MaxIntensity / Period` invariant requires a positive window
2254    /// (a zero-period supervisor either trips on the first failure or
2255    /// never trips, depending on operator interpretation, neither of
2256    /// which is the author's intent). Omit the slot to express "no
2257    /// reset"; carry a positive duration to express the sliding window.
2258    #[serde(
2259        default,
2260        skip_serializing_if = "Option::is_none",
2261        with = "duration_codec"
2262    )]
2263    pub restart_window: Option<Duration>,
2264
2265    /// Static children. Empty for `SimpleOneForOne` (children added
2266    /// dynamically); required for the other three strategies.
2267    #[serde(default)]
2268    pub children: Vec<ChildSpec>,
2269}
2270
2271const fn default_max_restarts() -> u32 {
2272    // Route the private serde-`#[serde(default = "…")]` helper through
2273    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
2274    // `pub const` rather than the raw `5` literal — one source of truth
2275    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
2276    // default across the two production consumers that currently
2277    // dispatch on it (this helper via `#[serde(default = "…")]` on
2278    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
2279    // impl at line 962). Pinned by
2280    // `default_max_restarts_helper_routes_through_lifted_default` +
2281    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
2282    // in the tests module; peer of the sibling caixa-core
2283    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
2284    // that now routes its author-omitted `:max-restarts` arm through
2285    // the same lifted constant.
2286    SUPERVISOR_MAX_RESTARTS_DEFAULT
2287}
2288
2289/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
2290/// count default for the `:supervisor :max-restarts` axis — the
2291/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
2292/// Erlang's worker-supervisor default, extracted as a typed `pub const`
2293/// so every substrate-side consumer that resolves "what
2294/// [`SupervisorSpec::max_restarts`] value does an author-omitted
2295/// `:max-restarts` slot degrade onto?" reaches for exactly one
2296/// substrate-primitive `u32`.
2297///
2298/// The `:max-restarts` default axis has two production consumers on the
2299/// substrate side today (both prior to this lift folded onto raw `5`
2300/// literals with no compile-time link back to a shared truth): the
2301/// serde-`#[serde(default = "default_max_restarts")]` helper on
2302/// [`SupervisorSpec::max_restarts`] that every author-omitted
2303/// `:supervisor :max-restarts` slot lands in past the derive-macro's
2304/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
2305/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
2306/// the composed [`SupervisorSpec`] altitude reaches through
2307/// (`feira app graph`, the future wasm-operator's per-supervisor
2308/// restart-intensity counter, the future M4
2309/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2310/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
2311/// A pair of open-coded `5`s across two files that expressed no
2312/// compile-time link back to the shared OTP-canonical default — a
2313/// future rebrand of the default (a tightening to Elixir's
2314/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
2315/// the operator pins through a future
2316/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
2317/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2318/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
2319/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
2320/// per-child-cohort roadmap lands) would have had to be threaded
2321/// through both open-coded copies in lockstep or the wire-format
2322/// author-omitted arm and the view-construction author-omitted arm
2323/// would silently disagree on which restart-budget an omitted
2324/// `:max-restarts` resolves to (an author writing `:supervisor
2325/// (:max-restarts ())` would round-trip through serde with the new
2326/// default while `supervisor_view` silently continued to compose the
2327/// stale `5`, or vice versa), a two-consumer split at the composition
2328/// boundary far from the source `caixa.lisp` with no field naming the
2329/// default-drift root cause. Lifting the resolution rule to a typed
2330/// `pub const` on the substrate primitive means every downstream
2331/// consumer of the per-Supervisor default-restart-budget-count surface
2332/// reaches for exactly one substrate-primitive `u32` — the resolver's
2333/// accepted value migrates as a unit on any future axis change.
2334///
2335/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2336/// worker-supervisor default (the closest canonical OTP-shape
2337/// production reference the substrate carries, matching the sibling
2338/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
2339/// this constant with on the paired sliding-window axis). Two orders of
2340/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
2341/// (the upper bracket on the same axis, sibling of this lower default;
2342/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
2343/// axis and now share one accessor discipline on the substrate) and
2344/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
2345/// restart floor — the "one restart, then escalate" default is
2346/// deliberately loose enough to absorb a short burst of transient
2347/// child failures without escalating past the supervisor's parent
2348/// while remaining tight enough to trip the `MaxIntensity / Period`
2349/// ratio's escalation on a genuinely-stuck child within the sibling
2350/// `60s` sliding window.
2351///
2352/// Lifted as a typed `pub const` so the bound has exactly one source
2353/// of truth — the serde-side wire-format author-omitted arm at
2354/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
2355/// struct-literal default field, and the caixa-core
2356/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
2357/// arm all read from one place. Same shape every other typed default
2358/// in this crate carries (the sibling
2359/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
2360/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
2361/// sibling `:restart-window` axis, and the peer
2362/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2363/// per-renderer defaults on the caixa-flux / caixa-helm rendering
2364/// axes).
2365pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
2366
2367/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
2368/// validated [`SupervisorSpec::max_restarts`] past
2369/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
2370///
2371/// The typed field is `u32` (the zero-floor arm
2372/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
2373/// so a programmatic struct literal
2374/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
2375/// author-surface form (`:max-restarts 4294967295` or any
2376/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
2377/// cleanly through serde — a structurally unbounded `u32` ceiling. The
2378/// runtime substrate consuming the value (Erlang/OTP's
2379/// `MaxIntensity / Period` ratio, the future wasm-operator's
2380/// per-supervisor restart-intensity counter, the M4
2381/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
2382/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
2383/// escalation threshold is structurally so high that no realistic
2384/// restarts-per-`:restart-window` traffic shape can reach it, the
2385/// supervisor never escalates to its parent, and a bad child can loop
2386/// inside the window indefinitely with the parent supervisor structurally
2387/// never receiving the "this subtree has exceeded its restart budget"
2388/// signal the typed slot is meant to express — the canonical
2389/// "supervisor intensity declared, no escalation" footgun, exactly the
2390/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
2391/// on the `:politicas :circuit-breaker :max-failures` axis (both are
2392/// "trip the next-higher protection layer after N events in a rolling
2393/// window" counters with identical degenerate-at-the-high-end shape).
2394///
2395/// The `1000` ceiling matches the sibling
2396/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
2397/// peer — same "events-per-window trip threshold" semantics, same `u32`
2398/// type, same no-op-at-the-high-end failure mode) so the M4
2399/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
2400/// and the future wasm-operator's per-supervisor restart-intensity
2401/// counter reach for either field knowing the value is in `1..=1000`
2402/// without re-validating at the reconciler layer. The cap sits two
2403/// orders of magnitude above every documented Erlang/OTP production
2404/// playbook recommendation (Learn You Some Erlang's
2405/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
2406/// `max_restarts: 3` default, OTP's `supervisor` callback module
2407/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
2408/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
2409/// default) and below the clearly-pathological "effectively no
2410/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
2411/// author can plausibly want at hyperscale (a long-running supervisor
2412/// over a very-flaky pool tolerating thousands of transient restarts
2413/// before escalating), but a hard wall above which the typed policy is
2414/// structurally a no-op carried verbatim on every emitted child-restart
2415/// reconciliation contract.
2416///
2417/// Lifted as a typed `pub const` so the bound has exactly one source of
2418/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2419/// materializer's admission webhook and the wasm-operator-side
2420/// per-supervisor restart-intensity reconciler read from one place. Same
2421/// shape every other typed upper bound in this crate carries
2422/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2423/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2424/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2425/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2426/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2427/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2428pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
2429
2430/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
2431/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
2432/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2433/// (inclusive on both ends, integer-millisecond magnitudes by the
2434/// canonical-form gate immediately preceding).
2435///
2436/// The typed field is `Option<Duration>` (the zero-floor arm
2437/// [`SupervisorError::RestartWindowZero`] already rejects
2438/// `Some(Duration::ZERO)`, and the canonical-form arm
2439/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
2440/// sub-millisecond residue), so a programmatic struct literal
2441/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
2442/// .. }` — 24h) and the equivalent author-surface form
2443/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
2444/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
2445/// cleanly through serde — a structurally unbounded `Duration` ceiling.
2446/// A `:restart-window` value far above the documented Erlang/OTP
2447/// `MaxIntensity / Period` production-playbook band (Learn You Some
2448/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
2449/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
2450/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
2451/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
2452/// degenerates the supervisor's restart-intensity counter into a
2453/// lifetime counter: the rolling failure-counting window is structurally
2454/// so long that transient restarts are never forgotten, so the
2455/// `MaxIntensity / Period` ratio degenerates from "trip the parent
2456/// supervisor when the child has exceeded its restart budget *within
2457/// the recent window*" to "trip the parent when the child has exceeded
2458/// its restart budget *over its lifetime*" — every transient restart
2459/// counts against the budget forever, the supervisor's reset semantic
2460/// never reaches the child, and the typed `:restart-window` slot
2461/// becomes a no-op rolling window carried on every emitted hierarchical
2462/// reconciliation contract. The canonical
2463/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
2464/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
2465/// `:politicas :circuit-breaker :window` axis with identical shape (both
2466/// are "rolling failure-counting window with a per-`Period` reset" Duration
2467/// axes whose lifetime-counter degenerate at the high end is the same
2468/// "the reset semantic never fires" CSE invariant violation).
2469///
2470/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
2471/// the shared duration codec emits (`"<n>h"` for any integer-hour
2472/// magnitude) — every value in the canonical authoring form's
2473/// `<integer><unit>` grammar at or below this cap renders to a clean
2474/// canonical string — and matches the three sibling typed-`Duration`
2475/// caps already lifted to this surface
2476/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2477/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
2478/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
2479/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
2480/// per-supervisor `:supervisor :restart-window` — now share a single
2481/// uniform top edge at the codec's largest emitted unit so the next
2482/// typed-slot wiring (the future wasm-operator's per-supervisor
2483/// `MaxIntensity / Period` reconciler, the M4
2484/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2485/// webhook, the `caixa-operator`'s hierarchical reconciliation
2486/// scheduler) reaches for any of the four knowing the value is in
2487/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
2488/// two orders of magnitude above every documented Erlang/OTP / Elixir /
2489/// Riak Core / RabbitMQ production-playbook recommendation band
2490/// (`5s..=300s`) and below the clearly-pathological "rolling window
2491/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
2492/// a value the author can plausibly want for a very-low-traffic
2493/// long-tail failure-restart window over a hyperscale-flaky child pool,
2494/// but a hard wall above which the rolling-window contract is
2495/// structurally a lifetime-counter contract.
2496///
2497/// Lifted as a typed `pub const` so the bound has exactly one source
2498/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2499/// materializer's admission webhook, the wasm-operator-side
2500/// per-supervisor `MaxIntensity / Period` reconciler, and the
2501/// `caixa-operator`'s hierarchical reconciliation scheduler all read
2502/// from one place. Same shape every other typed upper bound in this
2503/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
2504/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2505/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2506/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2507/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2508/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2509/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
2510/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2511/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2512pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
2513
2514/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
2515/// default for the `:supervisor :restart-window` axis — the canonical
2516/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
2517/// worker-supervisor default, extracted as a typed `pub const` so every
2518/// substrate-side consumer that resolves "what
2519/// [`SupervisorSpec::restart_window`] value does an author-omitted
2520/// `:restart-window` slot degrade onto?" reaches for exactly one
2521/// substrate-primitive [`Duration`].
2522///
2523/// The `:restart-window` default axis has one production consumer on the
2524/// substrate side today: the [`Default for SupervisorSpec`] impl's
2525/// struct-literal `restart_window` field, which prior to this lift folded
2526/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
2527/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
2528/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
2529/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
2530/// *not* fall back to this default on the sibling `:restart-window` axis
2531/// — an author-omitted `:supervisor :restart-window` composes to
2532/// `restart_window: None` (the shared codec's soft-swallow shape),
2533/// keeping author-declared intent ("no reset — never escalate on rolling
2534/// window") distinct from the [`Default for SupervisorSpec`] "canonical
2535/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
2536/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
2537/// default was split across two files with no compile-time link between
2538/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
2539/// `MaxIntensity` half at the substrate primitive while the `Period`
2540/// half rode as an open-coded literal at the composition site, so a
2541/// future coherent rebrand of the paired canonical (a tightening to
2542/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
2543/// per-cluster overlay the operator pins through a future
2544/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
2545/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2546/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
2547/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
2548/// roadmap lands) would have had to migrate the `MaxIntensity` half
2549/// through the lifted constant and the `Period` half through a raw
2550/// literal in lockstep or the two halves of the same OTP-canonical
2551/// default would silently drift out of pairing. Lifting the resolution
2552/// rule to a typed `pub const` on the substrate primitive means the
2553/// paired OTP-canonical default migrates as one unit on any future
2554/// axis change.
2555///
2556/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2557/// worker-supervisor default (the closest canonical OTP-shape
2558/// production reference the substrate carries, matching the paired
2559/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
2560/// constant is the `Period` denominator of on the same
2561/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
2562/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
2563/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
2564/// this lower default; both are typed [`Duration`] const bounds on the
2565/// `:supervisor :restart-window` axis and now share one accessor
2566/// discipline on the substrate) and above the OTP-`supervisor`
2567/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
2568/// rolling window" default is deliberately loose enough to absorb a
2569/// short burst of transient child failures without escalating past the
2570/// supervisor's parent while remaining tight enough for the paired
2571/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
2572/// stuck child within a human-scale observation window.
2573///
2574/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2575/// exactly one source of truth on each half — the sibling
2576/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
2577/// `Period` `60s` half now share the same substrate-primitive lift
2578/// discipline. Same shape every other typed default in this crate
2579/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
2580/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
2581/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
2582/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
2583/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
2584/// caixa-flux / caixa-helm rendering axes).
2585pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
2586
2587/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
2588/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
2589/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
2590/// worker-supervisor default, extracted as a typed `pub const` so every
2591/// substrate-side consumer that resolves "what
2592/// [`SupervisorSpec::estrategia`] variant does an author-omitted
2593/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
2594/// primitive [`RestartStrategy`].
2595///
2596/// The `:estrategia` default axis has three production consumers on the
2597/// substrate side today: the [`Default for RestartStrategy`] impl's
2598/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
2599/// `estrategia` field, and the
2600/// [`crate::manifest::Caixa::supervisor_view`] fold's
2601/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
2602/// collapse arm — three entry points onto the same OTP-canonical
2603/// `one_for_one` value that prior to this lift folded onto a raw
2604/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
2605/// implicit `RestartStrategy::default()` routes at the sibling consumers,
2606/// with no compile-time link back to the paired
2607/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
2608/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
2609/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
2610/// triple was split across three altitudes with no compile-time link
2611/// between the halves: the `MaxIntensity` half rode through the lifted
2612/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
2613/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2614/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
2615/// discriminator at the [`Default for RestartStrategy`] impl, so a future
2616/// coherent rebrand of the triple (Elixir's `{:one_for_one,
2617/// max_restarts: 3, max_seconds: 5}` — same strategy, different
2618/// intensity/period; an OTP `rest_for_one` widening once the substrate
2619/// discovers startup-order-coupled child cohorts as the more common
2620/// worker-supervisor default; a per-cluster overlay the operator pins
2621/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
2622/// §III.2 supervision-canary roadmap acknowledges) would have had to
2623/// migrate the `MaxIntensity` + `Period` halves through the lifted
2624/// constants and the `one_for_one` half through an open-coded arm in
2625/// lockstep or the three halves of the same OTP-canonical default would
2626/// silently drift out of pairing. Lifting the resolution rule to a typed
2627/// `pub const` on the substrate primitive means the paired OTP-canonical
2628/// worker-supervisor default migrates as one unit on any future axis
2629/// change.
2630///
2631/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
2632/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
2633/// closest canonical OTP-shape production reference the substrate
2634/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
2635/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2636/// `60s` `Period` half). The `one_for_one` strategy — restart only the
2637/// failed child, leaving siblings untouched — is the default for tree-of-
2638/// independent-workers use cases the substrate's [`RestartStrategy`]
2639/// discriminator's own docstring already carries as the default arm; it
2640/// composes with the `{5, 60}` restart-intensity ratio to name the same
2641/// substrate-canonical "canonical worker-supervisor" shape the paired
2642/// halves close on their respective axes.
2643///
2644/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2645/// exactly one source of truth on each of its three halves — the sibling
2646/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
2647/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
2648/// this `one_for_one` strategy half now share the same substrate-
2649/// primitive lift discipline. Same shape every other typed default in
2650/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
2651/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
2652/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
2653/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
2654/// upper caps on the paired sibling axes, and the peer
2655/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2656/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
2657pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
2658
2659/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
2660/// default for the `:children :restart` axis — the OTP `permanent`
2661/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
2662/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
2663/// `pub const` so every substrate-side consumer that resolves "what
2664/// [`ChildSpec::restart`] variant does an author-omitted `:children
2665/// :restart` slot degrade onto?" reaches for exactly one substrate-
2666/// primitive [`RestartPolicy`].
2667///
2668/// Completes the OTP-shape supervisor-tree default set at the substrate
2669/// primitive. The per-`:supervisor` axis already carries all three of its
2670/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2671/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
2672/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2673/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
2674/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
2675/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
2676/// the M2 `:supervisor` slot family. The split mattered because the two
2677/// axes resolve *together* on every author-omitted supervisor: a
2678/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
2679/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
2680/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
2681/// `permanent` through an open-coded enum arm, so a future coherent
2682/// rebrand of the OTP-shape default set (an Elixir-shaped
2683/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
2684/// per-cluster overlay the operator pins through the MESH-COMPOSITION
2685/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
2686/// once the substrate discovers clean-completion-aware children as the
2687/// more common child shape) would have had to migrate three halves
2688/// through typed constants and the fourth through a raw enum arm in
2689/// lockstep or the supervisor-level and child-level defaults would
2690/// silently drift apart.
2691///
2692/// The `:children :restart` default axis has two production consumers on
2693/// the substrate side today: the [`Default for RestartPolicy`] impl's
2694/// return arm, and the serde-side `#[serde(default)]` on
2695/// [`ChildSpec::restart`] that resolves an author-omitted `:children
2696/// :restart` slot through that same impl. Both now key off this one
2697/// substrate primitive, so the future wasm-operator's per-child post-exit
2698/// restart-decision branch, the future M4
2699/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2700/// admission webhook, and the `caixa-operator`'s hierarchical
2701/// reconciliation scheduler's per-child fan-out all reach for one typed
2702/// identifier when they resolve an omitted per-child restart posture.
2703///
2704/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
2705/// worker-child restart type — always restart the child regardless of how
2706/// it died, the canonical posture for long-running services that must
2707/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2708/// `one_for_one` tree-of-independent-workers strategy this constant pairs
2709/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
2710/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
2711/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
2712/// [`RestartPolicy::Temporary`] — never restart) express deliberate
2713/// one-shot / clean-completion-aware postures an author declares
2714/// explicitly, never a posture an omitted slot should silently assume.
2715pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
2716
2717/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
2718/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
2719/// `pub const fn` constructor rather than a struct-literal cascade over
2720/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
2721/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2722/// lifted consts — one source of truth for the Erlang/OTP-canonical
2723/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
2724/// paths every downstream consumer already reaches through (the
2725/// hand-authored-until-now [`Default::default`] the
2726/// `..SupervisorSpec::default()` struct-update-syntax on every
2727/// one-axis-under-test fixture in this crate's test module rests on,
2728/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
2729/// every `const`-context consumer reaches through).
2730///
2731/// Extends the [`Default`]-through-const-ctor fold discipline the
2732/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
2733/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
2734/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
2735/// and [`crate::BehaviorSpec`]
2736/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
2737/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
2738/// typed-slot spec family — extended here onto the M2 supervisor-slot
2739/// [`SupervisorSpec`] whose canonical baseline is not "everything
2740/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
2741/// supervisor triple. The `empty()` peer's naming did not fit
2742/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
2743/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
2744/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
2745/// the sibling `Option`-only slots fold to), so this peer is named
2746/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
2747/// existing per-arm pin tests
2748/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
2749/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
2750/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2751/// already reach for. Pinned load-bearing by
2752/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
2753/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
2754/// [`PartialEq`], sharpening the sibling
2755/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
2756/// pins from a per-field lift into a whole-struct one-source-of-truth
2757/// pin — the derived-until-now [`Default::default`] and the
2758/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
2759/// construction, not by coincidence).
2760impl Default for SupervisorSpec {
2761    #[inline]
2762    fn default() -> Self {
2763        Self::otp_canonical()
2764    }
2765}
2766
2767impl SupervisorSpec {
2768    /// `const`-context peer of the [`Default for SupervisorSpec`]
2769    /// impl (which routes through this constructor) — returns the
2770    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
2771    /// baseline this crate reaches for in every fixture-builder
2772    /// `..SupervisorSpec::default()` struct-update expression and
2773    /// every downstream `SupervisorSpec::default()` seed.
2774    ///
2775    /// Each field routes through the same substrate-canonical
2776    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
2777    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
2778    /// per-arm pin tests
2779    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
2780    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
2781    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2782    /// already assert, so a future coherent rebrand of the OTP-canonical
2783    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
2784    /// cluster overlay via a future `:restart-window-overrides` slot, a
2785    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
2786    /// absorption roadmap acknowledges) migrates through three typed
2787    /// constants in lockstep, and the paired [`Default`] impl inherits
2788    /// every future extension by construction.
2789    ///
2790    /// `pub const fn` rather than the derived-style `Default::default`
2791    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
2792    /// [`Default::default`] is not `const` on stable Rust, and
2793    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
2794    /// every consumer through a [`Clone::clone`]. The `pub const fn`
2795    /// discipline lets `const`-context callers construct the OTP-
2796    /// canonical baseline at compile time without runtime dispatch on
2797    /// the derived [`Default::default`], the same posture the sibling
2798    /// [`crate::LimitsSpec::empty`] (9739971) /
2799    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
2800    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
2801    /// spec `pub const fn` constructors carry on the sibling
2802    /// "everything `None`" baseline axis.
2803    ///
2804    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
2805    /// of the derived-style [`Default`]" family — sibling of the
2806    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
2807    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
2808    /// baseline" trio, extended here onto the M2 supervisor-slot
2809    /// [`SupervisorSpec`] whose canonical baseline is not "everything
2810    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
2811    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
2812    /// than `empty()` to name the actual invariant the return value
2813    /// pins — the same phrasing already used in the per-arm pin tests
2814    /// on this file. Pinned load-bearing by
2815    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
2816    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
2817    #[must_use]
2818    pub const fn otp_canonical() -> Self {
2819        Self {
2820            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
2821            max_restarts: default_max_restarts(),
2822            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2823            children: Vec::new(),
2824        }
2825    }
2826
2827    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
2828    /// sibling-restart-strategy scalar accessor every consumer that
2829    /// dispatches on the supervisor's per-sibling restart-decision shape
2830    /// keys off — returns the author-declared `:supervisor :estrategia`
2831    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
2832    /// the typed slot's own [`RestartStrategy`] storage.
2833    ///
2834    /// The `:supervisor :estrategia` slot carries the closed-set
2835    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
2836    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
2837    /// [`RestartStrategy::OneForAll`] — restart every child on any child
2838    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
2839    /// [`RestartStrategy::RestForOne`] — restart the failed child and
2840    /// every child started after it, the Erlang/OTP `rest_for_one`
2841    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
2842    /// dynamic children of the same shape, the Erlang/OTP
2843    /// `simple_one_for_one` per-session default) that every downstream
2844    /// consumer of the Supervisor's per-sibling restart-decision fan-out
2845    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
2846    /// paired coherently with the sibling `:children` axis
2847    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
2848    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
2849    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
2850    /// downstream consumer that reads the strategy keys off this scalar
2851    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2852    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
2853    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
2854    /// `estrategia:` field, the future `feira app graph` per-Supervisor
2855    /// strategy print line, the future wasm-operator's per-supervisor
2856    /// sibling-restart-strategy branch, the future M4
2857    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
2858    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
2859    /// reconciliation scheduler's per-strategy fan-out).
2860    ///
2861    /// Prior to this lift the `.estrategia` field was accessed inline at
2862    /// two production sites in `caixa-core/src/supervisor.rs` — the
2863    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2864    /// `match self.estrategia { … }` partition dispatch, and the
2865    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
2866    /// carrier at `estrategia: self.estrategia` — two open-coded
2867    /// field-accesses that expressed no compile-time link back to the
2868    /// typed slot. A future extension of the `:supervisor :estrategia`
2869    /// axis to a richer author surface (a per-cluster strategy override
2870    /// the operator pins through a future `:supervisor :estrategia-overrides`
2871    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2872    /// acknowledges, a per-tenant strategy-alias table the M4 CR
2873    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
2874    /// derivation the future adaptive-supervision engine computes from
2875    /// child-failure-history topology, a per-child-cohort strategy split
2876    /// the future `RestForCohort` extension acknowledged by the
2877    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
2878    /// would have had to be threaded through every open-coded copy in
2879    /// lockstep — one consumer reading the raw variant while a peer read
2880    /// the operator-resolved variant would silently split the
2881    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
2882    /// the actual partition-dispatch input the empty-children refusal
2883    /// arm reached under, a two-consumer split at the validator far from
2884    /// the source `caixa.lisp` with no field naming the strategy-drift
2885    /// root cause. Lifting the resolution rule to a typed method on the
2886    /// substrate primitive means every downstream consumer of the
2887    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
2888    /// reaches for exactly one typed dispatch — the resolver's accept-set
2889    /// migrates as a unit on any future axis addition.
2890    ///
2891    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
2892    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
2893    /// per-`:placement` distribution-strategy axis — same "one typed
2894    /// dispatch on the substrate primitive, thin projections at each
2895    /// consumer" discipline extended onto the M2 supervisor-slot
2896    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
2897    /// scalar axis. The two typed axes (`Placement::estrategia` on the
2898    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
2899    /// Supervisor side) now share one accessor discipline for the shared
2900    /// substrate concept "a `Copy`-projected closed-set enum-arm
2901    /// discriminator that partitions the downstream renderer's per-arm
2902    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
2903    /// `SupervisorSpec` type — companion to the sibling per-`:children`
2904    /// [`crate::ChildSpec::nome`] (57c61d0) /
2905    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2906    /// scalar accessors on the sibling per-`:children` `String`-carry
2907    /// axes. Named `estrategia()` to match the storage field's name and
2908    /// the peer [`crate::Placement::estrategia`] method-name discipline
2909    /// verbatim; the accessor's identity name maps onto the canonical
2910    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
2911    /// docstring already carries.
2912    ///
2913    /// Declared `pub const fn` to close the M2 supervisor-slot
2914    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
2915    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
2916    /// (converted in this commit) `Copy`-composite-enum accessor, peer
2917    /// of the sibling M2 per-`:supervisor`
2918    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2919    /// already lifted, and mirror of the peer M3 mesh-slot
2920    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
2921    /// `Copy`-return `pub const fn` scalar accessor whose method-name
2922    /// discipline this accessor was authored to match. Every downstream
2923    /// substrate-side `const`-context consumer of the per-`:supervisor`
2924    /// sibling-restart-strategy scalar (a future module-scope `const
2925    /// _:() = assert!(matches!(sup.estrategia(),
2926    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
2927    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2928    /// admission-webhook `const fn` per-supervisor strategy-arm floor
2929    /// over a typed [`SupervisorSpec`], any future `const fn`
2930    /// supervisor-tree composer over the substrate primitive that fans
2931    /// on the sibling-restart-strategy at compile time) now reaches
2932    /// through the same typed dispatch on the substrate primitive at
2933    /// const-eval time as at runtime. A future non-`Copy`-return
2934    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
2935    /// migration once the substrate grows per-cluster strategy overlays
2936    /// the [`SupervisorSpec`] docstring already anticipates, a
2937    /// per-tenant strategy-alias table the M4 CR materializer resolves
2938    /// per-CR) that would drop the `const` qualifier fails the
2939    /// fail-before-pass-after pin
2940    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
2941    /// caixa-core build time rather than surfacing as a downstream
2942    /// consumer regression.
2943    #[must_use]
2944    pub const fn estrategia(&self) -> RestartStrategy {
2945        self.estrategia
2946    }
2947
2948    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
2949    /// `MaxIntensity` restart-budget scalar accessor every consumer that
2950    /// reads the supervisor's per-`:restart-window` restart-budget count
2951    /// keys off — returns the author-declared `:supervisor :max-restarts`
2952    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
2953    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
2954    /// borrow of `&self` past the call). Non-optional (the `u32` field
2955    /// carries the restart-budget count as a required axis with a
2956    /// [`default_max_restarts`]-supplied default; the zero-floor arm
2957    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
2958    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
2959    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
2960    ///
2961    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
2962    /// `MaxIntensity` restart-budget count that pairs with the sibling
2963    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
2964    /// restart-intensity ratio the supervisor trips its own escalation on
2965    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
2966    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
2967    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
2968    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
2969    /// upper-cap bracket at
2970    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
2971    /// wasm-operator's per-supervisor restart-intensity counter's
2972    /// budget-vs-count comparator, the future M4
2973    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2974    /// webhook, the `caixa-operator`'s hierarchical reconciliation
2975    /// scheduler's per-supervisor escalation-decision branch, every
2976    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
2977    /// offending count verbatim for `feira lint` rendering).
2978    ///
2979    /// Prior to this lift the `.max_restarts` field was accessed inline at
2980    /// one production site in `caixa-core/src/supervisor.rs` — the
2981    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
2982    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
2983    /// that expressed no compile-time link back to the typed slot. A
2984    /// future extension of the `:max-restarts` axis to a richer author
2985    /// surface (a per-cluster restart-budget override the operator pins
2986    /// through a future `:supervisor :max-restarts-overrides` slot the
2987    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
2988    /// a per-tenant restart-budget-alias table the M4 CR materializer
2989    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
2990    /// the future adaptive-supervision engine computes from child-failure-
2991    /// history topology, a promotion of the plain `u32` count to a richer
2992    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
2993    /// budget-partition slot comes into scope) would have had to be
2994    /// threaded through every open-coded copy in lockstep or the validate
2995    /// gate and the future M4 emit path would silently disagree on which
2996    /// restart-budget count a given supervisor resolves to — an author's
2997    /// `:max-restarts 5` would satisfy validate while the emit path
2998    /// silently read a drifted other value (a `:max-restarts 10000`
2999    /// no-op supervisor at the emit boundary would carry the author's
3000    /// declared `5` verbatim in `feira lint` output while the future
3001    /// wasm-operator's restart-intensity counter operated under the
3002    /// drifted count), a two-consumer split at the validator far from the
3003    /// source `caixa.lisp` with no field naming the restart-budget-drift
3004    /// root cause. Lifting the resolution rule to a typed method on the
3005    /// substrate primitive means every downstream consumer of the
3006    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
3007    /// for exactly one typed dispatch — the resolver's accept-set migrates
3008    /// as a unit on any future axis addition.
3009    ///
3010    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
3011    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
3012    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
3013    /// outlier-detection trip-threshold axis — same "one typed dispatch on
3014    /// the substrate primitive, thin projections at each consumer"
3015    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
3016    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
3017    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
3018    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
3019    /// one accessor discipline for the shared substrate concept "a
3020    /// `Copy`-projected required `u32` count that trips the next-higher
3021    /// protection layer after N events in a rolling window" — both are
3022    /// counters with identical degenerate-at-the-high-end shape and share
3023    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
3024    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
3025    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
3026    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
3027    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
3028    /// the storage field's name verbatim and the peer
3029    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
3030    /// accessor's identity maps onto the canonical OTP-shape supervision
3031    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
3032    /// already carries.
3033    #[must_use]
3034    pub const fn max_restarts(&self) -> u32 {
3035        self.max_restarts
3036    }
3037
3038    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
3039    /// `Period` sliding-window scalar accessor every consumer of the
3040    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
3041    /// keys off — returns the author-declared `:supervisor :restart-window`
3042    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
3043    /// the typed slot's own `Option<Duration>` storage (`Duration` is
3044    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
3045    /// value; no borrow of `&self` past the call). `None` when the slot is
3046    /// absent (the canonical "never reset — every restart across the
3047    /// supervisor's lifetime counts against the sibling `:max-restarts`
3048    /// budget" sentinel the field's own docstring names and the peer
3049    /// `validate_accepts_none_restart_window` pin locks in on the
3050    /// [`SupervisorSpec::validate`] entry-side).
3051    ///
3052    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
3053    /// `Period` sliding-observation-interval that pairs with the sibling
3054    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
3055    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
3056    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
3057    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
3058    /// default). The typed slot's `Option<Duration>` accept-set —
3059    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
3060    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
3061    /// `Period > 0`; a zero period either trips on the first failure or
3062    /// never trips depending on operator interpretation, neither of which
3063    /// is the author's intent — omit the slot to express "no reset";
3064    /// carry a positive duration to express the sliding window),
3065    /// integer-millisecond canonical form enforced through
3066    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
3067    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
3068    /// future wasm-operator's per-supervisor restart-intensity counter
3069    /// quantizes at milliseconds), upper-bounded by
3070    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
3071    /// supervisor rolling window any operationally-reachable supervisor
3072    /// can honor without spanning multiple scheduler epochs the
3073    /// hierarchical-reconciliation scheduler treats as independent) —
3074    /// maps onto the future wasm-operator (M3) per-supervisor
3075    /// restart-intensity counter's rolling-observation-interval, the
3076    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3077    /// per-`spec.restartWindow` admission webhook, and the sibling
3078    /// `duration_codec`-serialized wire scalar every downstream consumer
3079    /// of the supervisor's per-`:supervisor` restart-intensity denominator
3080    /// keys off.
3081    ///
3082    /// Prior to this lift the `.restart_window` field was accessed inline
3083    /// at one production site in `caixa-core/src/supervisor.rs` — the
3084    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
3085    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
3086    /// open-coded field-access that expressed no compile-time link back to
3087    /// the typed slot. A future extension of the `:restart-window` axis to
3088    /// a richer author surface (a per-cluster restart-window override the
3089    /// operator pins through a future `:supervisor :restart-window-overrides`
3090    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3091    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
3092    /// materializer resolves per-CR, a per-supervisor dynamic
3093    /// restart-window derivation the future adaptive-supervision engine
3094    /// computes from child-failure-history topology, a promotion of the
3095    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
3096    /// pair once Erlang/OTP's per-child-cohort observation-interval-
3097    /// partition slot comes into scope) would have had to be threaded
3098    /// through every open-coded copy in lockstep or the validate gate and
3099    /// the future M4 emit path would silently disagree on which
3100    /// restart-window a given supervisor resolves to — an author's
3101    /// `:restart-window "60s"` would satisfy validate while the emit path
3102    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
3103    /// authored slot at the emit boundary would carry the author's
3104    /// declared window verbatim in `feira lint` output while the future
3105    /// wasm-operator's restart-intensity counter operated under a
3106    /// drifted window, or vice versa: an author's `:restart-window ()`
3107    /// would carry the "never reset" sentinel through validate while the
3108    /// emit path silently substituted a default sliding window), a
3109    /// two-consumer split at the validator far from the source
3110    /// `caixa.lisp` with no field naming the restart-window-drift root
3111    /// cause. Lifting the resolution rule to a typed method on the
3112    /// substrate primitive means every downstream consumer of the
3113    /// Supervisor's per-`:supervisor` restart-intensity-denominator
3114    /// surface reaches for exactly one typed dispatch — the resolver's
3115    /// accept-set migrates as a unit on any future axis addition.
3116    ///
3117    /// Third `Copy`-return accessor on the M2 supervisor-slot
3118    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
3119    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
3120    /// payload rather than a `Copy`-scalar, and the per-`:children`
3121    /// [`crate::ChildSpec::nome`] (57c61d0) /
3122    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3123    /// scalar accessors already close the per-element `String`-carry
3124    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
3125    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
3126    /// per-outermost-call wall-clock-deadline axis and the peer M3
3127    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
3128    /// accessor on the `:politicas` slot's per-call-deadline axis — all
3129    /// three share the shared substrate concept "a `Copy`-projected
3130    /// optional `Duration` that carries a positive integer-millisecond
3131    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
3132    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
3133    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
3134    /// bracket-helper the three axes each route through. Named
3135    /// `restart_window()` to match the storage field's name verbatim and
3136    /// the peer [`crate::LimitsSpec::wall_clock`] /
3137    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
3138    /// accessor's identity maps onto the canonical OTP-shape supervision
3139    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
3140    /// already carries.
3141    #[must_use]
3142    pub const fn restart_window(&self) -> Option<Duration> {
3143        self.restart_window
3144    }
3145
3146    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
3147    /// static-child-list slice accessor every consumer that walks the
3148    /// supervisor's declared child set keys off — returns the author-
3149    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
3150    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
3151    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
3152    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
3153    /// through). Non-optional: an empty slice is the load-bearing
3154    /// "author declared `:children ()`" sentinel every consumer of the
3155    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
3156    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
3157    /// three strategies require a non-empty slice — the paired
3158    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
3159    /// [`SupervisorError::NoChildren`] refusal cascade pins the
3160    /// partition on both arms).
3161    ///
3162    /// The `:supervisor :children` slot carries the OTP-shaped static
3163    /// child list the supervisor materializes one ComputeUnit per
3164    /// entry from — the Erlang/OTP `supervisor:init/1`'s
3165    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
3166    /// through the tatara-lisp `:children` author surface onto a typed
3167    /// `Vec<ChildSpec>` whose per-element `(nome(),
3168    /// versao_requirement(), restart)` triple the per-child
3169    /// [`SupervisorSpec::validate`] loop already gates through the
3170    /// lifted [`ChildSpec::nome`] (57c61d0) /
3171    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
3172    /// Every downstream consumer that fans on the static child list
3173    /// keys off this slice (the [`SupervisorSpec::validate`]
3174    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
3175    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
3176    /// per-child DNS-1123 / semver-requirement / duplicate-detection
3177    /// fan-out loop, every future wasm-operator (M3) per-supervisor
3178    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
3179    /// materialization loop, the future M4
3180    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3181    /// admission-webhook fan-out, the future `feira app graph`
3182    /// per-supervisor tree-print traversal).
3183    ///
3184    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
3185    /// inline at three production sites in `caixa-core/src/supervisor.rs`
3186    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
3187    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
3188    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
3189    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
3190    /// validate loop's `for child in &self.children` traversal head —
3191    /// three open-coded field-accesses that expressed no compile-time
3192    /// link back to the typed slot. A future extension of the
3193    /// `:supervisor :children` axis to a richer author surface (a
3194    /// per-cluster child-set overlay the operator pins through a future
3195    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
3196    /// supervision-canary roadmap acknowledges, a per-tenant
3197    /// child-set-alias table the M4 CR materializer resolves per-CR,
3198    /// a per-supervisor dynamic-child derivation the future adaptive-
3199    /// supervision engine computes from child-failure-history topology,
3200    /// a promotion of the plain `Vec<ChildSpec>` to a richer
3201    /// `{static, dynamic}` partition once Erlang/OTP's
3202    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
3203    /// would have had to be threaded through all three open-coded copies
3204    /// in lockstep or one consumer would silently disagree with the
3205    /// peers on which child-set a given supervisor resolves to — the
3206    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
3207    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
3208    /// would silently split the partition-dispatch's two-arm coherence
3209    /// (a supervisor that satisfies neither arm's precondition, or that
3210    /// satisfies both, at the cost of the paired
3211    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
3212    /// silently drifting from the per-child validate loop's actual
3213    /// traversal input), a three-consumer split at the validator far
3214    /// from the source `caixa.lisp` with no field naming the
3215    /// child-set-drift root cause. Lifting the resolution rule to a
3216    /// typed method on the substrate primitive means every downstream
3217    /// consumer of the Supervisor's per-`:supervisor` static-child-list
3218    /// surface reaches for exactly one typed dispatch — the resolver's
3219    /// accept-set migrates as a unit on any future axis addition.
3220    ///
3221    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
3222    /// — the seed for the same "one typed dispatch on the substrate
3223    /// primitive, thin projections at each consumer" discipline the
3224    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
3225    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
3226    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
3227    /// onto the first `Vec`-carry axis on the substrate. The four peer
3228    /// `Vec`-carry axes still unlifted at the time of this seed —
3229    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
3230    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
3231    /// (`Vec<Membro>` per-Aplicacao member list),
3232    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
3233    /// per-Aplicacao WIT-typed edge list),
3234    /// [`crate::UpgradeFromEntry::instructions`]
3235    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
3236    /// — inherit this accessor's discipline as future compounding runs
3237    /// migrate their consumers onto the shared slice-return shape.
3238    /// Fourth (and final) accessor on the M2 supervisor-slot
3239    /// `SupervisorSpec` type, sibling to the three `Copy`-return
3240    /// [`SupervisorSpec::estrategia`] (eafb619) /
3241    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
3242    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
3243    /// the last unlifted per-`:supervisor` field axis (the
3244    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
3245    /// per-`:supervisor` reader now routes through a typed dispatch on
3246    /// the substrate primitive. Named `children()` to match the storage
3247    /// field's name verbatim and the tatara-lisp author-surface term
3248    /// (`:children`) the field's own docstring already carries; the
3249    /// accessor's identity maps onto the canonical OTP-shape
3250    /// supervision vocabulary the [`SupervisorSpec::children`] field's
3251    /// docstring already reaches for ("Static children ..."). Returns
3252    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
3253    /// consumer of the child list treats it as a read-only sequence —
3254    /// the slice-view is the narrowest borrow that supports every
3255    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
3256    /// index, `.len()`) without leaking the backing `Vec`'s
3257    /// grow/push/reserve surface that no consumer of the typed view
3258    /// reaches for (the storage-side `Vec` remains reachable through
3259    /// the `pub children` field for the mutation-carrying
3260    /// `Caixa::supervisor_view` fold-in path in
3261    /// `manifest.rs:supervisor_view`).
3262    #[must_use]
3263    pub const fn children(&self) -> &[ChildSpec] {
3264        self.children.as_slice()
3265    }
3266
3267    /// Validate the supervisor's typed shape — strategy ↔ children
3268    /// invariants, max_restarts > 0, restart_window > 0 when set,
3269    /// per-child non-empty + duplicate-free names.
3270    ///
3271    /// Mirrors the value-shape discipline applied to every other
3272    /// typed slot:
3273    ///
3274    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
3275    ///     same "0 means the opposite of what you think" footgun
3276    ///     closed for `:politicas :timeout` (Envoy interprets a zero
3277    ///     timeout as `infinite`), `:politicas :circuit-breaker
3278    ///     :window`, and `:limits :wall-clock`. The
3279    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
3280    ///     `supervisor` requires `Period > 0`; a zero period either
3281    ///     trips on the first failure or never trips depending on
3282    ///     operator interpretation, neither of which is the
3283    ///     author's intent. Omit `:restart-window` to express "no
3284    ///     reset"; carry a positive duration to express the window.
3285    ///   - duplicate `:children` `:caixa` names are the same
3286    ///     graph-node-set / multiset distinction closed for
3287    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
3288    ///     and `:entrada :paths` (eb3456d). Two children with the
3289    ///     same `:caixa` materialize as two ComputeUnits with the
3290    ///     same name in the cluster's HelmRelease values, one
3291    ///     silently overwriting the other. Erlang/OTP's
3292    ///     `child_spec.id` is required-unique per supervisor;
3293    ///     pleme-io enforces the same set-not-multiset shape on
3294    ///     `:caixa` (the load-bearing identity in our renderer).
3295    pub fn validate(&self) -> Result<(), SupervisorError> {
3296        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
3297        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3298        // error carrier's `estrategia:` field through the lifted
3299        // [`SupervisorSpec::estrategia`] accessor rather than the raw
3300        // `self.estrategia` field access — the two production consumers
3301        // of the per-`:supervisor` sibling-restart-strategy scalar now
3302        // key off exactly one typed dispatch on the substrate primitive,
3303        // so any future rebrand on the axis (a per-cluster strategy
3304        // override the operator pins through a future `:supervisor
3305        // :estrategia-overrides` slot, a per-tenant strategy-alias table
3306        // the M4 CR materializer resolves per-CR) migrates as a single
3307        // caixa-core edit rather than a coordinated rewrite of the two
3308        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
3309        // (921fe1b) four-consumer migration on the per-`:placement`
3310        // distribution-strategy axis.
3311        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
3312        // dispatch's paired `.is_empty()` cross-slot refusal probes
3313        // (the `SimpleOneForOne`-arm
3314        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
3315        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3316        // refusal) through the lifted [`SupervisorSpec::children`]
3317        // slice-return accessor rather than the raw `self.children`
3318        // field access — the two paired production consumers of the
3319        // per-`:supervisor` static-child-list scalar-shape now key off
3320        // exactly one typed dispatch on the substrate primitive, so any
3321        // future rebrand on the axis (a per-cluster child-set overlay
3322        // the operator pins through a future `:supervisor
3323        // :children-overrides` slot, a per-tenant child-set-alias table
3324        // the M4 CR materializer resolves per-CR) migrates as a single
3325        // caixa-core edit rather than a coordinated rewrite of the
3326        // paired arms — first slice-return migration on any typed slot,
3327        // seed for the peer per-`:placement :clusters`,
3328        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
3329        // :instructions` `Vec`-carry axes.
3330        match self.estrategia() {
3331            RestartStrategy::SimpleOneForOne => {
3332                // SimpleOneForOne: children added at runtime. Static
3333                // list must be empty (one shape declared elsewhere).
3334                if !self.children().is_empty() {
3335                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
3336                }
3337            }
3338            _ => {
3339                if self.children().is_empty() {
3340                    return Err(SupervisorError::no_children(self.estrategia()));
3341                }
3342            }
3343        }
3344        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
3345        // axis. See [`crate::render::require_positive_bounded_u32`] for
3346        // the ordering discipline (zero-floor arm strictly precedes cap
3347        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
3348        // diagnostic with its counter-axis remediation directly named,
3349        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
3350        // cap-arm miss). Until this bracket landed the top edge ran all
3351        // the way to `u32::MAX` and a struct-literal
3352        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
3353        // equivalent author-surface `:max-restarts 100000` /
3354        // `:max-restarts 4294967295` typo landing in the slot) silently
3355        // passed validate. The runtime substrate consuming the value
3356        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
3357        // wasm-operator's per-supervisor restart-intensity counter, the
3358        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3359        // admission webhook) then turned a typed `:max-restarts`
3360        // policy into a no-op supervisor: the escalation threshold is
3361        // structurally so high that no realistic
3362        // restarts-per-`:restart-window` traffic shape can reach it,
3363        // the supervisor never escalates to its parent, and a bad
3364        // child can loop inside the window indefinitely with the
3365        // parent supervisor structurally never receiving the "this
3366        // subtree has exceeded its restart budget" signal the typed
3367        // slot is meant to express. The bracket set is
3368        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
3369        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
3370        // the sibling `:politicas :circuit-breaker :max-failures` axis:
3371        // both are "trip the next-higher protection layer after N
3372        // events in a rolling window" counters with identical
3373        // degenerate-at-the-high-end shape and now share one canonical
3374        // bracket helper. The bracket precedes the sibling
3375        // `:restart-window` zero-floor / canonical-millisecond arms so
3376        // an over-cap `max_restarts` paired with a structurally invalid
3377        // window surfaces the bracket diagnostic first, mirroring the
3378        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
3379        // ordering on the peer `:politicas :circuit-breaker` slot.
3380        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
3381        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
3382        // accessor rather than the raw `self.max_restarts` field access —
3383        // the one production consumer of the per-`:supervisor`
3384        // restart-budget-count scalar now keys off exactly one typed
3385        // dispatch on the substrate primitive, so any future rebrand on
3386        // the axis (a per-cluster restart-budget override the operator
3387        // pins through a future `:supervisor :max-restarts-overrides`
3388        // slot, a per-tenant restart-budget-alias table the M4 CR
3389        // materializer resolves per-CR) migrates as a single caixa-core
3390        // edit rather than a coordinated rewrite — sibling of the peer M3
3391        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
3392        // the per-`:politicas :circuit-breaker :max-failures` axis.
3393        crate::render::require_positive_bounded_u32(
3394            self.max_restarts(),
3395            SUPERVISOR_MAX_RESTARTS_MAX,
3396            || SupervisorError::ZeroMaxRestarts,
3397            SupervisorError::max_restarts_exceeds_cap,
3398        )?;
3399        // Route the [`SupervisorSpec::validate`] `:restart-window`
3400        // zero-floor + integer-millisecond canonical-form + upper-cap
3401        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
3402        // accessor rather than the raw `self.restart_window` field access —
3403        // the one production consumer of the per-`:supervisor`
3404        // restart-intensity-denominator scalar now keys off exactly one
3405        // typed dispatch on the substrate primitive, so any future rebrand
3406        // on the axis (a per-cluster restart-window override the operator
3407        // pins through a future `:supervisor :restart-window-overrides`
3408        // slot, a per-tenant restart-window-alias table the M4 CR
3409        // materializer resolves per-CR) migrates as a single caixa-core
3410        // edit rather than a coordinated rewrite — sibling of the peer M2
3411        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
3412        // on the per-`:limits :wall-clock` axis and the peer M3
3413        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
3414        // per-`:politicas :timeout` axis.
3415        if let Some(w) = self.restart_window() {
3416            // Zero-floor + integer-millisecond canonical-form +
3417            // upper-cap bracket on the typed `:restart-window` axis.
3418            // See
3419            // [`crate::render::require_positive_canonical_bounded_duration`]
3420            // for the full three-arm ordering discipline (zero-floor
3421            // strictly precedes canonical-form so `Duration::ZERO`
3422            // surfaces the self-locating `RestartWindowZero`
3423            // diagnostic; canonical-form strictly precedes the cap arm
3424            // so a sub-millisecond above-cap value surfaces the more
3425            // fundamental round-trip-shape diagnostic first) and the
3426            // three peer typed-`Duration` sites that share this
3427            // canonical bracket ([`crate::MeshPolicy::timeout`],
3428            // [`crate::CircuitBreaker::window`],
3429            // [`crate::LimitsSpec::wall_clock`]). Every validated
3430            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3431            // (1ms..=1h), integer-millisecond granularity.
3432            crate::render::require_positive_canonical_bounded_duration(
3433                w,
3434                SUPERVISOR_RESTART_WINDOW_MAX,
3435                || SupervisorError::RestartWindowZero,
3436                SupervisorError::restart_window_not_canonical,
3437                SupervisorError::restart_window_exceeds_cap,
3438            )?;
3439        }
3440        // Route the per-child DNS-1123 / semver-requirement / duplicate-
3441        // detection fan-out loop through the lifted named per-slot gate
3442        // [`SupervisorSpec::validate_children`] rather than an inline
3443        // three-per-child cascade — every future consumer that wants to
3444        // re-check only the `:children` slot's per-entry axes (the M4
3445        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3446        // admission webhook re-validating one added/renamed child, the
3447        // future wasm-operator's per-child dynamic-add re-validator on
3448        // the `SimpleOneForOne` runtime-add path once dynamic-children
3449        // graduate to a typed slot, a future partial re-validator on a
3450        // per-`:children`-entry patch) reaches every per-entry axis
3451        // through one dispatch rather than re-inlining the three-arm
3452        // cascade in lockstep with `validate` or paying the peer
3453        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
3454        // reach one entry check. Sibling of the peer M3 mesh-slot
3455        // per-slot gate family (`validate_membros` — the exact peer on
3456        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
3457        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
3458        // `validate_placement`; `validate_politicas` routing through
3459        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
3460        // per-slot gate discipline now spans both the M3 mesh-slot
3461        // family and the M2 `:children` per-child-cascade axis on one
3462        // shape: one named per-slot gate per typed per-entry loop.
3463        self.validate_children()?;
3464        Ok(())
3465    }
3466
3467    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
3468    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
3469    /// gate, and duplicate-`:caixa` dedup arm into one call every
3470    /// consumer that wants to re-validate one `:children` entry (or the
3471    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
3472    /// admits reaches through.
3473    ///
3474    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
3475    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
3476    /// three-per-entry shape (DNS-1123 name + semver-requirement +
3477    /// duplicate-`:caixa` dedup), lifted to one named substrate
3478    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3479    /// materializer's admission webhook re-checking one added or renamed
3480    /// child, the future wasm-operator's per-child dynamic-add
3481    /// re-validator on the `SimpleOneForOne` runtime-add path once
3482    /// dynamic-children graduate to a typed slot, a future partial
3483    /// re-validator on a per-`:children`-entry patch — each reaches the
3484    /// three per-entry axes through this one dispatch rather than
3485    /// re-inlining the three-arm cascade in lockstep with `validate`
3486    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
3487    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
3488    /// reach one entry check.
3489    ///
3490    /// Self-contained on `&self` — resolves its own dedup `HashSet`
3491    /// through [`SupervisorSpec::children`] rather than borrowing one
3492    /// threaded down from `validate`, the same posture the peer M3
3493    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
3494    /// [`crate::AplicacaoSpec::validate_contratos`],
3495    /// [`crate::AplicacaoSpec::validate_entrada`],
3496    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
3497    /// consumer that reaches this gate directly (without first calling
3498    /// `validate`) still runs the full per-child cascade — pinned by
3499    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3500    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3501    /// + `validate_children_is_self_contained_on_children_slot`.
3502    ///
3503    /// The three per-entry arms run in the same canonical order the
3504    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
3505    /// the diagnostic every author-declared per-`:children` entry surfaces
3506    /// through `validate` is byte-equal to the diagnostic this gate
3507    /// surfaces when called directly — the equivalence-pin pair
3508    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3509    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3510    /// asserts the two altitudes discriminate the same set on every
3511    /// per-entry-covered input.
3512    pub fn validate_children(&self) -> Result<(), SupervisorError> {
3513        let mut seen = std::collections::HashSet::new();
3514        for child in self.children() {
3515            // Every emitted cluster artifact's `metadata.name` for a
3516            // supervised child derives from this `:children :caixa` value
3517            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
3518            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
3519            // label value on every child's pod identity, and the per-
3520            // child K8s [`Service`][svc] `metadata.name` the future
3521            // wasm-operator (M3) provisions for inter-child supervision
3522            // tree wiring. Each apiserver-side schema on each landing
3523            // site enforces the DNS-1123 label rule on admission; a
3524            // structurally invalid child name (`"Worker"`, `"my_worker"`,
3525            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
3526            // UUID-shaped mistaken-identity slug) silently passes the
3527            // prior empty-/duplicate-only gate and the failure surfaces
3528            // at `kubectl apply` time as a `metadata.name: Invalid value`
3529            // rejection, far from the source caixa.lisp, with no field
3530            // naming the offending `:children` entry. Lifting the gate
3531            // to caixa-build time mirrors the `:membros :caixa` value-
3532            // shape trajectory (3f9d7a0) and the `:placement :clusters`
3533            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
3534            // identifier axis — the supervisor tree's child names —
3535            // through the lifted
3536            // [`crate::render::require_valid_dns_1123_label`] gate the
3537            // seven peer name axes (`:membros :caixa`, `:placement
3538            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
3539            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
3540            // route through, so drift between the eight axes' accepted
3541            // DNS-1123-label sets is structurally impossible.
3542            //
3543            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
3544            crate::render::require_valid_dns_1123_label(
3545                child.nome(),
3546                || SupervisorError::EmptyChildName,
3547                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
3548            )?;
3549            // The author surface for `:children :versao` is the same
3550            // Cargo-shaped semver requirement string `:deps :versao` and
3551            // `:membros :versao` carry — and the lacre pipeline resolves
3552            // all three axes through the same
3553            // [`crate::version::parse_requirement`] entry-point. The
3554            // shared [`crate::render::require_valid_versao_requirement`]
3555            // helper brackets the empty-first + parse cascade both peer
3556            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
3557            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
3558            // :versao`) route through, so drift between the three axes'
3559            // accepted requirement sets is structurally impossible and
3560            // the parse-side no-op the empty-first arm closes (semver's
3561            // empty parse yields an implicit `*`) lives in exactly one
3562            // predicate. Every `ChildSpec::versao` past validate is
3563            // round-trippable through [`crate::parse_requirement`]
3564            // without re-checking at the resolver layer, and the three
3565            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
3566            // are now structurally equivalent by construction.
3567            crate::render::require_valid_versao_requirement(
3568                child.versao_requirement(),
3569                || SupervisorError::empty_child_version(child.nome()),
3570                |reason| {
3571                    SupervisorError::child_versao_invalid(
3572                        child.nome(),
3573                        child.versao_requirement(),
3574                        reason,
3575                    )
3576                },
3577            )?;
3578            crate::render::insert_first_seen(&mut seen, child.nome(), || {
3579                SupervisorError::duplicate_child_caixa(child.nome())
3580            })?;
3581        }
3582        Ok(())
3583    }
3584}
3585
3586/// Cross-slot coherence gate on the supervision tree: no
3587/// `:children :caixa` entry may name the supervisor's own `:nome`.
3588///
3589/// A supervisor that lists itself as a child is a degenerate self-parent
3590/// — the supervision tree is a DAG rooted at the supervisor (OTP child
3591/// specs reference *distinct* child processes; a supervisor is never its
3592/// own child), and the wasm-operator's hierarchical reconciliation would
3593/// otherwise be handed a node that is its own parent: a one-node cycle it
3594/// either rejects far from the source `caixa.lisp` or recurses on. Because
3595/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
3596/// lacre closure root), a child whose `:caixa` equals the supervisor's
3597/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
3598///
3599/// Lives outside [`SupervisorSpec::validate`] because the typed view
3600/// carries the children but not the parent `:nome`; mirrors the
3601/// cross-slot precedence gate `validate_upgrade_from_against_versao`
3602/// (which likewise reads one slot against another at the
3603/// [`crate::layout`] wire-up site) and the mesh self-edge gate
3604/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
3605/// node to itself is structurally not a tree/mesh edge" discipline, here
3606/// on the supervision-tree axis.
3607pub fn validate_no_self_supervision(
3608    children: &[ChildSpec],
3609    parent_nome: &str,
3610) -> Result<(), SupervisorError> {
3611    for child in children {
3612        if child.nome() == parent_nome {
3613            return Err(SupervisorError::child_supervises_self(parent_nome));
3614        }
3615    }
3616    Ok(())
3617}
3618
3619#[derive(Debug, Error, PartialEq, Eq)]
3620pub enum SupervisorError {
3621    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
3622    NoChildren { estrategia: RestartStrategy },
3623    #[error(
3624        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
3625    )]
3626    SimpleOneForOneWithStaticChildren,
3627    #[error(":max-restarts must be > 0")]
3628    ZeroMaxRestarts,
3629    #[error(
3630        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
3631         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
3632         restart-intensity policy into a no-op supervisor: the escalation threshold is \
3633         structurally so high that no realistic restarts-per-:restart-window traffic shape \
3634         can reach it, so the supervisor never escalates to its parent and a bad child can \
3635         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
3636         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
3637         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3638         materializer's admission webhook) emits a `:max-restarts` declaration that is \
3639         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
3640         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
3641         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
3642         band) or restructure the supervision tree (split the flaky child into its own \
3643         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
3644    )]
3645    MaxRestartsExceedsCap { max_restarts: u32 },
3646    #[error(
3647        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
3648         requires Period > 0; a zero window either trips on the first failure or \
3649         never trips depending on operator interpretation. Omit :restart-window to \
3650         express `never reset`; carry a positive duration to express the window."
3651    )]
3652    RestartWindowZero,
3653    #[error(
3654        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
3655         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
3656         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
3657         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
3658         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
3659    )]
3660    RestartWindowNotCanonical { window: Duration },
3661    #[error(
3662        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
3663         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
3664         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
3665         failure-counting window is structurally so long that transient restarts are never \
3666         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
3667         when the child has exceeded its restart budget within the recent window` to `trip the \
3668         parent when the child has exceeded its restart budget over its lifetime`, and the \
3669         supervisor's reset semantic never reaches the child — every typed-slot consumer \
3670         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
3671         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3672         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
3673         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
3674         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
3675         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
3676         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
3677         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
3678         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
3679         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
3680         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
3681         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
3682         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
3683         hiding it behind a rolling-window declaration the cap arm rejects)"
3684    )]
3685    RestartWindowExceedsCap { window: Duration },
3686    #[error("child entry has empty :caixa name")]
3687    EmptyChildName,
3688    #[error(
3689        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
3690         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
3691         name / label value the child name lands in — the per-child \
3692         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
3693         label value, and the future wasm-operator per-child Service `metadata.name` \
3694         — each apiserver-side schema rejects names that don't match; use a \
3695         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
3696    )]
3697    ChildCaixaInvalid { caixa: String, reason: String },
3698    #[error("child {caixa:?} has empty :versao constraint")]
3699    EmptyChildVersion { caixa: String },
3700    #[error(
3701        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
3702         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
3703         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
3704         `:membros :versao` carry; the lacre pipeline resolves all three \
3705         through the same parser)"
3706    )]
3707    ChildVersaoInvalid {
3708        caixa: String,
3709        versao: String,
3710        reason: String,
3711    },
3712    #[error(
3713        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
3714         child_spec.id per supervisor; duplicate children materialize as duplicate \
3715         ComputeUnits in the rendered chart, one silently overwriting the other)"
3716    )]
3717    DuplicateChildCaixa { caixa: String },
3718    #[error(
3719        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
3720         never its own child (the supervision tree is a DAG rooted at the supervisor; \
3721         OTP child specs reference distinct child processes). Since every :nome is a \
3722         globally-unique substrate identity, a child naming the supervisor's own :nome \
3723         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
3724         self-referential :children entry or rename it to the actual child caixa."
3725    )]
3726    ChildSupervisesSelf { caixa: String },
3727}
3728
3729// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
3730// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
3731// and [`validate_no_self_supervision`] onto one substrate primitive per
3732// typed variant — the sibling on `SupervisorError` of the four uniform-shape
3733// `LayoutError`-envelope constructor families the peer
3734// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
3735// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
3736// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
3737// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
3738// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
3739// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
3740// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
3741// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
3742// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
3743// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
3744// variants on `{ de, para }`) already at that discipline on the peer
3745// `AplicacaoError` envelopes.
3746//
3747// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
3748// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
3749// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
3750// self-supervision arm) opened the identical
3751// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
3752// the exact "same block re-inlined at every consumer" shape the PRIME
3753// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
3754// `AplicacaoError` families each closed on their sibling envelopes. The
3755// three variants share one `{ caixa: String }` shape, so the fold routes
3756// each wire-up site through one dispatch per typed variant.
3757//
3758// The macro below generates one static constructor per variant of shape
3759// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
3760// collapses onto one dispatch:
3761// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
3762// struct-literal on the same `&str` fixture. The uniform one-field
3763// construction (`caixa: caixa.to_string()`) is spelled once — inside the
3764// macro — rather than at every wire-up site. Every constructor is
3765// `#[must_use]` so a caller who mistakenly discards the constructed error
3766// trips a compile warning at the wire-up site.
3767//
3768// Every future consumer that wants to construct one of these three
3769// variants outside `SupervisorSpec::validate_children` /
3770// `validate_no_self_supervision` — a deferred
3771// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3772// webhook re-checking one added/renamed child, a future
3773// `feira validate --supervisor` per-caixa admission verb, a per-child
3774// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
3775// once dynamic-children graduate to a typed slot, a per-Supervisor
3776// overlay resolver rejecting a duplicate/self-supervising child against
3777// a cluster-local snapshot — now reaches each variant through one call
3778// rather than re-inlining the three-line struct-literal in lockstep
3779// with the three in-crate wire-up sites.
3780macro_rules! supervisor_caixa_only_ctors {
3781    ($($ctor:ident => $variant:ident),* $(,)?) => {
3782        impl SupervisorError {
3783            $(
3784                #[doc = concat!(
3785                    "Construct a [`SupervisorError::",
3786                    stringify!($variant),
3787                    "`] naming the offending `:children :caixa` (or ",
3788                    "supervisor `:nome`, on the self-supervision arm). ",
3789                    "Folds the uniform `Self::",
3790                    stringify!($variant),
3791                    " { caixa: caixa.to_string() }` one-field ",
3792                    "struct-literal onto one substrate primitive so ",
3793                    "every [`SupervisorSpec::validate_children`] / ",
3794                    "[`validate_no_self_supervision`] wire-up on this ",
3795                    "variant reads through one dispatch rather than the ",
3796                    "pre-lift open-coded struct-literal block."
3797                )]
3798                #[must_use]
3799                pub fn $ctor(caixa: &str) -> Self {
3800                    Self::$variant { caixa: caixa.to_string() }
3801                }
3802            )*
3803        }
3804    };
3805}
3806
3807supervisor_caixa_only_ctors! {
3808    empty_child_version => EmptyChildVersion,
3809    duplicate_child_caixa => DuplicateChildCaixa,
3810    child_supervises_self => ChildSupervisesSelf,
3811}
3812
3813// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
3814// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
3815// one substrate primitive per typed variant — the M2 supervisor-side siblings
3816// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
3817// already lifted through the sibling
3818// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
3819// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
3820// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
3821// String }` two-slot shape the peer seven-variant
3822// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
3823// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
3824// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
3825// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
3826// variant carries the `{ caixa: String, versao: String, reason: String }`
3827// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
3828// carries on the same `:versao` value-shape.
3829//
3830// Each of the two wire-up sites opened the same closure-shaped
3831// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
3832// [versao: child.versao_requirement().to_string(),] reason }` block inside
3833// the paired [`crate::render::require_valid_dns_1123_label`] and
3834// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
3835// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
3836// as a bug, on the same altitude the peer `AplicacaoError` /
3837// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
3838// families already closed on their sibling envelopes.
3839//
3840// The two `#[must_use]` inherent constructors below fold each wire-up onto
3841// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
3842// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
3843// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
3844// The uniform per-field `.to_string()` / `.into()` construction is spelled
3845// once — inside each ctor body — rather than at every wire-up site. The
3846// `reason: impl Into<String>` bound accepts both `&str` literals and
3847// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
3848// diagnostic shape at the lift, matching the peer
3849// [`aplicacao_field_reason_ctors!`] and
3850// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
3851// sibling envelopes.
3852//
3853// Every future consumer that wants to construct one of these two variants
3854// outside `SupervisorSpec::validate_children` — a deferred
3855// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
3856// re-checking one added/renamed child's `:caixa` or `:versao`, a future
3857// `feira validate --supervisor` per-caixa admission verb, a per-child
3858// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
3859// dynamic-children graduate to a typed slot, a per-Supervisor overlay
3860// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
3861// cluster-local snapshot — now reaches each variant through one call rather
3862// than re-inlining the per-shape struct-literal block in lockstep with the
3863// two in-crate wire-up sites.
3864impl SupervisorError {
3865    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
3866    /// offending `:children :caixa` value under the given `reason`. Folds
3867    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
3868    /// reason: reason.into() }` two-slot struct-literal onto one substrate
3869    /// primitive so every wire-up on this variant reads through one
3870    /// dispatch, matching the peer
3871    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
3872    /// sibling `AplicacaoError { caixa: String, reason: String }`
3873    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
3874    /// outputs through the `impl Into<String>` bound.
3875    #[must_use]
3876    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
3877        Self::ChildCaixaInvalid {
3878            caixa: caixa.to_string(),
3879            reason: reason.into(),
3880        }
3881    }
3882
3883    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
3884    /// offending `:children :caixa` and its `:versao` requirement under
3885    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
3886    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
3887    /// reason.into() }` three-slot struct-literal onto one substrate
3888    /// primitive so every wire-up on this variant reads through one
3889    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
3890    /// { caixa, versao, reason }` three-slot axis on the peer
3891    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
3892    /// and `format!(…)` outputs through the `impl Into<String>` bound.
3893    #[must_use]
3894    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
3895        Self::ChildVersaoInvalid {
3896            caixa: caixa.to_string(),
3897            versao: versao.to_string(),
3898            reason: reason.into(),
3899        }
3900    }
3901}
3902
3903// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
3904// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
3905// three bracket-arms — one struct-literal at the `:children`-empty
3906// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
3907// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
3908// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
3909// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
3910// [`crate::render::require_positive_canonical_bounded_duration`]
3911// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
3912// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
3913// primitive per typed variant, matching the sibling
3914// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
3915// variants on the same `{ <field>: Duration | u32 }` shape) at that
3916// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
3917// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
3918// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
3919// wire-up site through one dispatch per typed variant without a runtime-
3920// work delta.
3921//
3922// Each of the four wire-up sites opened the identical
3923// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
3924// exact "same block re-inlined at every consumer" shape the PRIME
3925// DIRECTIVE names as a bug, on the same altitude the peer
3926// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
3927// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
3928// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
3929// the fold routes each wire-up site through one dispatch per typed
3930// variant.
3931//
3932// The macro below generates one static constructor per variant of shape
3933// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
3934// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
3935// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
3936// fixture — as a direct call at the [`SupervisorSpec::validate`]
3937// `:children`-empty refusal, or as a bare function pointer in the
3938// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
3939// [`crate::render::require_positive_bounded_u32`] /
3940// [`crate::render::require_positive_canonical_bounded_duration`] gate
3941// carries — rather than the pre-lift open-coded one-line closure over
3942// the same one-field struct-literal. `const fn` preserves the `Copy`-
3943// pass-through's zero-runtime-work property verbatim. Every constructor
3944// is `#[must_use]` so a caller who mistakenly discards the constructed
3945// error trips a compile warning at the wire-up site.
3946//
3947// Every future consumer that wants to construct one of these four
3948// variants outside `SupervisorSpec::validate` — a deferred
3949// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3950// webhook re-checking one edited `:estrategia` / `:max-restarts` /
3951// `:restart-window` slot against the cap + canonical-form cascade, a
3952// future `feira validate --supervisor` per-caixa admission verb re-
3953// running the shape gates on demand, a per-Supervisor overlay resolver
3954// rejecting an author-supplied slot against a cluster-local snapshot —
3955// now reaches each variant through one call rather than re-inlining the
3956// per-shape struct-literal block in lockstep with the four in-crate
3957// wire-up sites.
3958macro_rules! supervisor_scalar_ctors {
3959    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
3960        impl SupervisorError {
3961            $(
3962                #[doc = concat!(
3963                    "Construct a [`SupervisorError::",
3964                    stringify!($variant),
3965                    "`] naming the offending per-`:supervisor` `",
3966                    stringify!($field),
3967                    "` scalar. Folds the uniform `Self::",
3968                    stringify!($variant),
3969                    " { ",
3970                    stringify!($field),
3971                    " }` one-field `Copy`-pass-through struct-literal onto ",
3972                    "one substrate primitive so every per-axis wire-up on ",
3973                    "this variant reads through one dispatch — as a direct ",
3974                    "call (`SupervisorError::",
3975                    stringify!($ctor),
3976                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
3977                    "the same `Copy`-`",
3978                    stringify!($ty),
3979                    "` fixture) or as a bare function pointer in the ",
3980                    "`impl FnOnce(",
3981                    stringify!($ty),
3982                    ") -> SupervisorError` bracket-closure slot every ",
3983                    "`crate::render::require_positive_bounded_*` / ",
3984                    "`crate::render::require_positive_canonical_bounded_*` ",
3985                    "gate carries — rather than the pre-lift open-coded ",
3986                    "one-line closure over the same one-field struct-",
3987                    "literal. `const fn` preserves the `Copy`-pass-through's ",
3988                    "zero-runtime-work property verbatim."
3989                )]
3990                #[must_use]
3991                pub const fn $ctor($field: $ty) -> Self {
3992                    Self::$variant { $field }
3993                }
3994            )*
3995        }
3996    };
3997}
3998
3999supervisor_scalar_ctors! {
4000    no_children => NoChildren { estrategia: RestartStrategy },
4001    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
4002    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
4003    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
4004}
4005
4006/// Shared duration string codec for the typed slots that take a
4007/// duration (`restart_window`, `MeshPolicy::timeout`,
4008/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
4009/// reuse it without duplicating the parser.
4010pub mod duration_codec {
4011    use super::Duration;
4012    use serde::{Deserializer, Serializer};
4013
4014    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
4015        // Route through the canonical [`crate::render::serialize_option_via_str`]
4016        // — the substrate-side single-owner primitive for the forward
4017        // arm of the typed-magnitude codec family. See its docstring
4018        // for the full sibling roster.
4019        crate::render::serialize_option_via_str(v, s, render)
4020    }
4021
4022    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
4023        // Route through the canonical [`crate::render::deserialize_option_via_str`]
4024        // — the substrate-side single-owner primitive for the reverse
4025        // arm of the typed-magnitude codec family. See its docstring
4026        // for the full sibling roster.
4027        crate::render::deserialize_option_via_str(d, parse)
4028    }
4029
4030    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
4031        // Paired whitespace-rejection arm — same canonical-form
4032        // render-determinism discipline as the peer
4033        // `limits::parse_byte_size` / `limits::parse_duration` /
4034        // `limits::parse_millicores` /
4035        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
4036        // byte-scan closes the WhatWG-conformant whitespace bytes
4037        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
4038        // `char::is_whitespace` scan closes the strictly-complementary
4039        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
4040        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
4041        // codepoints) that `str::trim` at parse entry silently strips.
4042        // Either drift class would round-trip through `render` to a
4043        // *different* canonical form on next emit — breaking the
4044        // THEORY.md Part V render-determinism contract on three typed-
4045        // duration slots at once (`:supervisor :restart-window`,
4046        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
4047        // via the shared codec.
4048        //
4049        // Routed through the lifted [`crate::render::reject_whitespace`]
4050        // primitive — the substrate-side single-owner paired-arm gate
4051        // every typed-magnitude codec in caixa-core shares.
4052        crate::render::reject_whitespace::<String, _, _>(
4053            s,
4054            |b| {
4055                format!(
4056                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4057                 authoring form for the typed duration slots routed through this shared codec \
4058                 (`:supervisor :restart-window`, `:politicas :timeout`, \
4059                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4060                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
4061                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
4062                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
4063                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
4064                 Part V render-determinism contract every typed slot carries. Strip every \
4065                 whitespace byte (write `\"30s\"` verbatim)"
4066                )
4067            },
4068            |ch| {
4069                format!(
4070                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
4071                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
4072                 duration slots routed through this shared codec (`:supervisor \
4073                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
4074                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
4075                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
4076                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
4077                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
4078                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
4079                 `White_Space` property, strictly wider than the ASCII byte set) silently \
4080                 strips it at parse entry, and the value round-trips through `render` to \
4081                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
4082                 the THEORY.md Part V render-determinism contract every typed slot \
4083                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
4084                 verbatim with only ASCII bytes)",
4085                    cp = ch as u32
4086                )
4087            },
4088        )?;
4089        let s = s.trim();
4090        // Routed through the lifted
4091        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
4092        // the single-owner split every ASCII-alphabetic-unit typed-
4093        // magnitude codec in caixa-core (`limits::parse_byte_size` /
4094        // `limits::parse_duration` / this shared duration codec) shares.
4095        // See its docstring for the full sibling roster on the same
4096        // primitive altitude.
4097        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
4098        let num_trim = num_part.trim();
4099        // The canonical authoring form for every typed slot routed
4100        // through this shared codec — `:supervisor :restart-window`,
4101        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
4102        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
4103        // non-negative integer with no decimal point and no leading
4104        // sign, so the parser's accepted set must match for
4105        // serialize/deserialize to round-trip without canonical-form
4106        // drift. Until this gate landed the parser accepted any
4107        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
4108        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
4109        // tripped the value to a *different* canonical string on the
4110        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
4111        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
4112        // — breaking the THEORY.md Part V render-determinism contract
4113        // on three typed slots at once. Same canonical-form discipline
4114        // `crate::limits::parse_duration` (818dd38, the immediate
4115        // predecessor on the peer `:limits :wall-clock` codec) applies;
4116        // this gate lifts the discipline onto the shared codec that
4117        // backs the remaining three typed-duration slots in caixa-core.
4118        //
4119        // Strict canonical form: every byte of the magnitude is an
4120        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4121        // inputs the gate distinguishes "non-canonical-but-numeric"
4122        // (parses as f64 or i64 — surfaced with a self-locating
4123        // diagnostic naming the canonical authoring form, the
4124        // round-trip drift each rejected shape would produce on first
4125        // serialize, and the canonical-form remediation) from
4126        // "garbage" (parses as neither — surfaced with the existing
4127        // narrower "bad duration magnitude" wording so its diagnostic
4128        // shape remains stable for the parser-shape footgun case).
4129        // The pre-existing `num < 0.0` arm is now unreachable — the
4130        // digit-only gate strictly precedes magnitude parsing, and a
4131        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
4132        // non-canonical-but-numeric branch with the `-30` named
4133        // verbatim in the diagnostic rather than the prior
4134        // value-laundered "negative duration in \"-30s\"" wording.
4135        //
4136        // Routed through the lifted
4137        // [`crate::render::is_digit_only_magnitude`] predicate — the
4138        // same source of truth the four peer typed-magnitude codec
4139        // sites share.
4140        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
4141        if !digit_only {
4142            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
4143            if numeric {
4144                return Err(format!(
4145                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
4146                     canonical authoring form for the typed duration slots routed through \
4147                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4148                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4149                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
4150                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
4151                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
4152                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
4153                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
4154                     THEORY.md Part V render-determinism contract every typed slot carries. \
4155                     Pick an integer magnitude in the unit that divides cleanly (write \
4156                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
4157                ));
4158            }
4159            return Err(format!("bad duration magnitude in {s:?}"));
4160        }
4161        // Leading-zero arm — peer with the `rate_limit_codec` leading-
4162        // zero arm (4f46830) on the same canonical-form render-
4163        // determinism axis. The digit-only gate accepts `"030s"`,
4164        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
4165        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
4166        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
4167        // *different* canonical string on the next emit, breaking the
4168        // THEORY.md Part V render-determinism contract the same way
4169        // `"+30s"` did before the leading-`+` arm landed. The single-
4170        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
4171        // losslessly through `render` (`render(Duration::ZERO)` emits
4172        // `"0s"`) — the downstream semantic-zero gates (e.g.
4173        // `SupervisorError::ZeroRestartWindow` on
4174        // `:supervisor :restart-window`,
4175        // `AplicacaoError::PolicyTimeoutZero` /
4176        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
4177        // duration slots) refuse zero-magnitude authoring at the typed-
4178        // validate layer above, so the single-byte `"0"` stays in the
4179        // accepted set at this codec layer and the diagnostic
4180        // partitioning between canonical-form drift (this arm) and
4181        // semantic-zero (the downstream gates) remains stable.
4182        // Peer with the future leading-zero arms on the two remaining
4183        // typed-magnitude codecs the trajectory acknowledges:
4184        // `limits::parse_duration` backing `:limits :wall-clock`,
4185        // `limits::parse_byte_size` backing `:limits :memory` — each
4186        // carries the same canonical-form-drift class today; this
4187        // gate lands the discipline on the shared duration codec
4188        // first because the `rate_limit_codec` predecessor on the
4189        // same canonical-form-drift axis is the closest peer on the
4190        // trajectory.
4191        //
4192        // Routed through the lifted
4193        // [`crate::render::is_leading_zero_padded_magnitude`]
4194        // predicate — the same source of truth the four peer
4195        // typed-magnitude codec sites share.
4196        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
4197            return Err(format!(
4198                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
4199                 canonical authoring form for the typed duration slots routed through \
4200                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4201                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4202                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
4203                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
4204                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
4205                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
4206                 serialize — breaking the THEORY.md Part V render-determinism contract \
4207                 every typed slot carries. Strip the leading zeros (write \
4208                 `\"30s\"` instead of `\"030s\"`)"
4209            ));
4210        }
4211        // The digit-only gate guarantees every byte is `[0-9]`, and
4212        // the leading-zero arm above guarantees the magnitude is
4213        // either the single byte `"0"` or starts with `[1-9]`, so
4214        // the only way `u64::from_str` can fail here is overflow (the
4215        // magnitude exceeds `u64::MAX`). Surface that with an
4216        // overflow-shaped wording so the diagnostic names the offending
4217        // magnitude verbatim rather than collapsing onto the
4218        // non-canonical arm. The codec now operates on `u64` end-to-end
4219        // — every accepted magnitude is integer-exact; no f64 mantissa
4220        // drift between author-supplied magnitude and the consumer's
4221        // `Duration` value. Same shape `crate::limits::parse_duration`
4222        // (818dd38) carries on the peer `:limits :wall-clock` axis.
4223        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
4224            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
4225        })?;
4226        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
4227        // unit-arm dispatch through the canonical
4228        // [`crate::render::duration_from_integer_magnitude_and_unit`]
4229        // primitive — the substrate-side single-owner unit-dispatch
4230        // table every typed-duration codec in caixa-core routes
4231        // through (peer: `crate::limits::parse_duration` backing
4232        // `:limits :wall-clock`). Every unit conversion is integer-
4233        // exact for an integer magnitude; overflow surfaces via the
4234        // typed `DurationUnitError::Overflow { multiplier }`
4235        // discriminant so this arm reconstructs the pre-lift
4236        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
4237        // wording verbatim from `num` / `unit_trim` / the returned
4238        // `multiplier`, and the unknown-unit arm reconstructs the
4239        // pre-lift `"unknown duration unit \"<other>\""` wording from
4240        // the caller-scoped `unit_trim`. Load-bearing pinned by
4241        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
4242        let unit_trim = unit.trim();
4243        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
4244            |e| match e {
4245                crate::render::DurationUnitError::Overflow { multiplier } => format!(
4246                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
4247                ),
4248                crate::render::DurationUnitError::UnknownUnit => {
4249                    format!("unknown duration unit {unit_trim:?}")
4250                }
4251            },
4252        )?;
4253        Ok(dur)
4254    }
4255
4256    /// Render a [`Duration`] in the canonical pleme-io duration string
4257    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
4258    /// caixa typed-duration slot serializes to and the same form K8s
4259    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
4260    /// EnvoyConfig per-route timeouts both expect (an integer
4261    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
4262    /// `+`). Lifted to `pub` so caixa-side renderers
4263    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
4264    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
4265    /// emitter, the future caixa-otel collector pipeline emitter) can
4266    /// consume the same canonical formatter without re-inlining the
4267    /// magnitude/unit decision tree (and inheriting the same drift
4268    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
4269    /// downstream apply-time parsing in non-obvious ways).
4270    pub fn render(d: Duration) -> String {
4271        let total_ms = d.as_millis();
4272        if total_ms == 0 {
4273            return "0s".into();
4274        }
4275        if total_ms.is_multiple_of(3600 * 1000) {
4276            return format!("{}h", total_ms / (3600 * 1000));
4277        }
4278        if total_ms.is_multiple_of(60 * 1000) {
4279            return format!("{}m", total_ms / (60 * 1000));
4280        }
4281        if total_ms.is_multiple_of(1000) {
4282            return format!("{}s", total_ms / 1000);
4283        }
4284        format!("{total_ms}ms")
4285    }
4286
4287    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
4288    ///
4289    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
4290    /// largest divisor unit, so any sub-millisecond residue
4291    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
4292    /// §V.2.7 render-determinism contract:
4293    ///
4294    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
4295    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
4296    ///     `1_000_000` ns ≠ original `1_500_000` ns;
4297    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
4298    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
4299    ///     on every typed-`Duration` slot then rejects on re-validate.
4300    ///
4301    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
4302    /// the codec's round-trippable accepted set lives in exactly one place —
4303    /// every typed-`Duration` slot that routes through this shared codec
4304    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
4305    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
4306    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
4307    /// every typed-`Duration` slot whose own codec shares the same
4308    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
4309    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
4310    /// pair) calls this predicate from its `validate()` to bracket the
4311    /// accepted set against the codec's accepted set, structurally. Drift
4312    /// between the codec's granularity and any typed slot's accepted set is
4313    /// then a single-source-of-truth edit at this predicate rather than a
4314    /// silent round-trip break the next consumer discovers at apply time.
4315    ///
4316    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
4317    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
4318    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
4319    /// family — same "typed-slot's valid set matches its codec's accepted
4320    /// set, structurally" discipline carried at the codec layer.
4321    #[must_use]
4322    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
4323        d.subsec_nanos().is_multiple_of(1_000_000)
4324    }
4325}
4326
4327/// Required-Duration variant for fields that aren't Option<Duration>.
4328pub mod duration_codec_required {
4329    use super::Duration;
4330    use serde::{Deserialize, Deserializer, Serializer};
4331
4332    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
4333        s.serialize_str(&super::duration_codec::render(*v))
4334    }
4335
4336    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
4337        let s = String::deserialize(d)?;
4338        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
4339    }
4340}
4341
4342#[cfg(test)]
4343mod tests {
4344    use super::*;
4345
4346    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
4347        ChildSpec {
4348            caixa: name.into(),
4349            versao: ver.into(),
4350            restart,
4351        }
4352    }
4353
4354    #[test]
4355    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
4356        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
4357        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
4358        // posture. Each accessor projects the per-`:children :caixa`
4359        // / per-`:children :versao` [`String`] storage through the
4360        // `pub const fn` [`String::as_str`] (const-stable since Rust
4361        // 1.87, well within the workspace MSRV) — any future
4362        // accidental downgrade to non-`const` fails the corresponding
4363        // `<name>_via_const_fn` wrapper at caixa-core build time with
4364        // E0015 (`cannot call non-const method`), strictly stronger
4365        // than a runtime `assert!`. Sibling of the peer
4366        // per-M2/M3/universal-axis `String → &str` scalar-accessor
4367        // family pins on the sibling `const`-eval-surface passes
4368        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
4369        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
4370        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
4371        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
4372        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
4373        // [`crate::aplicacao::Entrada::destination`] at the M3
4374        // ingress axis,
4375        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
4376        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
4377        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
4378        // axis, and the per-`:contratos`
4379        // [`crate::aplicacao::WitContract::source`] /
4380        // [`crate::aplicacao::WitContract::destination`] /
4381        // [`crate::aplicacao::WitContract::world_ref`] trio the
4382        // sibling pin at 279823b already anchors).
4383        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
4384            c.nome()
4385        }
4386        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
4387            c.versao_requirement()
4388        }
4389        for (caixa, versao) in [
4390            ("worker-a", "^0.1"),
4391            ("worker-b", "~0.2.3"),
4392            ("collector", "*"),
4393        ] {
4394            let c = child(caixa, versao, RestartPolicy::Permanent);
4395            assert_eq!(nome_via_const_fn(&c), c.nome());
4396            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
4397            assert_eq!(c.nome(), caixa);
4398            assert_eq!(c.versao_requirement(), versao);
4399        }
4400    }
4401
4402    #[test]
4403    fn supervisor_children_slice_return_accessor_is_const_fn() {
4404        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
4405        // `const`-eval-surface posture. The accessor destructures the
4406        // per-`:children` `Vec<ChildSpec>` storage through the
4407        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
4408        // 1.66, well within the workspace MSRV) — any future
4409        // accidental downgrade to non-`const` fails
4410        // `children_via_const_fn` at caixa-core build time with E0015
4411        // (`cannot call non-const method`), strictly stronger than a
4412        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
4413        // `Vec → &[T]` slice-return accessor family pin
4414        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
4415        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
4416        // per-`:membros` / per-`:contratos` slice-return axes, and of
4417        // the peer M2 upgrade-appup axis pin
4418        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
4419        // on the per-`:upgrade-from :instructions` slice-return axis.
4420        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
4421            s.children()
4422        }
4423        // Sweep both the empty-children (leaf-supervisor with no
4424        // static children — the `SimpleOneForOne` dynamic-child
4425        // arm's canonical shape) and the populated-children
4426        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
4427        // arm's canonical shape) axes so the accessor carries a
4428        // const-dispatch pin on both arms.
4429        let s_empty = SupervisorSpec {
4430            estrategia: RestartStrategy::SimpleOneForOne,
4431            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4432            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4433            children: vec![],
4434        };
4435        assert!(children_via_const_fn(&s_empty).is_empty());
4436        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
4437        let s_full = SupervisorSpec {
4438            estrategia: RestartStrategy::OneForOne,
4439            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4440            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4441            children: vec![
4442                child("worker-a", "^0.1", RestartPolicy::Permanent),
4443                child("worker-b", "~0.2.3", RestartPolicy::Transient),
4444                child("collector", "*", RestartPolicy::Temporary),
4445            ],
4446        };
4447        assert_eq!(children_via_const_fn(&s_full).len(), 3);
4448        assert_eq!(children_via_const_fn(&s_full), s_full.children());
4449    }
4450
4451    #[test]
4452    fn default_has_one_for_one_and_5_restarts_in_60s() {
4453        let s = SupervisorSpec::default();
4454        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
4455        assert_eq!(s.max_restarts, 5);
4456        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
4457        assert!(s.children.is_empty());
4458    }
4459
4460    #[test]
4461    fn validate_one_for_one_requires_children() {
4462        let mut s = SupervisorSpec::default();
4463        s.children = vec![];
4464        assert!(matches!(
4465            s.validate().unwrap_err(),
4466            SupervisorError::NoChildren { .. }
4467        ));
4468        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
4469        s.validate().unwrap();
4470    }
4471
4472    #[test]
4473    fn validate_simple_one_for_one_forbids_static_children() {
4474        let mut s = SupervisorSpec {
4475            estrategia: RestartStrategy::SimpleOneForOne,
4476            ..SupervisorSpec::default()
4477        };
4478        s.children
4479            .push(child("w", "^0.1", RestartPolicy::Permanent));
4480        assert_eq!(
4481            s.validate().unwrap_err(),
4482            SupervisorError::SimpleOneForOneWithStaticChildren
4483        );
4484        s.children.clear();
4485        s.validate().unwrap();
4486    }
4487
4488    #[test]
4489    fn validate_rejects_zero_max_restarts() {
4490        let s = SupervisorSpec {
4491            max_restarts: 0,
4492            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4493            ..SupervisorSpec::default()
4494        };
4495        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
4496    }
4497
4498    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
4499    //
4500    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
4501    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
4502    // `:supervisor :max-restarts` axis — both fields are "trip the
4503    // next-higher protection layer after N events in a rolling window"
4504    // counters with identical degenerate-at-the-high-end shape, so the
4505    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
4506    // exactly as it lies in `1..=1000` on the breaker side.
4507
4508    #[test]
4509    fn validate_rejects_max_restarts_above_cap() {
4510        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
4511        // 1` is structurally one past the cap and silently passed
4512        // validate on every pre-gate codebase because the typed slot's
4513        // only check was the zero-floor arm. The no-op-supervisor vector
4514        // only surfaced at the runtime substrate (Erlang/OTP
4515        // MaxIntensity/Period ratio, the future wasm-operator's
4516        // per-supervisor restart-intensity counter) far from the source
4517        // caixa.lisp with no field naming the offending supervisor.
4518        let s = SupervisorSpec {
4519            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4520            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4521            ..SupervisorSpec::default()
4522        };
4523        assert_eq!(
4524            s.validate().unwrap_err(),
4525            SupervisorError::MaxRestartsExceedsCap {
4526                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4527            }
4528        );
4529    }
4530
4531    #[test]
4532    fn validate_rejects_max_restarts_far_above_cap() {
4533        // The `u32::MAX` worst case — the four-billion-restart
4534        // threshold a typo (`:max-restarts 4294967295`) or a
4535        // struct-literal copy-paste lands in the slot. Pin the cap
4536        // arm's coverage explicitly across the full `u32` overflow so
4537        // a future relaxation that drops the upper bound surfaces
4538        // here. Same shape every other typed-cap arm on this surface
4539        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
4540        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
4541        let s = SupervisorSpec {
4542            max_restarts: u32::MAX,
4543            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4544            ..SupervisorSpec::default()
4545        };
4546        assert_eq!(
4547            s.validate().unwrap_err(),
4548            SupervisorError::MaxRestartsExceedsCap {
4549                max_restarts: u32::MAX,
4550            }
4551        );
4552    }
4553
4554    #[test]
4555    fn validate_accepts_max_restarts_at_cap() {
4556        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
4557        // must validate. The cap is inclusive on the top edge,
4558        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
4559        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
4560        // discipline on the sibling capped axes. Pin the boundary
4561        // explicitly so a future off-by-one tightening
4562        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
4563        // here as a test failure rather than a silent contract
4564        // narrowing.
4565        let s = SupervisorSpec {
4566            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
4567            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4568            ..SupervisorSpec::default()
4569        };
4570        s.validate()
4571            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
4572    }
4573
4574    #[test]
4575    fn validate_accepts_max_restarts_typical_values() {
4576        // The documented production-playbook band positive-control
4577        // sweep — every value Erlang/OTP / Elixir / Riak Core /
4578        // RabbitMQ recommend (1..=100) must pass, plus a sweep
4579        // through the hyperscale band (200, 500, 1000) the cap
4580        // accepts. Pin the inclusive validated set explicitly so a
4581        // future tightening of the ceiling surfaces here.
4582        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
4583            let s = SupervisorSpec {
4584                max_restarts: n,
4585                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4586                ..SupervisorSpec::default()
4587            };
4588            s.validate()
4589                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
4590        }
4591    }
4592
4593    #[test]
4594    fn zero_max_restarts_takes_precedence_over_cap() {
4595        // The cross-arm ordering pin: `0` is structurally outside
4596        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
4597        // (cap), but the zero-floor diagnostic is the more
4598        // self-locating one (it directly names the counter-axis
4599        // remediation), so the validate gate must fire on zero first.
4600        // Same shape every other zero-then-shape ordering on this
4601        // surface uses (PolicyRetriesZero then
4602        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
4603        // PolicyBreakerMaxFailuresExceedsCap).
4604        let s = SupervisorSpec {
4605            max_restarts: 0,
4606            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4607            ..SupervisorSpec::default()
4608        };
4609        assert_eq!(
4610            s.validate().unwrap_err(),
4611            SupervisorError::ZeroMaxRestarts,
4612            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
4613        );
4614    }
4615
4616    #[test]
4617    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
4618        // The cross-arm ordering pin between the cap and the sibling
4619        // `:restart-window` gates (zero-window, canonical-window). A
4620        // supervisor carrying both an over-cap `max_restarts` AND a
4621        // structurally invalid window (zero, sub-ms) must surface the
4622        // cap diagnostic first — the cap arm is wired immediately
4623        // after the zero-restart arm and strictly before the window
4624        // arms, so the offending value the diagnostic names matches
4625        // the order the author would discover the gates by reading
4626        // top-to-bottom through `SupervisorSpec::validate`. Pin the
4627        // order so a future refactor that reorders the arms surfaces
4628        // here as a test failure rather than a silent diagnostic
4629        // regression. Peer of
4630        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
4631        // on the sibling `:politicas :circuit-breaker` slot.
4632        let s = SupervisorSpec {
4633            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4634            restart_window: Some(Duration::ZERO),
4635            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4636            ..SupervisorSpec::default()
4637        };
4638        assert_eq!(
4639            s.validate().unwrap_err(),
4640            SupervisorError::MaxRestartsExceedsCap {
4641                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4642            },
4643            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4644        );
4645    }
4646
4647    #[test]
4648    fn max_restarts_cap_diagnostic_carries_offending_value() {
4649        // The diagnostic-shape pin: the offending `u32` is carried
4650        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
4651        // variant so the surfaced error message names the value the
4652        // author wrote (`":supervisor :max-restarts (50000) exceeds the
4653        // supervisor-policy ceiling …"`), not just the cap. Same
4654        // self-locating diagnostic shape every other typed-cap arm on
4655        // this surface carries
4656        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
4657        // the offending failure count verbatim,
4658        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
4659        // retries count verbatim).
4660        let s = SupervisorSpec {
4661            max_restarts: 50_000,
4662            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4663            ..SupervisorSpec::default()
4664        };
4665        let err = s.validate().unwrap_err();
4666        assert!(
4667            matches!(
4668                err,
4669                SupervisorError::MaxRestartsExceedsCap {
4670                    max_restarts: 50_000
4671                }
4672            ),
4673            "got {err:?}"
4674        );
4675        let msg = err.to_string();
4676        assert!(
4677            msg.contains("50000"),
4678            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
4679        );
4680    }
4681
4682    #[test]
4683    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
4684        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
4685        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
4686        // half of Learn You Some Erlang's worker-supervisor default,
4687        // sibling of the `60s` `Period` half that the paired
4688        // [`Default for SupervisorSpec`] impl already pins on the
4689        // sibling `restart_window` axis. Pinning the literal here
4690        // surfaces a future rebrand (a tightening to Elixir's `3`,
4691        // a widening to a per-cluster overlay the operator pins
4692        // through a future `:max-restarts-overrides` slot) as a
4693        // deliberate test edit, not a silent contract migration.
4694        // Peer of the sibling
4695        // [`supervisor_max_restarts_cap_pins_canonical_value`]
4696        // upper-bracket pin on the same axis.
4697        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
4698    }
4699
4700    #[test]
4701    fn default_max_restarts_helper_routes_through_lifted_default() {
4702        // Composition pin: the private `default_max_restarts()`
4703        // serde-`#[serde(default = "…")]` helper on
4704        // [`SupervisorSpec::max_restarts`] must route through the
4705        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4706        // typed `pub const` rather than a raw `5` literal. Prior to
4707        // the lift the helper carried an inline `5` with no compile-
4708        // time link back to the shared default, so the wire-format
4709        // author-omitted arm and the caixa-core
4710        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
4711        // arm could silently split on any future default rebrand.
4712        // Byte-parity against the lifted constant closes the split.
4713        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
4714    }
4715
4716    #[test]
4717    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
4718        // Composition pin: the [`Default for SupervisorSpec`] impl's
4719        // struct-literal `max_restarts` field must route through the
4720        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4721        // typed `pub const` (via the private helper this test's
4722        // sibling `default_max_restarts_helper_routes_through_lifted_default`
4723        // already pins onto the constant). Structurally: every
4724        // `SupervisorSpec::default()` call must yield a
4725        // `max_restarts` field byte-equal to the lifted constant
4726        // (the two paired defaults — the serde-side wire-format arm
4727        // and the struct-literal default arm — cannot silently split
4728        // on any future default rebrand). Peer of the sibling
4729        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
4730        // — this pin closes the byte-parity arm on the two paired
4731        // altitude entry points onto the shared substrate constant.
4732        assert_eq!(
4733            SupervisorSpec::default().max_restarts(),
4734            SUPERVISOR_MAX_RESTARTS_DEFAULT,
4735        );
4736    }
4737
4738    #[test]
4739    fn supervisor_restart_window_default_pins_otp_canonical_value() {
4740        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
4741        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
4742        // Learn You Some Erlang's worker-supervisor default, paired
4743        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
4744        // `MaxIntensity` half this constant is the sliding-window
4745        // denominator of on the same `MaxIntensity / Period`
4746        // restart-intensity ratio. Pinning the literal here surfaces a
4747        // future coherent rebrand of the paired default (Elixir's
4748        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
4749        // the operator pins through a future
4750        // `:restart-window-overrides` slot) as a deliberate test edit,
4751        // not a silent contract migration. Peer of the sibling
4752        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
4753        // paired-half pin on the same OTP-canonical default and the
4754        // [`supervisor_restart_window_cap_pins_canonical_value`]
4755        // upper-bracket pin on the same axis.
4756        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
4757    }
4758
4759    #[test]
4760    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
4761        // Composition pin: the [`Default for SupervisorSpec`] impl's
4762        // struct-literal `restart_window` field must route through the
4763        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4764        // typed `pub const` rather than a raw
4765        // `Duration::from_secs(60)` literal. Prior to this lift the
4766        // paired `{intensity, 5, 60}` OTP-canonical default was split
4767        // across two altitudes with no compile-time link between the
4768        // halves — the `MaxIntensity` half rode through the lifted
4769        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
4770        // `Period` half rode as an open-coded literal at the
4771        // composition site, so a future coherent rebrand of the paired
4772        // canonical would have had to migrate one half through the
4773        // constant and the other through a raw literal in lockstep.
4774        // Byte-parity against the lifted constant on the `Period` half
4775        // closes the split — the paired OTP-canonical default now
4776        // migrates as one unit on any future axis change. Peer of the
4777        // sibling
4778        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4779        // byte-parity pin on the paired `MaxIntensity` half.
4780        assert_eq!(
4781            SupervisorSpec::default().restart_window(),
4782            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4783        );
4784    }
4785
4786    #[test]
4787    fn supervisor_estrategia_default_pins_otp_canonical_value() {
4788        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
4789        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
4790        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
4791        // canonical default, paired with the sibling
4792        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
4793        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
4794        // this constant is the strategy discriminator of on the same
4795        // OTP-canonical worker-supervisor default. Pinning the arm here
4796        // surfaces a future coherent rebrand of the paired triple (Elixir's
4797        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
4798        // intensity/period axes leaving this strategy arm untouched, an OTP
4799        // `rest_for_one` widening once the substrate discovers startup-
4800        // order-coupled child cohorts as the more common worker-supervisor
4801        // shape, a per-cluster overlay the operator pins through a future
4802        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
4803        // supervision-canary roadmap acknowledges) as a deliberate test
4804        // edit, not a silent contract migration. Peer of the sibling
4805        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
4806        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4807        // paired-half pins on the same OTP-canonical default.
4808        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
4809    }
4810
4811    #[test]
4812    fn restart_strategy_default_routes_through_lifted_default() {
4813        // Composition pin: the [`Default for RestartStrategy`] impl's
4814        // return arm must route through the substrate-canonical
4815        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
4816        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
4817        // an inline `Self::OneForOne` with no compile-time link back to
4818        // the shared OTP-canonical `one_for_one` strategy the paired
4819        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
4820        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
4821        // `.unwrap_or_default()` (now
4822        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
4823        // so a future rebrand of the OTP-canonical strategy default (an
4824        // OTP `rest_for_one` widening once the substrate discovers
4825        // startup-order-coupled child cohorts as the more common worker-
4826        // supervisor shape, a per-cluster overlay the operator pins
4827        // through a future `:estrategia-overrides` slot) would have had to
4828        // be threaded through the `Default` impl and the two peer routes
4829        // in lockstep or the three consumers would silently split. Byte-
4830        // parity against the lifted constant closes the split. Peer of
4831        // the sibling
4832        // [`default_max_restarts_helper_routes_through_lifted_default`] +
4833        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4834        // composition pins on the paired `MaxIntensity` + `Period` halves.
4835        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
4836    }
4837
4838    #[test]
4839    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
4840        // Composition pin: the [`Default for SupervisorSpec`] impl's
4841        // struct-literal `estrategia` field must route through the
4842        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
4843        // `pub const` (either directly, or via the
4844        // [`RestartStrategy::default`] impl that the sibling
4845        // `restart_strategy_default_routes_through_lifted_default` pin
4846        // already routes onto the constant). Structurally: every
4847        // `SupervisorSpec::default()` call must yield an `estrategia`
4848        // field byte-equal to the lifted constant (the three paired
4849        // defaults — the [`Default for RestartStrategy`] impl arm, the
4850        // struct-literal default arm here, and the
4851        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
4852        // silently split on any future default rebrand). Peer of the
4853        // sibling
4854        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4855        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4856        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
4857        // of the same `SupervisorSpec::default()` composed altitude.
4858        assert_eq!(
4859            SupervisorSpec::default().estrategia(),
4860            SUPERVISOR_ESTRATEGIA_DEFAULT,
4861        );
4862    }
4863
4864    #[test]
4865    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
4866        // Composition pin: the [`Default for SupervisorSpec`] impl must
4867        // route through the substrate-canonical
4868        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
4869        // rather than a re-hand-authored struct-literal cascade. Sharpens
4870        // the sibling per-arm
4871        // `supervisor_spec_default_*_routes_through_lifted_default` pins
4872        // from a per-field lift into a whole-struct one-source-of-truth
4873        // pin — the derived-until-now [`Default::default`] and the
4874        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
4875        // construction, not by coincidence.
4876        //
4877        // A future extension of the OTP-canonical baseline (a fifth
4878        // `restart_intensity` field the Erlang/OTP `#supervisor` record
4879        // grows, a per-child-cohort split of the `restart_window` /
4880        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
4881        // CR materializer's admission-time overlay pass) reaches both
4882        // paths through exactly one edit on
4883        // [`SupervisorSpec::otp_canonical`] — the derived path could
4884        // silently disagree with the constructor's shape on any new
4885        // field whose [`Default::default`] resolves to a different arm
4886        // than the OTP-canonical baseline the constructor names, while
4887        // this delegated impl reaches the constructor directly and
4888        // picks up every future extension by construction.
4889        //
4890        // Fourth peer on the M2 / M3 typed-slot-spec
4891        // [`Default`]-through-const-ctor fold family — sibling of the
4892        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
4893        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
4894        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
4895        // (91641a4), and [`crate::BehaviorSpec`]
4896        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
4897        // per-`Option`-only-typed-slot folds — extended here onto the
4898        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
4899        // is not "everything `None`" but the Erlang/OTP-canonical
4900        // `{one_for_one, 5, 60}` worker-supervisor triple.
4901        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
4902    }
4903
4904    #[test]
4905    fn supervisor_spec_otp_canonical_byte_equals_default() {
4906        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
4907        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
4908        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
4909        // pin already asserts against the [`Default::default`] path.
4910        // Sharpens the pair-invariant into a per-constructor pin so a
4911        // future extension of [`SupervisorSpec`] with a fifth field
4912        // whose OTP-canonical shape is non-`Default::default`-equivalent
4913        // trips at caixa-core test time rather than at a downstream
4914        // consumer that composed [`SupervisorSpec::otp_canonical`] with
4915        // [`SupervisorSpec::validate`] as its "canonical baseline
4916        // seed".
4917        let canonical = SupervisorSpec::otp_canonical();
4918        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
4919        assert_eq!(canonical.max_restarts, 5);
4920        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
4921        assert!(canonical.children.is_empty());
4922    }
4923
4924    #[test]
4925    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
4926        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
4927        // remain callable from a `const`-bound position so downstream
4928        // `const`-context callers wanting a canonical OTP-baseline seed
4929        // can construct one at compile time without runtime dispatch on
4930        // the derived [`Default::default`]. Peer of the sibling
4931        // `pub const fn` [`crate::LimitsSpec::empty`] /
4932        // [`crate::aplicacao::MeshPolicy::empty`] /
4933        // [`crate::BehaviorSpec::empty`] constructors on the sibling
4934        // typed-slot-spec `pub const fn` axis. If a future edit breaks
4935        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
4936        // (a non-`const` field-default helper, a non-`const`-stable
4937        // container type promotion), this evaluation fails at
4938        // build time on this file rather than at a downstream
4939        // `const`-context call site.
4940        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
4941        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
4942        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
4943        assert_eq!(
4944            CANONICAL.restart_window,
4945            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4946        );
4947        assert!(CANONICAL.children.is_empty());
4948    }
4949
4950    #[test]
4951    fn supervisor_child_restart_default_pins_otp_canonical_value() {
4952        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
4953        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
4954        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
4955        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
4956        // half of the same OTP-shape supervisor-tree default set whose
4957        // per-`:supervisor` halves the sibling
4958        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
4959        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
4960        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
4961        // arm here surfaces a future rebrand of the per-child default (an
4962        // OTP-`transient` widening once the substrate discovers clean-
4963        // completion-aware children as the more common child shape, a
4964        // per-cluster overlay the operator pins through a future
4965        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
4966        // supervision-canary roadmap acknowledges) as a deliberate test
4967        // edit, not a silent contract migration. Peer of the sibling
4968        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
4969        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
4970        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4971        // value pins on the per-`:supervisor` halves.
4972        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
4973    }
4974
4975    #[test]
4976    fn restart_policy_default_routes_through_lifted_default() {
4977        // Composition pin: the [`Default for RestartPolicy`] impl's return
4978        // arm must route through the substrate-canonical
4979        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
4980        // than a raw `Self::Permanent` arm. Prior to the lift the impl
4981        // carried an inline `Self::Permanent` with no compile-time link
4982        // back to the OTP-shape supervisor-tree default set whose three
4983        // per-`:supervisor` halves already rode through lifted constants
4984        // — so a future coherent rebrand of the set would have had to
4985        // migrate three halves through typed constants and this fourth
4986        // through a raw enum arm in lockstep or the supervisor-level and
4987        // child-level defaults would silently drift apart. Byte-parity
4988        // against the lifted constant closes the split. Peer of the
4989        // sibling
4990        // [`restart_strategy_default_routes_through_lifted_default`]
4991        // composition pin on the per-`:supervisor` `:estrategia` axis.
4992        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
4993    }
4994
4995    #[test]
4996    fn child_spec_serde_default_restart_routes_through_lifted_default() {
4997        // Composition pin: the serde-side `#[serde(default)]` on
4998        // [`ChildSpec::restart`] — the wire-format author-omitted
4999        // `:children :restart` arm — must resolve onto the substrate-
5000        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
5001        // (via the [`Default for RestartPolicy`] impl the sibling
5002        // `restart_policy_default_routes_through_lifted_default` pin
5003        // already routes onto the constant). Structurally: a `ChildSpec`
5004        // deserialized from a payload that omits the `restart` key must
5005        // yield a `restart` field byte-equal to the lifted constant, so
5006        // the wire-format author-omitted arm and the
5007        // [`RestartPolicy::default`] impl arm cannot silently split on any
5008        // future default rebrand. Peer of the sibling
5009        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
5010        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5011        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5012        // byte-parity pins on the per-`:supervisor` halves of the same
5013        // author-omitted-slot resolution surface.
5014        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
5015            .expect("ChildSpec must deserialize with the restart key omitted");
5016        assert_eq!(
5017            omitted.restart(),
5018            SUPERVISOR_CHILD_RESTART_DEFAULT,
5019            "an author-omitted :children :restart slot must degrade onto \
5020             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
5021             {:?}, expected {:?})",
5022            omitted.restart(),
5023            SUPERVISOR_CHILD_RESTART_DEFAULT,
5024        );
5025    }
5026
5027    #[test]
5028    fn supervisor_max_restarts_cap_pins_canonical_value() {
5029        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
5030        // 1000 — the same ceiling the peer
5031        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
5032        // `:politicas :circuit-breaker :max-failures` axis (both are
5033        // "trip the next-higher protection layer after N events in a
5034        // rolling window" counters with identical
5035        // degenerate-at-the-high-end shape; uniform top edge so the
5036        // M4 CR materializers and the wasm-operator reconciler reach
5037        // for either field knowing the value is in `1..=1000`). Two
5038        // orders of magnitude above every documented Erlang/OTP /
5039        // Elixir / Riak Core / RabbitMQ production-playbook
5040        // recommendation band and below the clearly-pathological
5041        // "effectively no escalation" floor (10_000, 100_000,
5042        // u32::MAX). Pinning the literal value here surfaces a future
5043        // drift (a relaxation to 10_000, a tightening to 100) as a
5044        // deliberate test edit, not a silent contract narrowing.
5045        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
5046    }
5047
5048    #[test]
5049    fn validate_rejects_empty_child_name() {
5050        let s = SupervisorSpec {
5051            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5052            ..SupervisorSpec::default()
5053        };
5054        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
5055    }
5056
5057    #[test]
5058    fn validate_rejects_empty_child_version() {
5059        let s = SupervisorSpec {
5060            children: vec![child("w", "", RestartPolicy::Permanent)],
5061            ..SupervisorSpec::default()
5062        };
5063        assert!(matches!(
5064            s.validate().unwrap_err(),
5065            SupervisorError::EmptyChildVersion { .. }
5066        ));
5067    }
5068
5069    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
5070
5071    #[test]
5072    fn validate_rejects_invalid_child_versao_requirement() {
5073        // The fail-before-pass-after pin: a non-empty but malformed
5074        // semver requirement (`"^bad-version"`) silently passed
5075        // `validate()` on every pre-gate codebase because the prior
5076        // shape only refused the empty string. The parse failure
5077        // surfaced far downstream at lacre-resolve time with a
5078        // `semver::Error` that didn't name which `:children` entry
5079        // carried the typo. The new gate moves the check to caixa-build
5080        // time at the source caixa.lisp — the third `:versao` typed
5081        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
5082        // structural parity.
5083        let s = SupervisorSpec {
5084            children: vec![
5085                child("worker", "^0.1", RestartPolicy::Permanent),
5086                child("cache", "^bad-version", RestartPolicy::Transient),
5087            ],
5088            ..SupervisorSpec::default()
5089        };
5090        let err = s.validate().unwrap_err();
5091        assert!(
5092            matches!(
5093                err,
5094                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5095                    if caixa == "cache" && versao == "^bad-version"
5096            ),
5097            "got {err:?}"
5098        );
5099    }
5100
5101    #[test]
5102    fn validate_rejects_child_versao_with_double_caret_typo() {
5103        // `"^^0.1"` is the canonical doubled-caret typo — looks
5104        // Cargo-shaped on first glance but fails the parser because
5105        // semver doesn't accept stacked operators. Pin this
5106        // adjacent-shape footgun explicitly so a future relaxation that
5107        // accepts "looks-canonical-but-isn't" forms surfaces here.
5108        let s = SupervisorSpec {
5109            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
5110            ..SupervisorSpec::default()
5111        };
5112        let err = s.validate().unwrap_err();
5113        assert!(
5114            matches!(
5115                err,
5116                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5117                    if caixa == "worker" && versao == "^^0.1"
5118            ),
5119            "got {err:?}"
5120        );
5121    }
5122
5123    #[test]
5124    fn validate_rejects_child_versao_with_v_prefixed_tag() {
5125        // `"v0.1"` is the canonical "git-tag-shape leaking into the
5126        // semver requirement slot" typo — an author copies the
5127        // publish-side git-tag string verbatim into `:versao`, but
5128        // Cargo's semver parser rejects the leading `v`. Same
5129        // adjacent-shape footgun pinned for `:membros :versao`
5130        // (9888b13).
5131        let s = SupervisorSpec {
5132            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
5133            ..SupervisorSpec::default()
5134        };
5135        let err = s.validate().unwrap_err();
5136        assert!(
5137            matches!(
5138                err,
5139                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5140                    if caixa == "worker" && versao == "v0.1"
5141            ),
5142            "got {err:?}"
5143        );
5144    }
5145
5146    #[test]
5147    fn validate_accepts_canonical_child_versao_forms() {
5148        // The Cargo-shaped requirement forms `:deps :versao` and
5149        // `:membros :versao` already accept via
5150        // `crate::parse_requirement` must pass the children gate
5151        // without re-validating at the resolver layer. Pin every leg so
5152        // a future tightening of the canonical set surfaces here as a
5153        // test failure.
5154        for form in [
5155            "^0.1",      // caret — minor-range pin (the most common shape)
5156            "~0.1.2",    // tilde — patch-range pin
5157            "0.1.0",     // exact — single-version pin
5158            "*",         // wildcard — any version (semver::VersionReq::STAR)
5159            ">=0.1, <2", // multi-range — comma-separated comparators
5160        ] {
5161            let s = SupervisorSpec {
5162                children: vec![child("worker", form, RestartPolicy::Permanent)],
5163                ..SupervisorSpec::default()
5164            };
5165            s.validate()
5166                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5167        }
5168    }
5169
5170    #[test]
5171    fn child_versao_empty_takes_precedence_over_invalid() {
5172        // Order pin: the existing `EmptyChildVersion` diagnostic (which
5173        // doesn't try to parse) fires before the new
5174        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
5175        // `:versao` keeps its narrower error message —
5176        // `parse_requirement` would also reject `""`, but the
5177        // empty-string arm is the more self-locating diagnostic for the
5178        // author. Same ordering discipline as
5179        // `membro_versao_empty_takes_precedence_over_invalid` in
5180        // aplicacao.rs.
5181        let s = SupervisorSpec {
5182            children: vec![child("worker", "", RestartPolicy::Permanent)],
5183            ..SupervisorSpec::default()
5184        };
5185        let err = s.validate().unwrap_err();
5186        assert!(
5187            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
5188            "got {err:?}"
5189        );
5190    }
5191
5192    #[test]
5193    fn child_versao_invalid_fires_before_duplicate_check() {
5194        // Order pin: a malformed requirement on a non-duplicate entry
5195        // surfaces *its own* diagnostic (which names the offending
5196        // `:versao` string), even when a later entry would otherwise
5197        // collapse onto an earlier name. The per-entry shape gate runs
5198        // inline before the duplicate-key insert — parallel to
5199        // `membro_versao_invalid_fires_before_duplicate_check` in
5200        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
5201        let s = SupervisorSpec {
5202            children: vec![
5203                child("worker", "^bad", RestartPolicy::Permanent),
5204                child("cache", "^0.1", RestartPolicy::Transient),
5205                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5206            ],
5207            ..SupervisorSpec::default()
5208        };
5209        let err = s.validate().unwrap_err();
5210        assert!(
5211            matches!(
5212                err,
5213                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
5214            ),
5215            "got {err:?}"
5216        );
5217    }
5218
5219    #[test]
5220    fn child_versao_invalid_diagnostic_carries_offending_versao() {
5221        // The diagnostic-shape pin: the error names the offending
5222        // `:versao` value verbatim so the author can grep their
5223        // caixa.lisp without re-running the build, and carries a
5224        // non-empty `reason` from `semver::VersionReq::parse` so the
5225        // parser's own wording flows through to the diagnostic.
5226        let s = SupervisorSpec {
5227            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
5228            ..SupervisorSpec::default()
5229        };
5230        let err = s.validate().unwrap_err();
5231        let SupervisorError::ChildVersaoInvalid {
5232            caixa,
5233            versao,
5234            reason,
5235        } = err
5236        else {
5237            panic!("expected ChildVersaoInvalid, got other variant");
5238        };
5239        assert_eq!(caixa, "worker");
5240        assert_eq!(versao, "not-a-req");
5241        assert!(
5242            !reason.is_empty(),
5243            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
5244        );
5245    }
5246
5247    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
5248
5249    #[test]
5250    fn validate_rejects_child_caixa_with_uppercase() {
5251        // The canonical "I copied the Servico's display name verbatim"
5252        // typo — child caixa names are lowercase per K8s DNS-1123 label
5253        // rule. The diagnostic names the offending name and suggests the
5254        // lower-cased fix in one edit, mirroring the
5255        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
5256        let s = SupervisorSpec {
5257            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
5258            ..SupervisorSpec::default()
5259        };
5260        let err = s.validate().unwrap_err();
5261        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5262            panic!("expected ChildCaixaInvalid, got other variant");
5263        };
5264        assert_eq!(caixa, "Worker");
5265        assert!(
5266            reason.contains("uppercase"),
5267            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
5268        );
5269        assert!(
5270            reason.contains("\"worker\""),
5271            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
5272        );
5273    }
5274
5275    #[test]
5276    fn validate_rejects_child_caixa_with_underscore() {
5277        // The canonical "I'm thinking of a Python module / Postgres
5278        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
5279        // label schema. K8s rejects `metadata.name: my_worker` at
5280        // admission time with an opaque `field is invalid` (no source-
5281        // citing diagnostic). The gate moves it to caixa-build time.
5282        let s = SupervisorSpec {
5283            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
5284            ..SupervisorSpec::default()
5285        };
5286        let err = s.validate().unwrap_err();
5287        assert!(
5288            matches!(
5289                err,
5290                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5291                    if caixa == "my_worker" && reason.contains('_')
5292            ),
5293            "got {err:?}"
5294        );
5295    }
5296
5297    #[test]
5298    fn validate_rejects_child_caixa_with_dot() {
5299        // A `:children :caixa` entry is a single DNS-1123 label, not a
5300        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
5301        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
5302        // (3f9d7a0) on the peer name axis.
5303        let s = SupervisorSpec {
5304            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
5305            ..SupervisorSpec::default()
5306        };
5307        let err = s.validate().unwrap_err();
5308        assert!(
5309            matches!(
5310                err,
5311                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5312                    if caixa == "team.worker" && reason.contains('.')
5313            ),
5314            "got {err:?}"
5315        );
5316    }
5317
5318    #[test]
5319    fn validate_rejects_child_caixa_with_leading_hyphen() {
5320        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
5321        // with an alphanumeric. The K8s apiserver rejects `-worker`
5322        // outright; the renderer would emit a `metadata.name: "-worker"`
5323        // that fails admission far from the source caixa.lisp.
5324        let s = SupervisorSpec {
5325            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
5326            ..SupervisorSpec::default()
5327        };
5328        let err = s.validate().unwrap_err();
5329        assert!(
5330            matches!(
5331                err,
5332                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5333                    if caixa == "-worker" && reason.contains("start and end")
5334            ),
5335            "got {err:?}"
5336        );
5337    }
5338
5339    #[test]
5340    fn validate_rejects_child_caixa_with_trailing_hyphen() {
5341        // The symmetric arm of the boundary rule. Pin separately so
5342        // both ends of the label are covered against a future relaxation
5343        // that only checks one boundary.
5344        let s = SupervisorSpec {
5345            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
5346            ..SupervisorSpec::default()
5347        };
5348        let err = s.validate().unwrap_err();
5349        assert!(
5350            matches!(
5351                err,
5352                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5353                    if caixa == "worker-"
5354            ),
5355            "got {err:?}"
5356        );
5357    }
5358
5359    #[test]
5360    fn validate_rejects_child_caixa_with_unicode() {
5361        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
5362        // (`xn--…`) by the author before it reaches K8s. The byte-by-
5363        // byte ASCII validity check rejects multi-byte UTF-8 sequences
5364        // by the first byte that fails the `[a-z0-9-]` predicate.
5365        let s = SupervisorSpec {
5366            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
5367            ..SupervisorSpec::default()
5368        };
5369        let err = s.validate().unwrap_err();
5370        assert!(
5371            matches!(
5372                err,
5373                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5374                    if caixa == "café"
5375            ),
5376            "got {err:?}"
5377        );
5378    }
5379
5380    #[test]
5381    fn validate_rejects_child_caixa_with_whitespace() {
5382        // Whitespace is the canonical "I pasted from a sketch / doc"
5383        // footgun. The apiserver rejects every `metadata.name` value
5384        // carrying whitespace; pin the gate fires at the right boundary.
5385        let s = SupervisorSpec {
5386            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
5387            ..SupervisorSpec::default()
5388        };
5389        let err = s.validate().unwrap_err();
5390        assert!(
5391            matches!(
5392                err,
5393                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5394                    if caixa == "my worker"
5395            ),
5396            "got {err:?}"
5397        );
5398    }
5399
5400    #[test]
5401    fn validate_rejects_child_caixa_too_long() {
5402        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
5403        // 63 bytes; the K8s apiserver rejects every `metadata.name`
5404        // axis over the limit at admission time. The diagnostic names
5405        // both the cap and the actual length so the author can shorten
5406        // in one edit, mirroring `rejects_membro_caixa_too_long`
5407        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
5408        let too_long = "a".repeat(64);
5409        let s = SupervisorSpec {
5410            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
5411            ..SupervisorSpec::default()
5412        };
5413        let err = s.validate().unwrap_err();
5414        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5415            panic!("expected ChildCaixaInvalid, got other variant");
5416        };
5417        assert_eq!(caixa, too_long);
5418        assert!(
5419            reason.contains("63"),
5420            "diagnostic must name the 63-byte cap (got: {reason:?})"
5421        );
5422        assert!(
5423            reason.contains("64"),
5424            "diagnostic must name the actual length (got: {reason:?})"
5425        );
5426    }
5427
5428    #[test]
5429    fn child_caixa_max_length_validates() {
5430        // The 63-byte boundary control pin — exactly-at-the-cap is
5431        // accepted, mirroring `membro_caixa_max_length_validates`
5432        // (3f9d7a0) and `placement_cluster_max_length_validates`
5433        // (6cbb900). Pinned separately so a future off-by-one tightening
5434        // surfaces here.
5435        let max_label = "a".repeat(63);
5436        let s = SupervisorSpec {
5437            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
5438            ..SupervisorSpec::default()
5439        };
5440        s.validate().unwrap();
5441    }
5442
5443    #[test]
5444    fn validate_accepts_canonical_child_caixa_forms() {
5445        // The realistic shapes a supervised child's `:caixa` carries —
5446        // single-word `worker`, version-suffixed `cache-v2`, single-char
5447        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
5448        // `payment-retry`, all-digit `0`. Pin every leg so a future
5449        // tightening (e.g. requiring a leading lowercase letter) surfaces
5450        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
5451        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
5452        // (6cbb900).
5453        for form in [
5454            "worker",
5455            "cache-v2",
5456            "a",
5457            "db",
5458            "2-pool",
5459            "payment-retry",
5460            "0",
5461        ] {
5462            let s = SupervisorSpec {
5463                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
5464                ..SupervisorSpec::default()
5465            };
5466            s.validate()
5467                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5468        }
5469    }
5470
5471    #[test]
5472    fn child_caixa_empty_takes_precedence_over_invalid() {
5473        // Order pin: the existing `EmptyChildName` diagnostic (which
5474        // doesn't try to parse the DNS-1123 shape) fires before the new
5475        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
5476        // its narrower error message — `is_dns_1123_label` would reject
5477        // the empty string too (boundary check on the first byte), but
5478        // the empty-string arm is the more self-locating diagnostic for
5479        // the author. Same ordering discipline as
5480        // `membro_caixa_empty_takes_precedence_over_invalid` in
5481        // aplicacao.rs.
5482        let s = SupervisorSpec {
5483            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5484            ..SupervisorSpec::default()
5485        };
5486        let err = s.validate().unwrap_err();
5487        assert_eq!(err, SupervisorError::EmptyChildName);
5488    }
5489
5490    #[test]
5491    fn child_caixa_invalid_fires_before_versao_check() {
5492        // Order pin: the per-axis shape gate runs inline before the
5493        // per-entry versao check, so a malformed `:caixa` on an entry
5494        // whose `:versao` would also fail surfaces the more self-
5495        // locating name-axis diagnostic first. Parallel to
5496        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
5497        // and `placement_cluster_invalid_fires_before_duplicate_check`
5498        // (6cbb900).
5499        let s = SupervisorSpec {
5500            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
5501            ..SupervisorSpec::default()
5502        };
5503        let err = s.validate().unwrap_err();
5504        assert!(
5505            matches!(
5506                err,
5507                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
5508            ),
5509            "got {err:?}"
5510        );
5511    }
5512
5513    #[test]
5514    fn child_caixa_invalid_fires_before_duplicate_check() {
5515        // Order pin: a malformed name on a non-duplicate entry surfaces
5516        // its own diagnostic, even when a later entry would otherwise
5517        // collapse onto an earlier name. The per-entry shape gate runs
5518        // inline before the duplicate-key HashSet insert, mirroring
5519        // `placement_cluster_invalid_fires_before_duplicate_check`
5520        // (6cbb900).
5521        let s = SupervisorSpec {
5522            children: vec![
5523                child("Worker", "^0.1", RestartPolicy::Permanent),
5524                child("cache", "^0.1", RestartPolicy::Transient),
5525                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5526            ],
5527            ..SupervisorSpec::default()
5528        };
5529        let err = s.validate().unwrap_err();
5530        assert!(
5531            matches!(
5532                err,
5533                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
5534            ),
5535            "got {err:?}"
5536        );
5537    }
5538
5539    #[test]
5540    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
5541        // The diagnostic-shape pin: the error names the offending
5542        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
5543        // the author can grep their caixa.lisp without re-running the
5544        // build. Mirrors the diagnostic-shape sweep on every prior
5545        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
5546        let s = SupervisorSpec {
5547            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
5548            ..SupervisorSpec::default()
5549        };
5550        let err = s.validate().unwrap_err();
5551        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5552            panic!("expected ChildCaixaInvalid, got other variant");
5553        };
5554        assert_eq!(caixa, "My_Worker");
5555        assert!(
5556            !reason.is_empty(),
5557            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
5558        );
5559    }
5560
5561    // ── value-shape: zero restart_window + duplicate child names ──────────
5562
5563    #[test]
5564    fn validate_accepts_none_restart_window() {
5565        // Omitted `:restart-window` is the "never reset" sentinel —
5566        // valid by design. Mirrors :limits axes where None = unbounded.
5567        let s = SupervisorSpec {
5568            restart_window: None,
5569            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5570            ..SupervisorSpec::default()
5571        };
5572        s.validate().unwrap();
5573    }
5574
5575    #[test]
5576    fn validate_rejects_zero_restart_window() {
5577        // Same "0 means the opposite of what you think" footgun closed
5578        // for :politicas :timeout (Envoy treats 0s as infinite) and
5579        // :limits :wall-clock (wasmtime traps before the call starts).
5580        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
5581        let s = SupervisorSpec {
5582            restart_window: Some(Duration::ZERO),
5583            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5584            ..SupervisorSpec::default()
5585        };
5586        assert_eq!(
5587            s.validate().unwrap_err(),
5588            SupervisorError::RestartWindowZero
5589        );
5590    }
5591
5592    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
5593    //
5594    // The fourth (and last) typed-`Duration` axis in caixa-core to get
5595    // the integer-millisecond canonical-form gate — peer with
5596    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
5597    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
5598    // path is already gated at the shared codec layer (see
5599    // `restart_window_serde_rejects_fractional_seconds`); this arm
5600    // closes the programmatic-struct-literal path the codec gate can't
5601    // see.
5602
5603    #[test]
5604    fn validate_rejects_sub_millisecond_restart_window() {
5605        // The fail-before-pass-after pin: a programmatic
5606        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
5607        // `validate` on every pre-gate codebase, then truncated to
5608        // `as_millis() == 1` on first serialize — the shared codec
5609        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
5610        // 1_000_000 ns, the typed `restart_window` no longer matches
5611        // its rendered form.
5612        let s = SupervisorSpec {
5613            restart_window: Some(Duration::from_micros(1500)),
5614            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5615            ..SupervisorSpec::default()
5616        };
5617        match s.validate().unwrap_err() {
5618            SupervisorError::RestartWindowNotCanonical { window } => {
5619                assert_eq!(window, Duration::from_micros(1500));
5620            }
5621            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5622        }
5623    }
5624
5625    #[test]
5626    fn validate_rejects_one_nanosecond_restart_window() {
5627        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
5628        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
5629        // so the shared codec emits the literal `"0s"` — the next
5630        // serde round-trip would parse back to `Duration::ZERO`, which
5631        // the `RestartWindowZero` arm then rejects on re-validate. The
5632        // canonical-form gate at this layer surfaces a self-locating
5633        // diagnostic naming the offending Duration verbatim rather
5634        // than a downstream `RestartWindowZero` whose remediation
5635        // points at omitting the slot.
5636        let s = SupervisorSpec {
5637            restart_window: Some(Duration::from_nanos(1)),
5638            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5639            ..SupervisorSpec::default()
5640        };
5641        match s.validate().unwrap_err() {
5642            SupervisorError::RestartWindowNotCanonical { window } => {
5643                assert_eq!(window, Duration::from_nanos(1));
5644            }
5645            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5646        }
5647    }
5648
5649    #[test]
5650    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
5651        // The 1-ns-past-1ms boundary case: a `Duration` carrying
5652        // 1_000_001 ns is structurally past the integer-ms granularity
5653        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
5654        // trip would truncate to `1ms` and the consumer would observe
5655        // a 1-ns drift on every emit. Same boundary the peer
5656        // `validate_rejects_nanosecond_past_canonical_boundary` test
5657        // in limits.rs pins for the `:limits :wall-clock` axis.
5658        let w = Duration::from_nanos(1_000_001);
5659        let s = SupervisorSpec {
5660            restart_window: Some(w),
5661            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5662            ..SupervisorSpec::default()
5663        };
5664        assert_eq!(
5665            s.validate().unwrap_err(),
5666            SupervisorError::RestartWindowNotCanonical { window: w }
5667        );
5668    }
5669
5670    #[test]
5671    fn validate_accepts_integer_millisecond_restart_window_values() {
5672        // The positive-control sweep: every `Duration` the shared
5673        // codec can round-trip losslessly — the canonical
5674        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
5675        // pair emits and accepts — passes `validate` without
5676        // surfacing the new canonical-form arm. Mirrors
5677        // `validate_accepts_integer_millisecond_wall_clock_values` on
5678        // the sibling `:limits :wall-clock` axis.
5679        for w in [
5680            Duration::from_millis(1),
5681            Duration::from_millis(500),
5682            Duration::from_millis(1500),
5683            Duration::from_secs(1),
5684            Duration::from_secs(30),
5685            Duration::from_secs(60),
5686            Duration::from_secs(120),
5687            Duration::from_secs(3600),
5688        ] {
5689            let s = SupervisorSpec {
5690                restart_window: Some(w),
5691                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5692                ..SupervisorSpec::default()
5693            };
5694            s.validate()
5695                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
5696        }
5697    }
5698
5699    #[test]
5700    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
5701        // Cross-arm ordering pin: `Duration::ZERO` has
5702        // `subsec_nanos() == 0` and would otherwise pass the
5703        // canonical-form arm — the zero-floor arm must fire first so
5704        // the more self-locating `RestartWindowZero` diagnostic (with
5705        // its omit-axis remediation directly named) leads. Same
5706        // posture every peer zero-then-shape gate uses
5707        // (`WallClockZero` → `WallClockNotCanonical`,
5708        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
5709        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
5710        let s = SupervisorSpec {
5711            restart_window: Some(Duration::ZERO),
5712            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5713            ..SupervisorSpec::default()
5714        };
5715        assert_eq!(
5716            s.validate().unwrap_err(),
5717            SupervisorError::RestartWindowZero
5718        );
5719    }
5720
5721    #[test]
5722    fn restart_window_canonical_diagnostic_carries_offending_duration() {
5723        // Diagnostic-shape pin: the canonical-form arm names the
5724        // offending `Duration` verbatim so the author's grep lands on
5725        // the field's value, not a generic "duration not canonical"
5726        // message. Same shape every other typed-canonical-form arm
5727        // on this surface carries (`WallClockNotCanonical` carries
5728        // the offending `Duration` verbatim,
5729        // `PolicyTimeoutNotCanonical` carries the offending
5730        // `Duration` verbatim).
5731        let w = Duration::from_micros(500);
5732        let s = SupervisorSpec {
5733            restart_window: Some(w),
5734            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5735            ..SupervisorSpec::default()
5736        };
5737        let err = s.validate().unwrap_err();
5738        let msg = err.to_string();
5739        assert!(
5740            msg.contains("500"),
5741            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
5742        );
5743        assert!(
5744            msg.contains("sub-millisecond"),
5745            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
5746        );
5747    }
5748
5749    #[test]
5750    fn restart_window_validated_value_round_trips_through_codec() {
5751        // The structural property the canonical-ms gate enforces:
5752        // every `SupervisorSpec::restart_window` past
5753        // `SupervisorSpec::validate` round-trips losslessly through
5754        // the shared duration codec (serialize → string →
5755        // deserialize → equal value). Pin this end-to-end so a future
5756        // change to either side (the validate gate's accepted
5757        // granularity, the codec's parse/render unit set) that breaks
5758        // the alignment surfaces here. Peer of
5759        // `wall_clock_validated_value_round_trips_through_codec` on
5760        // the sibling `:limits :wall-clock` axis.
5761        for w in [
5762            Duration::from_millis(1),
5763            Duration::from_millis(1500),
5764            Duration::from_secs(30),
5765            Duration::from_secs(3600),
5766        ] {
5767            let s = SupervisorSpec {
5768                restart_window: Some(w),
5769                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5770                ..SupervisorSpec::default()
5771            };
5772            s.validate().unwrap();
5773            let json = serde_json::to_string(&s).unwrap();
5774            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5775            assert_eq!(back.restart_window, Some(w));
5776        }
5777    }
5778
5779    // ── value-shape: upper cap on :restart-window ─────────────────────────
5780    //
5781    // The fourth (and last) typed-`Duration` axis in caixa-core to get
5782    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
5783    // `:politicas :timeout` (2e8ee7e), and `:politicas
5784    // :circuit-breaker :window` (379a814). Brackets the typed
5785    // `:restart-window` axis structurally: every validated value lies
5786    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
5787    // granularity, closing the
5788    // rolling-window-degenerates-to-lifetime-counter footgun the prior
5789    // zero-floor-and-canonical-form-only checks left open.
5790
5791    #[test]
5792    fn validate_rejects_restart_window_above_cap() {
5793        // The fail-before-pass-after pin: 3601s = 1h + 1s is
5794        // structurally one canonical-tick past the
5795        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
5796        // integer-millisecond magnitude the canonical-form arm above
5797        // accepts cleanly, that the shared duration codec round-trips
5798        // losslessly as `"3601s"`, and that silently passed validate on
5799        // every pre-gate codebase because the typed slot's only checks
5800        // were the zero-floor and canonical-form arms. The runtime
5801        // substrate consuming the value (Erlang/OTP's MaxIntensity/
5802        // Period reconciler, the future wasm-operator's per-supervisor
5803        // restart-intensity counter) reaches for a `Duration` so long
5804        // no realistic restart-recovery pattern resets the counter,
5805        // far from the source caixa.lisp.
5806        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5807        let s = SupervisorSpec {
5808            restart_window: Some(w),
5809            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5810            ..SupervisorSpec::default()
5811        };
5812        assert_eq!(
5813            s.validate().unwrap_err(),
5814            SupervisorError::RestartWindowExceedsCap { window: w }
5815        );
5816    }
5817
5818    #[test]
5819    fn validate_rejects_restart_window_one_millisecond_above_cap() {
5820        // Boundary case: exactly 1ms past the cap (the granularity the
5821        // canonical-form gate enforces). Catches a future "strictly
5822        // less than" half-measure and pins the diagnostic to name the
5823        // offending `Duration` verbatim. Peer of
5824        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
5825        // `rejects_policy_timeout_one_millisecond_above_cap` /
5826        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
5827        // on the sibling typed-`Duration` axes' top edges.
5828        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
5829        let s = SupervisorSpec {
5830            restart_window: Some(w),
5831            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5832            ..SupervisorSpec::default()
5833        };
5834        assert_eq!(
5835            s.validate().unwrap_err(),
5836            SupervisorError::RestartWindowExceedsCap { window: w }
5837        );
5838    }
5839
5840    #[test]
5841    fn validate_rejects_restart_window_far_above_cap() {
5842        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
5843        // `(:restart-window "7d")`, or any "I want a lifetime counter
5844        // but wrote a `<integer>h` magnitude anyway" typo — values the
5845        // canonical-form arm accepts as integer-millisecond magnitudes,
5846        // the codec round-trips losslessly through serde, but the
5847        // operator's `MaxIntensity / Period` reconciler cannot honor
5848        // as a meaningful rolling window. Until this gate landed
5849        // validate accepted them. Pin the common above-cap values (24h,
5850        // 7d, ~11.5d) so a future relaxation that drops the upper bound
5851        // surfaces here.
5852        for w in [
5853            Duration::from_secs(86_400),    // 24h
5854            Duration::from_secs(604_800),   // 7d
5855            Duration::from_secs(1_000_000), // ~11.5 days
5856        ] {
5857            let s = SupervisorSpec {
5858                restart_window: Some(w),
5859                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5860                ..SupervisorSpec::default()
5861            };
5862            assert_eq!(
5863                s.validate().unwrap_err(),
5864                SupervisorError::RestartWindowExceedsCap { window: w }
5865            );
5866        }
5867    }
5868
5869    #[test]
5870    fn validate_accepts_restart_window_at_cap() {
5871        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
5872        // (1h) — must validate. The cap is inclusive on the top edge,
5873        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
5874        // [`crate::POLICY_TIMEOUT_MAX`] /
5875        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
5876        // capped axes. Pin the boundary explicitly so a future
5877        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
5878        // instead of `>`) surfaces here as a test failure rather than a
5879        // silent contract narrowing.
5880        let s = SupervisorSpec {
5881            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5882            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5883            ..SupervisorSpec::default()
5884        };
5885        s.validate()
5886            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
5887    }
5888
5889    #[test]
5890    fn validate_accepts_restart_window_typical_values() {
5891        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
5892        // per-supervisor production-playbook band positive-control
5893        // sweep — every value Learn You Some Erlang's `{intensity, 5,
5894        // 60}` worker-supervisor `Period = 60s` default, Elixir's
5895        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
5896        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
5897        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
5898        // default recommend (5s..=300s) must pass, plus a sweep
5899        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
5900        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
5901        // on the sibling `:limits :wall-clock` axis.
5902        for w in [
5903            Duration::from_millis(1),
5904            Duration::from_millis(500),
5905            Duration::from_secs(1),
5906            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
5907            Duration::from_secs(10), // Riak Core lower
5908            Duration::from_secs(30),
5909            Duration::from_secs(60),  // Learn You Some Erlang default
5910            Duration::from_secs(120), // OTP supervisor MaxT typical
5911            Duration::from_secs(300), // Riak Core upper
5912            Duration::from_secs(900), // 15m
5913            Duration::from_secs(1800),
5914            Duration::from_secs(3600), // exactly 1h, the cap
5915        ] {
5916            let s = SupervisorSpec {
5917                restart_window: Some(w),
5918                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5919                ..SupervisorSpec::default()
5920            };
5921            s.validate()
5922                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
5923        }
5924    }
5925
5926    #[test]
5927    fn restart_window_zero_takes_precedence_over_cap() {
5928        // The cross-arm ordering pin: `Duration::ZERO` is structurally
5929        // outside both `>= 1ms` (zero-floor) and `<=
5930        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
5931        // diagnostic is the more self-locating one (it directly names
5932        // the omit-axis remediation), so the validate gate must fire
5933        // on zero first. Same shape every other zero-then-cap ordering
5934        // on this surface uses (`WallClockZero` then
5935        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
5936        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
5937        // `PolicyBreakerWindowExceedsCap`).
5938        let s = SupervisorSpec {
5939            restart_window: Some(Duration::ZERO),
5940            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5941            ..SupervisorSpec::default()
5942        };
5943        assert_eq!(
5944            s.validate().unwrap_err(),
5945            SupervisorError::RestartWindowZero,
5946            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
5947        );
5948    }
5949
5950    #[test]
5951    fn restart_window_canonical_takes_precedence_over_cap() {
5952        // The cross-arm ordering pin: a `Duration` that is *both*
5953        // sub-millisecond (non-canonical-form) and structurally above
5954        // the cap surfaces the canonical-form diagnostic first,
5955        // because the round-trip-shape break is the more fundamental
5956        // issue (the value can't even round-trip through the codec,
5957        // so the cap diagnostic naming `1ms..=1h` would be misleading
5958        // — there's no integer-ms form of the offending value). Pin
5959        // the order so a future refactor that reorders the arms
5960        // surfaces here as a test failure rather than a silent
5961        // diagnostic regression. Peer of
5962        // `wall_clock_canonical_takes_precedence_over_cap` /
5963        // `policy_timeout_canonical_takes_precedence_over_cap`.
5964        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
5965        let s = SupervisorSpec {
5966            restart_window: Some(w),
5967            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5968            ..SupervisorSpec::default()
5969        };
5970        assert_eq!(
5971            s.validate().unwrap_err(),
5972            SupervisorError::RestartWindowNotCanonical { window: w },
5973            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
5974        );
5975    }
5976
5977    #[test]
5978    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
5979        // The cross-arm ordering pin between the `:max-restarts` cap
5980        // and the sibling `:restart-window` cap. A supervisor carrying
5981        // both an over-cap `max_restarts` AND an over-cap window must
5982        // surface the `MaxRestartsExceedsCap` diagnostic first — the
5983        // cap arm is wired immediately after the zero-restart arm and
5984        // strictly before every window-axis arm (zero / canonical /
5985        // cap), so the offending value the diagnostic names matches
5986        // the order the author would discover the gates by reading
5987        // top-to-bottom through `SupervisorSpec::validate`. Pin the
5988        // order so a future refactor that reorders the arms surfaces
5989        // here as a test failure rather than a silent diagnostic
5990        // regression. Peer of
5991        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
5992        // on the sibling zero / canonical window arms.
5993        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5994        let s = SupervisorSpec {
5995            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5996            restart_window: Some(w),
5997            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5998            ..SupervisorSpec::default()
5999        };
6000        assert_eq!(
6001            s.validate().unwrap_err(),
6002            SupervisorError::MaxRestartsExceedsCap {
6003                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6004            },
6005            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
6006        );
6007    }
6008
6009    #[test]
6010    fn restart_window_cap_diagnostic_carries_offending_value() {
6011        // The diagnostic-shape pin: the offending `Duration` is
6012        // carried verbatim into the
6013        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
6014        // surfaced error message names the value the author wrote,
6015        // not just the cap. Same self-locating diagnostic shape every
6016        // other typed-cap arm on this surface carries
6017        // (`WallClockExceedsCap` carries the offending `Duration`
6018        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
6019        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
6020        // the offending `Duration` verbatim).
6021        let w = Duration::from_secs(7200); // 2h
6022        let s = SupervisorSpec {
6023            restart_window: Some(w),
6024            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6025            ..SupervisorSpec::default()
6026        };
6027        let err = s.validate().unwrap_err();
6028        assert!(
6029            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
6030            "got {err:?}"
6031        );
6032        let msg = err.to_string();
6033        assert!(
6034            msg.contains("7200"),
6035            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
6036        );
6037    }
6038
6039    #[test]
6040    fn supervisor_restart_window_cap_pins_canonical_value() {
6041        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
6042        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
6043        // shared duration codec emits as a clean canonical string
6044        // (`"<n>h"`). Pinning the literal value here surfaces a future
6045        // drift (a relaxation to 24h, a tightening to 5m) as a
6046        // deliberate test edit, not a silent contract narrowing.
6047        //
6048        // The four typed-`Duration` caps on the validation surface
6049        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
6050        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
6051        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
6052        // single uniform top edge at the codec's largest emitted unit
6053        // — a structural-property invariant the equality assertions
6054        // here enshrine, so a future drift on any of the four
6055        // surfaces as a deliberate test edit. Same shape every other
6056        // typed-cap value pin uses
6057        // (`wall_clock_cap_pins_canonical_value`,
6058        // `policy_timeout_cap_pins_canonical_value`,
6059        // `circuit_breaker_window_cap_pins_canonical_value`).
6060        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
6061        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
6062        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
6063        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
6064        assert_eq!(
6065            SUPERVISOR_RESTART_WINDOW_MAX,
6066            crate::POLICY_BREAKER_WINDOW_MAX
6067        );
6068    }
6069
6070    #[test]
6071    fn restart_window_cap_value_round_trips_through_codec() {
6072        // The codec round-trip property the cap arm preserves: the
6073        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
6074        // through the shared duration codec — every value at the cap
6075        // serializes to the canonical `"1h"` form and parses back
6076        // identically. Pin the round-trip so a future change to the
6077        // codec's unit set or to the cap's magnitude that breaks the
6078        // round-trip property surfaces here. Peer of
6079        // `wall_clock_cap_value_round_trips_through_codec` on the
6080        // sibling `:limits :wall-clock` axis.
6081        let s = SupervisorSpec {
6082            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6083            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6084            ..SupervisorSpec::default()
6085        };
6086        s.validate().unwrap();
6087        let json = serde_json::to_string(&s).unwrap();
6088        assert!(
6089            json.contains("\"1h\""),
6090            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
6091        );
6092        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6093        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
6094    }
6095
6096    #[test]
6097    fn validate_rejects_duplicate_child_caixa() {
6098        // Two children with the same :caixa render to two ComputeUnits
6099        // with the same name in the cluster's HelmRelease values —
6100        // one silently overwrites the other. Erlang/OTP's child_spec.id
6101        // is required-unique per supervisor; same set-not-multiset
6102        // discipline applied here as for :membros / :placement
6103        // :clusters / :entrada :paths.
6104        let s = SupervisorSpec {
6105            children: vec![
6106                child("worker", "^0.1", RestartPolicy::Permanent),
6107                child("cache", "^0.1", RestartPolicy::Transient),
6108                child("worker", "^0.2", RestartPolicy::Permanent),
6109            ],
6110            ..SupervisorSpec::default()
6111        };
6112        let err = s.validate().unwrap_err();
6113        assert!(
6114            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
6115            "got {err:?}"
6116        );
6117    }
6118
6119    #[test]
6120    fn validate_duplicate_child_diagnostic_names_first_collision() {
6121        // Iteration walks the :children list in declaration order —
6122        // the diagnostic names the first repeat, deterministically,
6123        // even when multiple names duplicate.
6124        let s = SupervisorSpec {
6125            children: vec![
6126                child("a", "^0.1", RestartPolicy::Permanent),
6127                child("b", "^0.1", RestartPolicy::Permanent),
6128                child("a", "^0.1", RestartPolicy::Permanent),
6129                child("b", "^0.1", RestartPolicy::Permanent),
6130            ],
6131            ..SupervisorSpec::default()
6132        };
6133        let err = s.validate().unwrap_err();
6134        assert!(
6135            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
6136            "got {err:?}"
6137        );
6138    }
6139
6140    // ── self-supervision cross-slot gate ──────────────────────────
6141
6142    #[test]
6143    fn validate_no_self_supervision_rejects_self_referential_child() {
6144        // A supervisor whose `:children` lists its own `:nome` is a
6145        // one-node reconciliation cycle — rejected, naming the parent.
6146        let children = vec![
6147            child("worker", "^0.1", RestartPolicy::Permanent),
6148            child("orquestra", "^0.1", RestartPolicy::Permanent),
6149        ];
6150        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
6151        assert!(
6152            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
6153            "got {err:?}"
6154        );
6155    }
6156
6157    #[test]
6158    fn validate_no_self_supervision_accepts_distinct_children() {
6159        // Positive control: distinct child names (including a child that
6160        // is itself a supervisor — nested trees are valid OTP) pass.
6161        let children = vec![
6162            child("worker", "^0.1", RestartPolicy::Permanent),
6163            child("sub-tree", "^0.1", RestartPolicy::Permanent),
6164        ];
6165        validate_no_self_supervision(&children, "orquestra").unwrap();
6166    }
6167
6168    #[test]
6169    fn validate_no_self_supervision_empty_children_is_ok() {
6170        // SimpleOneForOne / no-static-children supervisors have nothing
6171        // to self-reference — the gate is vacuously satisfied.
6172        validate_no_self_supervision(&[], "orquestra").unwrap();
6173    }
6174
6175    #[test]
6176    fn validate_simple_one_for_one_skips_uniqueness_check() {
6177        // SimpleOneForOne supervisors carry no static children — the
6178        // duplicate-child loop never runs. A zero-window declaration
6179        // on a SimpleOneForOne supervisor still trips the window check
6180        // (window applies to dynamic children too).
6181        let s = SupervisorSpec {
6182            estrategia: RestartStrategy::SimpleOneForOne,
6183            restart_window: None,
6184            children: vec![],
6185            ..SupervisorSpec::default()
6186        };
6187        s.validate().unwrap();
6188        let s_zero = SupervisorSpec {
6189            estrategia: RestartStrategy::SimpleOneForOne,
6190            restart_window: Some(Duration::ZERO),
6191            children: vec![],
6192            ..SupervisorSpec::default()
6193        };
6194        assert_eq!(
6195            s_zero.validate().unwrap_err(),
6196            SupervisorError::RestartWindowZero
6197        );
6198    }
6199
6200    #[test]
6201    fn validate_zero_window_runs_after_max_restarts_check() {
6202        // Pin the order: max_restarts == 0 fires before
6203        // restart_window == 0s, so an author with both wrong sees the
6204        // counter-axis diagnostic first (matches the order in the
6205        // struct and in the doc comment).
6206        let s = SupervisorSpec {
6207            max_restarts: 0,
6208            restart_window: Some(Duration::ZERO),
6209            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6210            ..SupervisorSpec::default()
6211        };
6212        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
6213    }
6214
6215    #[test]
6216    fn round_trip_all_strategies() {
6217        for &strat in RestartStrategy::ALL {
6218            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
6219            // shape partition through the [`gen_platform::IsVariant`]
6220            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
6221            // predicate rather than the raw
6222            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
6223            // open-coded pattern-match — same closed-set-typed-enum
6224            // arm-discriminator dispatch discipline the sibling
6225            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
6226            // (915a934) extended onto its two paired positive / negated
6227            // `matches!` filter sites, and the sibling
6228            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
6229            // predicate convergence (766ec63) extended onto the M3 mesh-
6230            // slot per-`:placement` distribution-strategy `matches!`
6231            // discriminator axis. See the sibling
6232            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
6233            // fixture and the peer `manifest::tests::
6234            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
6235            // fixture — all three sites (the last unlifted
6236            // `matches!`-based arm-discriminator axis on the OTP-shape
6237            // supervisor sibling-restart-strategy closed-set typed enum,
6238            // acknowledged in 915a934's Prior-commits footnote as the
6239            // outstanding follow-up) now consult one typed dispatch on
6240            // the substrate primitive.
6241            let s = SupervisorSpec {
6242                estrategia: strat,
6243                children: if strat.is_simple_one_for_one() {
6244                    vec![]
6245                } else {
6246                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
6247                },
6248                ..SupervisorSpec::default()
6249            };
6250            let json = serde_json::to_string(&s).unwrap();
6251            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6252            assert_eq!(s, back);
6253        }
6254    }
6255
6256    #[test]
6257    fn round_trip_all_restart_policies() {
6258        for policy in [
6259            RestartPolicy::Permanent,
6260            RestartPolicy::Temporary,
6261            RestartPolicy::Transient,
6262        ] {
6263            let c = child("w", "^0.1", policy);
6264            let json = serde_json::to_string(&c).unwrap();
6265            let back: ChildSpec = serde_json::from_str(&json).unwrap();
6266            assert_eq!(c, back);
6267        }
6268    }
6269
6270    #[test]
6271    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
6272        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
6273        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
6274        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
6275        // is the only variant that satisfies `.is_simple_one_for_one()`;
6276        // every static-children-bearing arm (`OneForOne` / `OneForAll`
6277        // / `RestForOne`) returns `false`. This pin makes the partition
6278        // invariant load-bearing at caixa-core test time so a future
6279        // derive regression (a hole that returns `false` for
6280        // `SimpleOneForOne` too, or a byte-collision that flips a second
6281        // variant to `true`) trips here rather than laundering the arm
6282        // at the three test-fixture builder sites (a hole flips the
6283        // `SimpleOneForOne` fixture to carry a non-empty children list
6284        // and the subsequent `SupervisorSpec::validate` would refuse the
6285        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
6286        // a collision flips a peer strategy's fixture to carry an empty
6287        // children list and the subsequent `validate` would refuse with
6288        // [`SupervisorError::NoChildren`] — either way, the pin fires
6289        // here, at the derive site, rather than at the fixture-refusal
6290        // site far away). Peer of the sibling
6291        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
6292        // (915a934) pin on the M2 OTP-appup axis and the sibling
6293        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
6294        // pin on the M0 `:kind` axis.
6295        let cases: &[(RestartStrategy, bool)] = &[
6296            (RestartStrategy::OneForOne, false),
6297            (RestartStrategy::OneForAll, false),
6298            (RestartStrategy::RestForOne, false),
6299            (RestartStrategy::SimpleOneForOne, true),
6300        ];
6301        for (variant, expected) in cases {
6302            assert_eq!(
6303                variant.is_simple_one_for_one(),
6304                *expected,
6305                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
6306                 return {expected} (partition invariant on the \
6307                 IsVariant-derived arm-discriminator predicate — every \
6308                 test-fixture site that partitions the `:children` slot \
6309                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
6310                 off this typed dispatch, so a derive regression must \
6311                 surface here rather than at the fixture-refusal site)"
6312            );
6313        }
6314    }
6315
6316    #[test]
6317    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
6318        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
6319        // fixture-shape partition against the pre-lift
6320        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
6321        // pattern-match every test-fixture builder site previously
6322        // coupled to inline. Asserts the two projections agree byte-for-
6323        // byte on every arm of the enum, so a future derive regression
6324        // that flipped either predicate's arm-set would surface here at
6325        // caixa-core test time rather than at the three fixture-builder
6326        // sites (`supervisor::tests::round_trip_all_strategies`,
6327        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
6328        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
6329        // far from the derive site. Same peer-shape byte-identity pin
6330        // every sibling `IsVariant`-derive-routed convergence carries on
6331        // the substrate's closed-set typed-enum surface (peer of
6332        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
6333        // on the M2 OTP-appup axis).
6334        for &strat in RestartStrategy::ALL {
6335            let via_predicate = strat.is_simple_one_for_one();
6336            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
6337            assert_eq!(
6338                via_predicate, via_matches,
6339                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
6340                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
6341                 the pre-lift open-coded pattern and the \
6342                 IsVariant-derived predicate are the same axis, \
6343                 one typed dispatch"
6344            );
6345        }
6346    }
6347
6348    #[test]
6349    fn duration_codec_round_trip_canonical_units() {
6350        // Note the canonical-form rule: durations serialize to the
6351        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
6352        // "60s" — but the round-trip preserves the underlying Duration.
6353        let cases = [
6354            ("30s", Duration::from_secs(30)),
6355            ("5m", Duration::from_secs(300)),
6356            ("1h", Duration::from_secs(3600)),
6357            ("500ms", Duration::from_millis(500)),
6358        ];
6359        for (lit, dur) in cases {
6360            let s = SupervisorSpec {
6361                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6362                restart_window: Some(dur),
6363                ..SupervisorSpec::default()
6364            };
6365            let json = serde_json::to_string(&s).unwrap();
6366            assert!(
6367                json.contains(&format!("\"{lit}\"")),
6368                "expected \"{lit}\" in {json}"
6369            );
6370            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6371            assert_eq!(back.restart_window, Some(dur));
6372        }
6373    }
6374
6375    #[test]
6376    fn duration_canonicalizes_to_largest_unit() {
6377        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
6378        // typed Duration still equals 60s on the way back.
6379        let s = SupervisorSpec {
6380            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6381            restart_window: Some(Duration::from_secs(60)),
6382            ..SupervisorSpec::default()
6383        };
6384        let json = serde_json::to_string(&s).unwrap();
6385        assert!(json.contains("\"1m\""), "{json}");
6386        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6387        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
6388    }
6389
6390    #[test]
6391    fn three_child_one_for_one_validates() {
6392        let s = SupervisorSpec {
6393            estrategia: RestartStrategy::OneForOne,
6394            max_restarts: 5,
6395            restart_window: Some(Duration::from_secs(60)),
6396            children: vec![
6397                child("worker", "^0.1", RestartPolicy::Permanent),
6398                child("cache", "^0.1", RestartPolicy::Transient),
6399                child("scratch", "^0.1", RestartPolicy::Temporary),
6400            ],
6401        };
6402        s.validate().unwrap();
6403    }
6404
6405    #[test]
6406    fn json_uses_pascal_case_for_strategy_and_policy() {
6407        // Variant names are PascalCase by default in serde, matching
6408        // tatara-lisp's enum convention (`:estrategia OneForOne`).
6409        let c = child("w", "^0.1", RestartPolicy::Permanent);
6410        let json = serde_json::to_string(&c).unwrap();
6411        assert!(json.contains("\"Permanent\""));
6412        assert!(!json.contains("\"permanent\""));
6413
6414        let s = SupervisorSpec {
6415            estrategia: RestartStrategy::OneForOne,
6416            children: vec![c],
6417            ..SupervisorSpec::default()
6418        };
6419        let json = serde_json::to_string(&s).unwrap();
6420        assert!(json.contains("\"estrategia\":\"OneForOne\""));
6421    }
6422
6423    // ── shared duration codec: integer-magnitude canonical-form gate ──
6424    //
6425    // The gate lifts the discipline `crate::limits::parse_duration`
6426    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
6427    // the shared codec backing the remaining three typed-duration
6428    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
6429    // `:politicas :circuit-breaker :window`. Every magnitude `render`
6430    // emits is a non-negative integer with no decimal point and no
6431    // leading sign, so the codec's accepted set must match for
6432    // serialize/deserialize to round-trip without canonical-form
6433    // drift.
6434
6435    #[test]
6436    fn parse_accepts_integer_canonical_units() {
6437        // Pin the happy-path: every canonical author shape `render`
6438        // ever emits parses to the same `Duration` value, so the
6439        // codec's accepted set is at least a superset of its emitted
6440        // set on the canonical-unit axis.
6441        for (lit, dur) in [
6442            ("30s", Duration::from_secs(30)),
6443            ("500ms", Duration::from_millis(500)),
6444            ("2m", Duration::from_secs(120)),
6445            ("1h", Duration::from_secs(3600)),
6446            ("0s", Duration::ZERO),
6447        ] {
6448            assert_eq!(
6449                duration_codec::parse(lit).unwrap(),
6450                dur,
6451                "parse({lit:?}) should be {dur:?}"
6452            );
6453        }
6454    }
6455
6456    #[test]
6457    fn parse_accepts_bare_integer_as_seconds() {
6458        // The `"s" | ""` arm: a bare integer with no unit is read as
6459        // seconds. Pin this so the unit-empty form keeps parsing (it
6460        // renders to `"<n>s"` on serialize — that's a unit-choice
6461        // drift the integer-magnitude gate does NOT close, matching
6462        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
6463        // the peer `:limits :memory` codec).
6464        assert_eq!(
6465            duration_codec::parse("30").unwrap(),
6466            Duration::from_secs(30)
6467        );
6468    }
6469
6470    #[test]
6471    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
6472        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
6473        // on first serialize — DRIFT. The integer-magnitude gate names
6474        // the offending `"1.5"` verbatim and points at the canonical
6475        // remediation `"1500ms"`.
6476        let err = duration_codec::parse("1.5s").unwrap_err();
6477        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
6478        assert!(
6479            err.contains("not a non-negative integer"),
6480            "missing canonical-form reason in {err:?}"
6481        );
6482        assert!(
6483            err.contains("\"1500ms\""),
6484            "missing canonical-form remediation in {err:?}"
6485        );
6486    }
6487
6488    #[test]
6489    fn parse_rejects_decimal_shaped_integer_seconds() {
6490        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
6491        // `1s` exactly, so the round-trip looks correct — but the
6492        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
6493        // decimal-shape-with-integer-value form so author intent is
6494        // never silently rewritten.
6495        let err = duration_codec::parse("1.0s").unwrap_err();
6496        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
6497        assert!(
6498            err.contains("not a non-negative integer"),
6499            "missing canonical-form reason in {err:?}"
6500        );
6501    }
6502
6503    #[test]
6504    fn parse_rejects_half_unit_minute() {
6505        // `"0.5m"` is the unit-fraction footgun — author writes a
6506        // human-readable half-minute, serde silently rewrites to
6507        // `"30s"` on next emit. The gate names the offending
6508        // magnitude `"0.5"` and points at the integer-in-smaller-unit
6509        // form.
6510        let err = duration_codec::parse("0.5m").unwrap_err();
6511        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
6512        assert!(
6513            err.contains("\"30s\""),
6514            "missing canonical-form remediation in {err:?}"
6515        );
6516    }
6517
6518    #[test]
6519    fn parse_rejects_leading_plus_sign() {
6520        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
6521        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
6522        // cleanly to 30s and round-tripped to `"30s"` on next emit
6523        // (DRIFT). The digit-only gate closes the leading-sign class
6524        // first; the diagnostic names `"+30"` verbatim.
6525        let err = duration_codec::parse("+30s").unwrap_err();
6526        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
6527        assert!(
6528            err.contains("not a non-negative integer"),
6529            "missing canonical-form reason in {err:?}"
6530        );
6531    }
6532
6533    #[test]
6534    fn parse_rejects_leading_minus_sign() {
6535        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
6536        // rejected with `"negative duration in \"-30s\""`. Under the
6537        // integer-magnitude gate the diagnostic is unified — `-30` is
6538        // non-digit-only, f64-numeric, and surfaces with the canonical-
6539        // form reason (no leading `+` / `-` sign) naming the offending
6540        // `"-30"` verbatim. Same diagnostic shape as every other
6541        // rejected non-integer magnitude.
6542        let err = duration_codec::parse("-30s").unwrap_err();
6543        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
6544        assert!(
6545            err.contains("not a non-negative integer"),
6546            "missing canonical-form reason in {err:?}"
6547        );
6548    }
6549
6550    #[test]
6551    fn parse_garbage_still_falls_through_to_bad_magnitude() {
6552        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
6553        // through to the narrower "bad duration magnitude" arm — the
6554        // canonical-form diagnostic is reserved for the parser-shape
6555        // footgun case, not the "not a number at all" case. Same
6556        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
6557        // the peer `:limits :memory` codec.
6558        let err = duration_codec::parse("--1s").unwrap_err();
6559        assert!(
6560            err.contains("bad duration magnitude"),
6561            "expected bad-magnitude wording in {err:?}"
6562        );
6563    }
6564
6565    #[test]
6566    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
6567        // The accepted set is now closed under `u64`-exact integer
6568        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
6569        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
6570        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
6571        // possible. Pin the integer-exact arms across the four unit
6572        // suffixes so a future refactor that reaches back for f64
6573        // (`from_secs_f64`, `mul_f64`) surfaces here.
6574        assert_eq!(
6575            duration_codec::parse("3600s").unwrap(),
6576            Duration::from_secs(3600)
6577        );
6578        assert_eq!(
6579            duration_codec::parse("60m").unwrap(),
6580            Duration::from_secs(3600)
6581        );
6582        assert_eq!(
6583            duration_codec::parse("1h").unwrap(),
6584            Duration::from_secs(3600)
6585        );
6586        assert_eq!(
6587            duration_codec::parse("999ms").unwrap(),
6588            Duration::from_millis(999)
6589        );
6590    }
6591
6592    #[test]
6593    fn restart_window_serde_rejects_fractional_seconds() {
6594        // The shared codec backs `SupervisorSpec::restart_window`
6595        // (`with = "duration_codec"`) — so the gate applies on serde
6596        // deserialize for the typed Supervisor slot. A
6597        // `{"restartWindow":"1.5s"}` payload that previously round-
6598        // tripped to a different canonical string on next serialize
6599        // is now refused at deserialize with the integer-magnitude
6600        // diagnostic.
6601        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6602            "restartWindow":"1.5s",
6603            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6604        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6605        let msg = err.to_string();
6606        assert!(
6607            msg.contains("not a non-negative integer"),
6608            "expected integer-magnitude diagnostic in {msg:?}"
6609        );
6610        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
6611    }
6612
6613    #[test]
6614    fn restart_window_serde_rejects_leading_plus() {
6615        // The `u64::from_str` leading-`+` permissiveness gap that
6616        // motivated the digit-only gate (the `f64`-side accepted
6617        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
6618        // is now closed on the shared codec — surfaces as a structured
6619        // diagnostic at the serde layer for every typed-duration slot.
6620        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6621            "restartWindow":"+30s",
6622            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6623        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6624        let msg = err.to_string();
6625        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
6626        assert!(
6627            msg.contains("not a non-negative integer"),
6628            "missing canonical-form reason in {msg:?}"
6629        );
6630    }
6631
6632    #[test]
6633    fn parse_rejects_leading_zero_magnitude() {
6634        // `"030s"` is digit-only, so the existing non-digit-only / sign
6635        // / fractional arm doesn't catch it — `u64::from_str("030")`
6636        // returns `Ok(30)`, so before this gate `"030s"` parsed to
6637        // `Duration::from_secs(30)` and round-tripped through `render`
6638        // to `"30s"` — a *different* canonical string on the next emit,
6639        // breaking the THEORY.md Part V render-determinism contract
6640        // exactly the way `"+30s"` did before the leading-`+` arm
6641        // landed. Peer with the `rate_limit_codec` leading-zero arm
6642        // (4f46830) on the same canonical-form-drift axis.
6643        let err = duration_codec::parse("030s").unwrap_err();
6644        assert!(
6645            err.contains("non-canonical leading zero"),
6646            "expected leading-zero diagnostic in {err:?}"
6647        );
6648        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6649        assert!(
6650            err.contains("\"30s\""),
6651            "missing canonical-form remediation in {err:?}"
6652        );
6653        assert!(
6654            err.contains("THEORY.md"),
6655            "missing render-determinism citation in {err:?}"
6656        );
6657    }
6658
6659    #[test]
6660    fn parse_rejects_multi_digit_zero_magnitude() {
6661        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
6662        // digit-only, parse losslessly to `Duration::ZERO`, but render
6663        // back to `"0s"` (the single-byte canonical form) on the next
6664        // emit. The leading-zero arm refuses the drift class at the
6665        // codec layer; the semantic-zero gate downstream
6666        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
6667        // the single-byte canonical form `"0s"` separately on the
6668        // typed-validate layer.
6669        let err = duration_codec::parse("00s").unwrap_err();
6670        assert!(
6671            err.contains("non-canonical leading zero"),
6672            "expected leading-zero diagnostic in {err:?}"
6673        );
6674        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
6675    }
6676
6677    #[test]
6678    fn parse_rejects_leading_zero_per_hour_window() {
6679        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
6680        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
6681        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
6682        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
6683        // `h` / bare-integer-as-seconds) inherits the same gate.
6684        let err = duration_codec::parse("01h").unwrap_err();
6685        assert!(
6686            err.contains("non-canonical leading zero"),
6687            "expected leading-zero diagnostic in {err:?}"
6688        );
6689        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
6690    }
6691
6692    #[test]
6693    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
6694        // The `parse_accepts_bare_integer_as_seconds` happy-path
6695        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
6696        // multi-byte starts-with-`0`, parses losslessly to
6697        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
6698        // bare-integer surface accepts permissive unit-empty
6699        // shorthand but still must reject leading-zero padding.
6700        let err = duration_codec::parse("030").unwrap_err();
6701        assert!(
6702            err.contains("non-canonical leading zero"),
6703            "expected leading-zero diagnostic in {err:?}"
6704        );
6705        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6706    }
6707
6708    #[test]
6709    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
6710        // The codec-layer / typed-validate-layer boundary: `"0s"` /
6711        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
6712        // each round-trips losslessly through `render`
6713        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
6714        // accepts them. The downstream semantic-zero gates
6715        // (`SupervisorError::ZeroRestartWindow`,
6716        // `AplicacaoError::PolicyTimeoutZero`,
6717        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
6718        // zero-magnitude authoring at the typed-validate layer above,
6719        // peer with the `rate_limit_codec` codec-layer / typed-
6720        // validate-layer partition for `"0/s"`.
6721        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
6722        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
6723        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
6724    }
6725
6726    #[test]
6727    fn parse_accepts_canonical_magnitude_with_leading_one() {
6728        // The complementary boundary: a future tightening cannot
6729        // drift into rejecting valid canonical magnitudes that
6730        // happen to start with `1` (or any digit `[1-9]`). Pin
6731        // every canonical-unit suffix so the leading-zero arm
6732        // remains strictly narrower than the digit-only arm.
6733        assert_eq!(
6734            duration_codec::parse("100ms").unwrap(),
6735            Duration::from_millis(100)
6736        );
6737        assert_eq!(
6738            duration_codec::parse("100s").unwrap(),
6739            Duration::from_secs(100)
6740        );
6741        assert_eq!(
6742            duration_codec::parse("10m").unwrap(),
6743            Duration::from_secs(600)
6744        );
6745        assert_eq!(
6746            duration_codec::parse("10h").unwrap(),
6747            Duration::from_secs(36_000)
6748        );
6749    }
6750
6751    #[test]
6752    fn restart_window_serde_rejects_leading_zero() {
6753        // The shared codec backs `SupervisorSpec::restart_window`
6754        // (`with = "duration_codec"`) — so the leading-zero arm
6755        // applies on serde deserialize for the typed Supervisor slot.
6756        // A `{"restartWindow":"030s"}` payload that previously round-
6757        // tripped to a different canonical string on next serialize
6758        // is now refused at deserialize with the leading-zero
6759        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
6760        // / `restart_window_serde_rejects_fractional_seconds` on the
6761        // same canonical-form-drift axis.
6762        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6763            "restartWindow":"030s",
6764            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6765        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6766        let msg = err.to_string();
6767        assert!(
6768            msg.contains("non-canonical leading zero"),
6769            "expected leading-zero diagnostic in {msg:?}"
6770        );
6771        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
6772    }
6773
6774    #[test]
6775    fn parse_rejects_leading_whitespace() {
6776        // `" 30s"` — the canonical paste-from-aligned-doc /
6777        // paste-from-YAML-quoted-plain-scalar footgun. Before this
6778        // gate the top-level `s.trim()` at parse entry silently ate
6779        // the leading space and parsed the value to
6780        // `Duration::from_secs(30)`, which then round-tripped through
6781        // `render` to `"30s"` (a *different* canonical string on the
6782        // next emit) — the exact canonical-form-drift class the
6783        // leading-`+` / leading-zero arms already close, extended
6784        // to the whitespace-byte class. Peer with the sibling
6785        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
6786        // the M3 `:politicas` axis.
6787        let err = duration_codec::parse(" 30s").unwrap_err();
6788        assert!(
6789            err.contains("contains whitespace byte"),
6790            "expected whitespace diagnostic in {err:?}"
6791        );
6792        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6793        assert!(
6794            err.contains("THEORY.md"),
6795            "missing render-determinism contract citation in {err:?}"
6796        );
6797    }
6798
6799    #[test]
6800    fn parse_rejects_trailing_whitespace() {
6801        // `"30s "` — the canonical shell-history / trailing-space
6802        // paste footgun. Before this gate the top-level `s.trim()`
6803        // silently ate the trailing space and parsed to
6804        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
6805        // next emit — same canonical-form drift as the leading-space
6806        // sibling, closed on the same whitespace-byte arm.
6807        let err = duration_codec::parse("30s ").unwrap_err();
6808        assert!(
6809            err.contains("contains whitespace byte"),
6810            "expected whitespace diagnostic in {err:?}"
6811        );
6812        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6813    }
6814
6815    #[test]
6816    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
6817        // `"30 s"` — the canonical typographically-spaced author
6818        // shape (the same idiom every prose reference to a duration
6819        // renders as, mistakenly retained when the value is pasted
6820        // into a codec-shaped slot). Before this gate the per-part
6821        // `num_part.trim()` / `unit.trim()` calls silently ate the
6822        // whitespace between the magnitude and the unit and parsed
6823        // the value to `Duration::from_secs(30)`, round-tripping to
6824        // `"30s"` — the codec's *internal* whitespace-tolerance
6825        // vector, orthogonal to the leading / trailing surface but
6826        // the same canonical-form-drift class. Pins the arm as
6827        // strictly stronger than the pre-existing top-level
6828        // `s.trim()` behavior: it fires on whitespace anywhere in
6829        // the value, not just at the string boundary.
6830        let err = duration_codec::parse("30 s").unwrap_err();
6831        assert!(
6832            err.contains("contains whitespace byte"),
6833            "expected whitespace diagnostic in {err:?}"
6834        );
6835        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6836    }
6837
6838    #[test]
6839    fn parse_rejects_tab_byte() {
6840        // `"\t30s"` — the canonical paste-from-indented-doc /
6841        // paste-from-YAML-block-scalar footgun where a tab byte leads
6842        // the magnitude. Pins that the gate covers tab (`0x09`) as
6843        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
6844        // members and both would be silently swallowed by `s.trim()`
6845        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
6846        // space alone to the full ASCII-whitespace set (space `0x20`,
6847        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
6848        // the tab arm as a representative of the non-space members.
6849        let err = duration_codec::parse("\t30s").unwrap_err();
6850        assert!(
6851            err.contains("contains whitespace byte"),
6852            "expected whitespace diagnostic in {err:?}"
6853        );
6854        assert!(
6855            err.contains("0x09"),
6856            "missing offending tab byte in {err:?}"
6857        );
6858    }
6859
6860    #[test]
6861    fn restart_window_serde_rejects_whitespace() {
6862        // The shared codec backs `SupervisorSpec::restart_window`
6863        // (`with = "duration_codec"`) — so the whitespace arm
6864        // applies on serde deserialize for the typed Supervisor slot.
6865        // A `{"restartWindow":" 30s"}` payload that previously round-
6866        // tripped to a different canonical string on next serialize
6867        // is now refused at deserialize with the whitespace-byte
6868        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
6869        // / `restart_window_serde_rejects_leading_plus` /
6870        // `restart_window_serde_rejects_fractional_seconds` on the
6871        // same canonical-form-drift axis.
6872        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6873            "restartWindow":" 30s",
6874            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6875        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6876        let msg = err.to_string();
6877        assert!(
6878            msg.contains("contains whitespace byte"),
6879            "expected whitespace diagnostic in {msg:?}"
6880        );
6881        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
6882    }
6883
6884    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
6885    //
6886    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
6887    // duration codec — closes the strictly-complementary class the
6888    // byte-scan cannot see, through the lifted
6889    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
6890    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
6891    // and `:politicas :circuit-breaker :window` simultaneously via
6892    // this shared codec.
6893
6894    #[test]
6895    fn duration_codec_parse_rejects_leading_nbsp() {
6896        // NBSP prefix — the strictly-complementary drift class the
6897        // ASCII byte-scan cannot see. `str::trim` strips it silently
6898        // and the value drifts to `"30s"` on next serialize.
6899        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
6900        assert!(
6901            err.contains("non-ASCII Unicode whitespace character"),
6902            "expected non-ASCII whitespace diagnostic in {err:?}"
6903        );
6904        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
6905    }
6906
6907    #[test]
6908    fn duration_codec_parse_rejects_trailing_line_separator() {
6909        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
6910        // footgun.
6911        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
6912        assert!(
6913            err.contains("non-ASCII Unicode whitespace character"),
6914            "expected non-ASCII whitespace diagnostic in {err:?}"
6915        );
6916        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
6917    }
6918
6919    #[test]
6920    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
6921        // Positive-control pin: every ASCII-only canonical form the
6922        // renderer emits stays accepted through the new arm.
6923        assert_eq!(
6924            duration_codec::parse("30s").unwrap(),
6925            Duration::from_secs(30)
6926        );
6927        assert_eq!(
6928            duration_codec::parse("500ms").unwrap(),
6929            Duration::from_millis(500)
6930        );
6931        assert_eq!(
6932            duration_codec::parse("1h").unwrap(),
6933            Duration::from_secs(3600)
6934        );
6935    }
6936
6937    #[test]
6938    fn restart_window_serde_rejects_non_ascii_whitespace() {
6939        // The shared codec backs `SupervisorSpec::restart_window` — so
6940        // the new non-ASCII Unicode whitespace arm applies on serde
6941        // deserialize for the typed Supervisor slot. A
6942        // `{"restartWindow":" 30s"}` payload that previously
6943        // survived the ASCII byte-scan (only ASCII whitespace was
6944        // refused) is now refused at deserialize with the
6945        // non-ASCII-whitespace-and-codepoint diagnostic.
6946        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
6947            \"restartWindow\":\"\u{00A0}30s\",\
6948            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
6949        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6950        let msg = err.to_string();
6951        assert!(
6952            msg.contains("non-ASCII Unicode whitespace character"),
6953            "expected non-ASCII whitespace diagnostic in {msg:?}"
6954        );
6955        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
6956    }
6957
6958    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
6959
6960    #[test]
6961    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
6962        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
6963        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
6964        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
6965        // name the exact camelCase JSON keys the
6966        // `#[serde(rename_all = "camelCase")]` attribute on
6967        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
6968        // field carries `Some(_)` / non-empty) and pin that each canonical
6969        // byte-sequence appears verbatim in the JSON — a future accidental
6970        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
6971        // name flip at the derive attribute (any of which would silently
6972        // break every downstream JSON consumer that reaches for one of the
6973        // four consts via `Value::get(...)`) surfaces here as a build-time
6974        // test failure at `supervisor.rs`, not as an apply-time
6975        // `.get(<stale-canonical-const>)` returning `None` far from the
6976        // derive-attr drift's commit. Peer with the sibling
6977        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
6978        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
6979        // M2 typed-slot family established, extended here to close the
6980        // top-level Supervisor axis.
6981        let spec = SupervisorSpec {
6982            estrategia: RestartStrategy::OneForOne,
6983            max_restarts: 5,
6984            restart_window: Some(Duration::from_secs(60)),
6985            children: vec![ChildSpec {
6986                caixa: "w".into(),
6987                versao: "^0.1".into(),
6988                restart: RestartPolicy::Permanent,
6989            }],
6990        };
6991        let json = serde_json::to_string(&spec).unwrap();
6992        for key in [
6993            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6994            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6995            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6996            crate::render::SUPERVISOR_KEY_CHILDREN,
6997        ] {
6998            let quoted = format!("\"{key}\"");
6999            assert!(
7000                json.contains(&quoted),
7001                "serialized SupervisorSpec must carry the lifted \
7002                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
7003                 the JSON emission (got: {json})",
7004            );
7005        }
7006    }
7007
7008    #[test]
7009    fn supervisor_key_consts_are_pairwise_distinct() {
7010        // Cross-axis drift-detection pin: a future collapse of two
7011        // canonical top-level byte-strings onto the same value (e.g. an
7012        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
7013        // also read `"estrategia"`) would silently reroute every
7014        // downstream probe on one axis onto the sibling axis's overlay
7015        // entry and pass every propagation-probe test that expected only
7016        // the stale axis's value. Peer of the sibling four-way distinct
7017        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
7018        let all = [
7019            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7020            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7021            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7022            crate::render::SUPERVISOR_KEY_CHILDREN,
7023        ];
7024        for (i, a) in all.iter().enumerate() {
7025            for b in all.iter().skip(i + 1) {
7026                assert_ne!(
7027                    a, b,
7028                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
7029                     canonical byte-sequences — got `{a}` == `{b}`",
7030                );
7031            }
7032        }
7033    }
7034
7035    #[test]
7036    fn supervisor_key_consts_are_lower_camel_case_shape() {
7037        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
7038        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7039        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7040        // capital, no whitespace / dots) — the canonical shape the
7041        // `#[serde(rename_all = "camelCase")]` derive produces on
7042        // `SupervisorSpec`. A future flip to a non-camelCase attribute
7043        // at the derive surfaces both here (this test fails on the
7044        // stale-constant shape) and at
7045        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7046        // (that test fails on the mismatch between const and derive).
7047        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
7048        // (d8b8b4f) on the sibling M2 `:limits` axis.
7049        for key in [
7050            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7051            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7052            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7053            crate::render::SUPERVISOR_KEY_CHILDREN,
7054        ] {
7055            assert!(
7056                !key.is_empty(),
7057                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
7058            );
7059            let first = key.chars().next().unwrap();
7060            assert!(
7061                first.is_ascii_lowercase(),
7062                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
7063                 (got {key:?}, leads with {first:?})",
7064            );
7065            assert!(
7066                key.chars().all(|c| c.is_ascii_alphanumeric()),
7067                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
7068                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7069            );
7070        }
7071    }
7072
7073    #[test]
7074    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
7075        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
7076        // (camelCase JSON keys, no leading colon) must never collide
7077        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
7078        // consts (kebab-case author-facing labels with leading colon)
7079        // that sit next to them at `caixa_core::render`. Both families
7080        // cover the same four typed Supervisor slots on two distinct
7081        // axes (author-side kebab vs renderer-side camelCase);
7082        // collapsing either family onto the other's byte-shape would
7083        // silently reroute the render-side probe onto the author-facing
7084        // surface, or vice versa. Peer of the byte-distinctness
7085        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
7086        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
7087        let pairs = [
7088            (
7089                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7090                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
7091            ),
7092            (
7093                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7094                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
7095            ),
7096            (
7097                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7098                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
7099            ),
7100            (
7101                crate::render::SUPERVISOR_KEY_CHILDREN,
7102                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
7103            ),
7104        ];
7105        for (json_key, author_key) in pairs {
7106            assert_ne!(
7107                json_key, author_key,
7108                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
7109                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
7110                 got JSON `{json_key}` == author `{author_key}`",
7111            );
7112        }
7113    }
7114
7115    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
7116
7117    #[test]
7118    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
7119        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
7120        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
7121        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
7122        // keys the `#[serde(rename_all = "camelCase")]` attribute on
7123        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
7124        // pin that each canonical byte-sequence appears verbatim in the
7125        // JSON — a future accidental `rename_all = "snake_case"` /
7126        // `"kebab-case"` / verbatim-field-name flip at the derive
7127        // attribute (any of which would silently break every downstream
7128        // JSON consumer that reaches for one of the three consts via
7129        // `Value::get(...)`) surfaces here as a build-time test failure at
7130        // `supervisor.rs`, not as an apply-time
7131        // `.get(<stale-canonical-const>)` returning `None` far from the
7132        // derive-attr drift's commit. Peer with the enclosing
7133        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7134        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
7135        // discipline the SupervisorSpec top-level lift established,
7136        // extended here to the sibling per-`:children` entry `ChildSpec`
7137        // derive so the last M2 typed-struct sub-block
7138        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
7139        // surface without a lifted serde-key peer joins the substrate's
7140        // "one canonical byte-string per typed serialized-key axis"
7141        // discipline.
7142        let c = ChildSpec {
7143            caixa: "worker".into(),
7144            versao: "^0.1".into(),
7145            restart: RestartPolicy::Permanent,
7146        };
7147        let json = serde_json::to_string(&c).unwrap();
7148        for key in [
7149            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7150            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7151            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7152        ] {
7153            let quoted = format!("\"{key}\"");
7154            assert!(
7155                json.contains(&quoted),
7156                "serialized ChildSpec must carry the lifted \
7157                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
7158                 in the JSON emission (got: {json})",
7159            );
7160        }
7161    }
7162
7163    #[test]
7164    fn supervisor_child_key_consts_are_pairwise_distinct() {
7165        // Cross-axis drift-detection pin: a future collapse of two
7166        // canonical `ChildSpec` per-entry byte-strings onto the same
7167        // value (e.g. an accidental copy-paste flip of
7168        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
7169        // silently reroute every downstream probe on one axis onto the
7170        // sibling axis's overlay entry and pass every propagation-probe
7171        // test that expected only the stale axis's value. Peer of the
7172        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
7173        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
7174        // pair (ce80ca0).
7175        let all = [
7176            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7177            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7178            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7179        ];
7180        for (i, a) in all.iter().enumerate() {
7181            for b in all.iter().skip(i + 1) {
7182                assert_ne!(
7183                    a, b,
7184                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
7185                     distinct canonical byte-sequences — got `{a}` == `{b}`",
7186                );
7187            }
7188        }
7189    }
7190
7191    #[test]
7192    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
7193        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
7194        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7195        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7196        // capital, no whitespace / dots) — the canonical shape the
7197        // `#[serde(rename_all = "camelCase")]` derive produces on
7198        // `ChildSpec`. A future flip to a non-camelCase attribute at the
7199        // derive surfaces both here (this test fails on the
7200        // stale-constant shape) and at
7201        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
7202        // (that test fails on the mismatch between const and derive).
7203        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
7204        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
7205        for key in [
7206            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7207            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7208            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7209        ] {
7210            assert!(
7211                !key.is_empty(),
7212                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
7213            );
7214            let first = key.chars().next().unwrap();
7215            assert!(
7216                first.is_ascii_lowercase(),
7217                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
7218                 byte (got {key:?}, leads with {first:?})",
7219            );
7220            assert!(
7221                key.chars().all(|c| c.is_ascii_alphanumeric()),
7222                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
7223                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7224            );
7225        }
7226    }
7227
7228    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
7229
7230    #[test]
7231    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
7232        // The fail-before-pass-after pin: pre-lift there was no
7233        // single-source binding between the [`RestartStrategy`] variant
7234        // name the un-`rename`d `Serialize` derive emits under
7235        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
7236        // every downstream cluster-side dispatcher (the future
7237        // wasm-operator's per-supervisor sibling-restart branch, the
7238        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7239        // admission-time enum-arm bind, the `caixa-operator`'s
7240        // hierarchical reconciliation scheduler's per-strategy fan-out)
7241        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
7242        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
7243        // override, or a variant rename in the source — would silently
7244        // rebrand the emitted scalar under one spelling while every
7245        // downstream dispatcher still probed the other, with the failure
7246        // surfacing at the operator's reconcile posture (subtrees coming
7247        // up under the `default()` `OneForOne` arm rather than the typed
7248        // slot's declared strategy — a bad child would then only take
7249        // itself down instead of the sibling set the author intended, so
7250        // shared-state children fall out of sync) far from the source
7251        // rebrand commit and with no field naming the drift. Pinning the
7252        // two paths (the `Serialize` derive's serialized string AND the
7253        // [`RestartStrategy::as_str`] helper) to the same four lifted
7254        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
7255        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
7256        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
7257        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
7258        // byte-strings makes any future drift on either endpoint fail
7259        // here at caixa-core build time. Peer of the M3
7260        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7261        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
7262        // three-path-convergence discipline, extended to close the
7263        // OTP-shaped per-supervisor sibling-restart axis.
7264        for (variant, expected) in [
7265            (
7266                RestartStrategy::OneForOne,
7267                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7268            ),
7269            (
7270                RestartStrategy::OneForAll,
7271                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7272            ),
7273            (
7274                RestartStrategy::RestForOne,
7275                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7276            ),
7277            (
7278                RestartStrategy::SimpleOneForOne,
7279                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7280            ),
7281        ] {
7282            let json = serde_json::to_string(&variant).unwrap();
7283            assert_eq!(
7284                json,
7285                format!("\"{expected}\""),
7286                "RestartStrategy::{variant:?} must serialize to {expected:?}"
7287            );
7288            assert_eq!(
7289                variant.as_str(),
7290                expected,
7291                "RestartStrategy::{variant:?}.as_str() must return the lifted \
7292                 SUPERVISOR_ESTRATEGIA_* constant"
7293            );
7294        }
7295    }
7296
7297    #[test]
7298    fn supervisor_estrategia_consts_are_pairwise_distinct() {
7299        // Cross-arm drift-detection pin: a future collapse of two
7300        // canonical variant byte-strings onto the same value (e.g. an
7301        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
7302        // to also read `"OneForOne"`) would silently reroute every
7303        // downstream operator's per-strategy dispatch onto the sibling
7304        // arm's reconcile branch and pass every propagation-probe test
7305        // that expected only the stale arm's value — the mis-strategied
7306        // subtree would come up with the wrong sibling-restart posture
7307        // on every subsequent failure. Peer of the sibling four-way
7308        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
7309        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
7310        let all = [
7311            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7312            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7313            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7314            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7315        ];
7316        for (i, a) in all.iter().enumerate() {
7317            for (j, b) in all.iter().enumerate() {
7318                if i != j {
7319                    assert_ne!(
7320                        a, b,
7321                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
7322                         — got duplicate {a:?} at indices {i} and {j}",
7323                    );
7324                }
7325            }
7326        }
7327    }
7328
7329    #[test]
7330    fn restart_strategy_display_routes_through_as_str_helper() {
7331        // The fail-before-pass-after pin on the first half of the
7332        // three-path convergence: pre-convergence the sibling
7333        // OTP-shape typed enum [`RestartStrategy`] carried a
7334        // [`std::fmt::Display`] surface via its
7335        // `#[discriminant(also_display)]` gen-platform derive route,
7336        // which arrived kebab-case as `"one-for-one"` /
7337        // `"one-for-all"` / `"rest-for-one"` /
7338        // `"simple-one-for-one"` while the wire format ran as
7339        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
7340        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
7341        // Every consumer reaching for a strategy byte-string past the
7342        // wire format had to pick between three paths
7343        // ([`RestartStrategy::as_str`], the `Serialize` derive's
7344        // serialized string, or `format!("{v}")` on the
7345        // discriminant-Display route), any two of which a future
7346        // variant rename or `#[serde(rename_all = "kebab-case")]`
7347        // attribute would silently desynchronize. Wiring
7348        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
7349        // closes the third path: every `format!("{v}")` call reaches
7350        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7351        // const the wire format and the [`RestartStrategy::as_str`]
7352        // helper already route through, so a future variant rename
7353        // lands at exactly one place. Pin the routing here so a future
7354        // `impl std::fmt::Display for RestartStrategy`
7355        // reimplementation that hand-rolls the arms instead of
7356        // delegating to [`RestartStrategy::as_str`] fails at
7357        // caixa-core build time. Peer of the M3
7358        // `placement_strategy_display_routes_through_as_str_helper`
7359        // (cc8f749) which the M3 axis converged first.
7360        for &variant in RestartStrategy::ALL {
7361            assert_eq!(
7362                variant.to_string(),
7363                variant.as_str(),
7364                "RestartStrategy::{variant:?} Display must route through \
7365                 RestartStrategy::as_str (single source of truth: the lifted \
7366                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
7367            );
7368        }
7369    }
7370
7371    #[test]
7372    fn restart_strategy_display_matches_serialized_wire_byte_string() {
7373        // The fail-before-pass-after pin on the second half of the
7374        // three-path convergence: `Display` (user-facing text) agrees
7375        // byte-for-byte with the `Serialize` derive's wire format
7376        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
7377        // scalar) on every variant. Pre-convergence the two paths
7378        // were structurally independent — a future
7379        // `#[serde(rename_all = "kebab-case")]` attribute on the
7380        // enum would silently rebrand the emitted wire scalar
7381        // (`one-for-one`, `one-for-all`, `rest-for-one`,
7382        // `simple-one-for-one`) while every consumer that
7383        // pretty-prints the strategy (the future wasm-operator's
7384        // per-supervisor sibling-restart-strategy diagnostic line,
7385        // the future `feira app graph` per-supervisor strategy line,
7386        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7387        // materializer's admission-webhook rejection body) would
7388        // still emit the PascalCase form the `as_str` / `Display`
7389        // route returns, with the mismatch surfacing at consumer
7390        // parse time / operator dispatch time far from the source
7391        // rebrand commit. Pin the two paths byte-for-byte here so any
7392        // future serde-attribute or variant-rename drift is a
7393        // caixa-core-build-time test failure at this call, not a
7394        // silent per-consumer dispatch miss. Peer of the M3
7395        // `placement_strategy_display_matches_serialized_wire_byte_string`
7396        // (cc8f749) which the M3 axis converged first.
7397        for &variant in RestartStrategy::ALL {
7398            let wire = serde_json::to_string(&variant).unwrap();
7399            let unquoted = wire
7400                .strip_prefix('"')
7401                .and_then(|s| s.strip_suffix('"'))
7402                .expect("serialized RestartStrategy is a JSON string");
7403            assert_eq!(
7404                variant.to_string(),
7405                unquoted,
7406                "RestartStrategy::{variant:?} Display byte-string must match the \
7407                 Serialize derive's wire byte-string (three-path convergence: \
7408                 Display + as_str + Serialize all resolve to the same \
7409                 SUPERVISOR_ESTRATEGIA_* const)"
7410            );
7411        }
7412    }
7413
7414    #[test]
7415    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
7416        // Fail-before-pass-after byte-parity pin on the lifted
7417        // `impl AsRef<str> for RestartStrategy` — asserts the
7418        // standard-library trait impl and the substrate-primitive
7419        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
7420        // to the same `&str` per instance across the four-arm
7421        // closed set, so any future silent detour that routes the
7422        // impl through a divergent projection (a per-arm inline
7423        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
7424        // re-inlining that opens a compile-time link to the un-lifted
7425        // arm-literal, a swap onto the kebab-case
7426        // [`gen_platform::Discriminant`] catalog identity that would
7427        // collide the wire axis with the dispatcher-catalog axis) trips
7428        // at caixa-core test time under `PartialEq` rather than at a
7429        // downstream `impl AsRef<str>`-bound consumer's silent split.
7430        // Sweeps every one of the four arms
7431        // [`RestartStrategy::ALL`] carries so no arm's projection is
7432        // covered only by the sibling wire-format `Serialize` derive
7433        // path. Peer of the sibling
7434        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
7435        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
7436        // top-level `:versao` typed newtype — the two pins together
7437        // cover the substrate primitive's `AsRef<str>` projection axis
7438        // on the paired newtype + closed-set-typed-enum surface.
7439        for &variant in RestartStrategy::ALL {
7440            assert_eq!(
7441                <RestartStrategy as AsRef<str>>::as_ref(&variant),
7442                variant.as_str(),
7443                "AsRef<str> impl on RestartStrategy::{variant:?} must \
7444                 byte-equal RestartStrategy::as_str on the same instance \
7445                 — divergence signals a silent detour off the substrate-\
7446                 primitive accessor"
7447            );
7448        }
7449    }
7450
7451    #[test]
7452    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
7453        // Fail-before-pass-after byte-parity pin on the three-path
7454        // convergence discipline the M2 sibling-restart primitive now
7455        // carries on the `&str`-projection axis:
7456        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
7457        // lifted impl), `format!("{s}")` (the pre-existing
7458        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
7459        // primitive `pub const fn` accessor both trait impls delegate
7460        // through) must resolve to the same byte-string on every
7461        // instance across the four-arm closed set. Refuses any future
7462        // divergence between the two trait impls (a stray
7463        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7464        // rather than delegating through the shared accessor; a
7465        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7466        // literal cascade) that would silently split the two
7467        // projection paths of the same closed-set typed enum. Mirrors
7468        // the sibling three-path-convergence discipline the peer
7469        // [`crate::CaixaVersion`] typed newtype carries on its
7470        // `AsRef<str>` / `Display` / `as_str` triple
7471        // (version.rs pin
7472        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7473        // 16d5c7e).
7474        for &variant in RestartStrategy::ALL {
7475            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
7476            let via_display: String = format!("{variant}");
7477            let via_accessor: &str = variant.as_str();
7478            assert_eq!(via_as_ref, via_accessor);
7479            assert_eq!(via_display, via_accessor);
7480            assert_eq!(via_as_ref, via_display.as_str());
7481        }
7482    }
7483
7484    #[test]
7485    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
7486        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
7487        // exhaustive-iteration surface: every variant appears exactly
7488        // once, and the slice length matches the arm count of the
7489        // closed set. Every consumer that walks the accepted-strategy
7490        // set (a future `feira supervisor --estrategia …` CLI-side
7491        // arg-parse's "did you mean" hint, a future M4 admission-
7492        // webhook's rejection body naming the accepted-`:estrategia`
7493        // list, the [`RestartStrategy::from_wire`] reverse-projection
7494        // consumers that iterate the accept-set for diagnostic
7495        // rendering) reads through this slice, so a future arm addition
7496        // that grows the enum but forgets to grow [`Self::ALL`]
7497        // silently truncates every downstream consumer's accept-set at
7498        // the same pre-addition boundary — this pin fails at caixa-core
7499        // build time on the pairwise-distinct + arm-count invariants.
7500        //
7501        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
7502        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7503        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7504        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7505        // pins on the peer closed-set typed-enum axes.
7506        let all: &[RestartStrategy] = RestartStrategy::ALL;
7507        assert_eq!(
7508            all.len(),
7509            4,
7510            "RestartStrategy::ALL must enumerate every variant of the \
7511             four-arm closed set (OneForOne, OneForAll, RestForOne, \
7512             SimpleOneForOne); got {all:?}"
7513        );
7514        for (i, a) in all.iter().enumerate() {
7515            for (j, b) in all.iter().enumerate() {
7516                if i != j {
7517                    assert_ne!(
7518                        a, b,
7519                        "RestartStrategy::ALL must carry every variant exactly \
7520                         once — got duplicate {a:?} at indices {i} and {j}"
7521                    );
7522                }
7523            }
7524        }
7525        for variant in [
7526            RestartStrategy::OneForOne,
7527            RestartStrategy::OneForAll,
7528            RestartStrategy::RestForOne,
7529            RestartStrategy::SimpleOneForOne,
7530        ] {
7531            assert!(
7532                all.contains(&variant),
7533                "RestartStrategy::ALL must contain {variant:?} — a future arm \
7534                 addition that grows the enum but forgets to grow the ALL slice \
7535                 silently truncates every downstream consumer's accept-set at \
7536                 the pre-addition boundary"
7537            );
7538        }
7539    }
7540
7541    #[test]
7542    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
7543        // Fail-before-pass-after pin on the forward accept-set of the
7544        // [`RestartStrategy::from_wire`] reverse projection: every
7545        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7546        // constant the [`RestartStrategy::as_str`] emitter walks parses
7547        // back to its paired variant. Any future arm addition that
7548        // grows the emitter's `as_str` match but forgets to grow the
7549        // parser's `from_wire` match silently splits the two halves of
7550        // the round-trip — the wire byte-string one non-serde consumer
7551        // parses from the one the emitter wrote — with the failure
7552        // surfacing at parse time far from the rebrand commit. Pinning
7553        // the four-arm accept-set here catches the drift at caixa-core
7554        // build time.
7555        //
7556        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
7557        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
7558        // accept-set pins on the peer closed-set typed-enum `str → Self`
7559        // axes.
7560        for (wire, expected) in [
7561            (
7562                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7563                RestartStrategy::OneForOne,
7564            ),
7565            (
7566                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7567                RestartStrategy::OneForAll,
7568            ),
7569            (
7570                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7571                RestartStrategy::RestForOne,
7572            ),
7573            (
7574                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7575                RestartStrategy::SimpleOneForOne,
7576            ),
7577        ] {
7578            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7579                panic!(
7580                    "RestartStrategy::from_wire({wire:?}) must accept every \
7581                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
7582                     lifted canonical byte-string that RestartStrategy::{expected:?} \
7583                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
7584                )
7585            });
7586            assert_eq!(
7587                parsed, expected,
7588                "RestartStrategy::from_wire({wire:?}) must return \
7589                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
7590            );
7591        }
7592    }
7593
7594    #[test]
7595    fn restart_strategy_from_wire_round_trips_through_as_str() {
7596        // Fail-before-pass-after pin on the closed round-trip between
7597        // the forward [`RestartStrategy::as_str`] emitter and the
7598        // reverse [`RestartStrategy::from_wire`] parser: for every
7599        // variant in [`RestartStrategy::ALL`], parsing the emitter's
7600        // output must return exactly the same variant. Any per-arm
7601        // divergence — a future arm added to `as_str` but not
7602        // `from_wire`, an accidental copy-paste flip in one but not
7603        // the other — silently splits the emit and parse halves and
7604        // the failure surfaces at consumer parse time far from the
7605        // drift site. The `ALL`-iterating shape means a future arm
7606        // addition picks up the coverage by construction.
7607        //
7608        // Peer of the sibling
7609        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
7610        // (18c7342) round-trip pin on
7611        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
7612        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
7613        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
7614        for &variant in RestartStrategy::ALL {
7615            let wire = variant.as_str();
7616            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7617                panic!(
7618                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7619                     must be Some({variant:?}) — the two halves of the round-trip \
7620                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
7621                     got None on wire byte-string {wire:?}"
7622                )
7623            });
7624            assert_eq!(
7625                parsed, variant,
7626                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7627                 must round-trip to the same variant; got {parsed:?}"
7628            );
7629        }
7630    }
7631
7632    #[test]
7633    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
7634        // Fail-before-pass-after pin on the closed-set refusal
7635        // discipline of [`RestartStrategy::from_wire`]: every
7636        // byte-string outside the four-arm accept-set returns `None`
7637        // rather than silently collapsing onto the [`Default`]
7638        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
7639        // exercised here sweeps the load-bearing drift shapes: the
7640        // empty string (a stripped serde-attribute drift), all-
7641        // whitespace strings (the canonical text-editor accidental
7642        // padding shape), the kebab-case dispatcher-catalog identities
7643        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
7644        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
7645        // derived [`std::str::FromStr`] accept-set, which parses the
7646        // *other* axis of this enum's two-axis split and must not leak
7647        // into the `from_wire` PascalCase-wire accept-set), the
7648        // lowercased single-word forms (`"oneforone"`), the padded
7649        // canonical scalar (`" OneForOne "`), the trailing-newline
7650        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
7651        // (`"AllForOne"` — the canonical typo direction).
7652        //
7653        // Peer of the sibling
7654        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
7655        // (2aa6d23) +
7656        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
7657        // (18c7342) refusal pins on the peer closed-set typed-enum
7658        // axes.
7659        for bad in [
7660            "",
7661            " ",
7662            "\n",
7663            "\t",
7664            "one-for-one",
7665            "one-for-all",
7666            "rest-for-one",
7667            "simple-one-for-one",
7668            "oneforone",
7669            "OneForOnes",
7670            "one_for_one",
7671            "one for one",
7672            "ONEFORONE",
7673            "OneForOne ",
7674            " OneForOne",
7675            " SimpleOneForOne ",
7676            "OneForOne\n",
7677            "restforone",
7678            "REST_FOR_ONE",
7679            "AllForOne",
7680            "Simple",
7681            "?",
7682        ] {
7683            assert!(
7684                RestartStrategy::from_wire(bad).is_none(),
7685                "RestartStrategy::from_wire({bad:?}) must return None — the \
7686                 parser's accept-set is exactly the four RestartStrategy::as_str \
7687                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
7688                 and this byte-string is outside that closed set"
7689            );
7690        }
7691    }
7692
7693    #[test]
7694    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
7695        // Fail-before-pass-after pin on the fourth path of the four-path
7696        // convergence: `from_wire` (the reverse projection) inverts the
7697        // `Serialize` derive's wire byte-string on every variant.
7698        // Together with the pre-existing three-path convergence
7699        // (`Display` + `as_str` + `Serialize` all resolve to the same
7700        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
7701        // pinned by
7702        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
7703        // this closes the round-trip: the wire byte-string the
7704        // `Serialize` derive emits parses back to the same variant
7705        // through `from_wire`, so any future serde-attribute or variant-
7706        // rename drift on the emit half now surfaces as a matched drift
7707        // on the parse half at caixa-core build time — the two halves
7708        // migrate as a unit through the lifted consts on any future
7709        // rename, and the round-trip cannot silently split.
7710        //
7711        // Peer of the sibling
7712        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7713        // (18c7342) wire-format pin on
7714        // [`crate::aplicacao::PlacementStrategy::from_wire`].
7715        for &variant in RestartStrategy::ALL {
7716            let wire = serde_json::to_string(&variant).unwrap();
7717            let unquoted = wire
7718                .strip_prefix('"')
7719                .and_then(|s| s.strip_suffix('"'))
7720                .expect("serialized RestartStrategy is a JSON string");
7721            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
7722                panic!(
7723                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
7724                     Serialize derive's wire byte-string for \
7725                     RestartStrategy::{variant:?} — the four-path convergence \
7726                     (Display + as_str + Serialize + from_wire) resolves through \
7727                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
7728                )
7729            });
7730            assert_eq!(
7731                parsed, variant,
7732                "RestartStrategy::from_wire of the Serialize derive's wire \
7733                 byte-string for RestartStrategy::{variant:?} must round-trip \
7734                 to the same variant; got {parsed:?}"
7735            );
7736        }
7737    }
7738
7739    #[test]
7740    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
7741        // Fail-before-pass-after byte-parity pin on the newly lifted
7742        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
7743        // library trait impl and the substrate-primitive
7744        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
7745        // the same four-arm accept-set across every arm the exhaustive
7746        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7747        // detour that routes the trait impl through a divergent projection
7748        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
7749        // … }` re-inlining that opens a compile-time link to the un-
7750        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
7751        // attribute drift that silently splits the wire byte-string from
7752        // every consumer that reaches for this typed dispatch, an
7753        // accidental swap onto the kebab-case dispatcher-catalog axis the
7754        // pre-existing [`std::str::FromStr`] impl parses through and which
7755        // would collide the two-axis wire/catalog split the sibling
7756        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
7757        // trips at caixa-core test time under `assert_eq!` rather than at
7758        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
7759        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
7760        // carries so no arm's projection is covered only by the sibling
7761        // method-named `from_wire` path. Peer of the sibling
7762        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
7763        // (3c83606),
7764        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
7765        // (bf33136), and the M3
7766        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
7767        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
7768        // onto the first M2-OTP-shape closed-set typed enum on the caixa
7769        // surface.
7770        for &variant in RestartStrategy::ALL {
7771            let wire = variant.as_str();
7772            assert_eq!(
7773                <RestartStrategy as TryFrom<&str>>::try_from(wire),
7774                Ok(variant),
7775                "TryFrom<&str> impl on RestartStrategy must round-trip \
7776                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
7777                 Ok(RestartStrategy::{variant:?}) — divergence from \
7778                 RestartStrategy::from_wire signals a silent detour off \
7779                 the substrate-primitive accessor"
7780            );
7781            assert_eq!(
7782                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
7783                RestartStrategy::from_wire(wire),
7784                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
7785                 RestartStrategy::from_wire on the same input"
7786            );
7787        }
7788    }
7789
7790    #[test]
7791    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
7792        // Rejection witness on the `impl TryFrom<&str> for
7793        // RestartStrategy` — sweeps a candidate set of byte-strings
7794        // outside the four-arm PascalCase wire accept-set the sibling
7795        // [`RestartStrategy::as_str`] emits and asserts every one lands on
7796        // `Err(())`, so a future accidental widening of the trait impl's
7797        // accept-set (a stray additional
7798        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
7799        // path, a silent inclusion of the kebab-case dispatcher-catalog
7800        // byte-string the pre-existing [`std::str::FromStr`] impl the
7801        // [`gen_platform::FromStrKind`] derive installs parses onto the
7802        // wire axis — which would collide the two-axis
7803        // wire/dispatcher-catalog split the sibling
7804        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
7805        // an English-rebrand or plural-arm silent alias that would
7806        // widen the wire accept-set past the OTP-canonical four) trips at
7807        // caixa-core test time. The candidate set includes the empty
7808        // string, whitespace-only padding, the kebab-case dispatcher-
7809        // catalog byte-strings on the sibling axis (a caller who confuses
7810        // the two axes trips here rather than at a downstream consumer's
7811        // silent reject), a lowercase / uppercase / mixed-case fold of
7812        // each PascalCase arm (a caller who assumes case-fold acceptance
7813        // trips here), leading/trailing whitespace padding, the trailing-
7814        // newline shape, quote-wrapped candidates, and a residual set of
7815        // plausible-but-wrong English rebrand candidates. Peer of the
7816        // sibling
7817        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
7818        // (3c83606) and
7819        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
7820        // (6fd00cd) rejection witnesses.
7821        let rejected: &[&str] = &[
7822            "",
7823            " ",
7824            "\n",
7825            "\t",
7826            "one-for-one",
7827            "one-for-all",
7828            "rest-for-one",
7829            "simple-one-for-one",
7830            "oneforone",
7831            "one_for_one",
7832            "OneForOnes",
7833            "ONEFORONE",
7834            "oneforall",
7835            "restforone",
7836            "simpleoneforone",
7837            "OneForOne ",
7838            " OneForOne",
7839            " OneForAll ",
7840            "OneForOne\n",
7841            "RestForOne\t",
7842            "OneForEach",
7843            "AllForOne",
7844            "one for one",
7845            "\"OneForOne\"",
7846            "?",
7847        ];
7848        for &input in rejected {
7849            assert_eq!(
7850                <RestartStrategy as TryFrom<&str>>::try_from(input),
7851                Err(()),
7852                "TryFrom<&str> impl on RestartStrategy must reject the \
7853                 non-wire byte-string {input:?} — silent acceptance signals \
7854                 an accept-set widening off the paired \
7855                 RestartStrategy::from_wire resolver"
7856            );
7857        }
7858    }
7859
7860    #[test]
7861    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
7862        // Cross-axis partition pin: the paired `TryFrom<&str>` and
7863        // `from_wire` reverse projections must resolve identically on
7864        // *every* input, not just the ones [`RestartStrategy::ALL`]
7865        // enumerates. Sweeps a mixed candidate set spanning accepted
7866        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
7867        // dispatcher-catalog byte-strings, empty, whitespace-padded,
7868        // quoted, English-rebrand candidates) inputs and asserts the
7869        // trait's `Result::ok()` projection byte-equals the method-named
7870        // resolver's `Option<Self>` return-shape on each, locking the two
7871        // paths together by construction so any future detour (a stray
7872        // `try_from` special-case that widens or narrows the accept-set
7873        // outside the paired `from_wire` resolver, an accidental swap
7874        // onto the kebab-case [`std::str::FromStr`] impl the
7875        // [`gen_platform::FromStrKind`] derive installs on the sibling
7876        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
7877        // the sibling
7878        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
7879        // pin — extends the round-trip discipline onto the M2-OTP-shape
7880        // sibling-restart axis.
7881        let candidates: &[&str] = &[
7882            "OneForOne",
7883            "OneForAll",
7884            "RestForOne",
7885            "SimpleOneForOne",
7886            "",
7887            "one-for-one",
7888            "one-for-all",
7889            "rest-for-one",
7890            "simple-one-for-one",
7891            "oneforone",
7892            "unknown",
7893            "OneForOne ",
7894            " OneForOne",
7895            "\"OneForOne\"",
7896            "OneForEach",
7897            "?",
7898        ];
7899        for &input in candidates {
7900            let via_trait: Option<RestartStrategy> =
7901                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
7902            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
7903            assert_eq!(
7904                via_trait, via_method,
7905                "TryFrom<&str> and from_wire must resolve identically on \
7906                 input {input:?} — divergence signals the two reverse-\
7907                 projection paths have drifted onto different accept-sets"
7908            );
7909        }
7910    }
7911
7912    #[test]
7913    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
7914        // Fail-before-pass-after byte-parity pin on the newly lifted
7915        // `impl From<RestartStrategy> for &'static str` — asserts the
7916        // standard-library trait impl and the substrate-primitive
7917        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
7918        // the same four-arm emit-set across every arm the exhaustive
7919        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7920        // detour that routes the trait impl through a divergent
7921        // projection (a per-arm inline `match strategy { OneForOne =>
7922        // "OneForOne", … }` re-inlining that opens a compile-time link to
7923        // the un-lifted arm-literal, an accidental swap onto the sibling
7924        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
7925        // would collide the two-axis wire/catalog split the sibling
7926        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
7927        // at caixa-core test time under `assert_eq!` rather than at a
7928        // downstream `impl Into<&'static str>`-bound consumer's silent
7929        // split. Sweeps every one of the four arms
7930        // [`RestartStrategy::ALL`] carries so no arm's projection is
7931        // covered only by the sibling method-named `as_str` /
7932        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
7933        // `<&'static str as From<RestartStrategy>>::from` output in a
7934        // `const`-shape binding to make the `'static` lifetime promise a
7935        // build-time invariant — a future accidental downgrade of any of
7936        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7937        // constants to a non-`&'static str` (a `String::leak()`-produced
7938        // return, a `Box::leak`-cast) trips at caixa-core build time
7939        // rather than at a downstream `'static`-bound consumer.
7940        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7941        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7942        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7943        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7944        for &variant in RestartStrategy::ALL {
7945            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7946            let via_method: &'static str = variant.as_str();
7947            assert_eq!(
7948                via_trait, via_method,
7949                "From<RestartStrategy> for &'static str impl must round-trip \
7950                 RestartStrategy::{variant:?} to the same lifted \
7951                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
7952                 divergence signals a silent detour off the substrate-primitive \
7953                 accessor"
7954            );
7955            let via_into: &'static str = variant.into();
7956            assert_eq!(
7957                via_into, via_method,
7958                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
7959                 byte-equal RestartStrategy::as_str on the same input — the \
7960                 blanket-derived Into shape must resolve to the same as_str \
7961                 dispatch as the explicit From impl"
7962            );
7963        }
7964        assert_eq!(
7965            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7966            [
7967                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7968                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7969                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7970                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7971            ],
7972            "const-context RestartStrategy::as_str must resolve to the four \
7973             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
7974             downgrade of any arm to a non-const or non-static byte-string \
7975             breaks the `&'static str`-lifetime promise the paired \
7976             From<RestartStrategy> for &'static str impl carries by \
7977             construction"
7978        );
7979    }
7980
7981    #[test]
7982    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
7983        // Cross-axis partition pin: the paired trait-idiomatic
7984        // `From<RestartStrategy> for &'static str` forward projection and
7985        // the method-named [`RestartStrategy::as_str`] forward projection
7986        // must resolve identically on *every* arm, not just the ones
7987        // named in the primary byte-parity pin above. Sweeps every
7988        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
7989        // output byte-equals the method-named accessor's return-value on
7990        // each, locking the two forward-projection paths together by
7991        // construction so any future detour (a stray `From` special-case
7992        // that lands on a divergent per-arm literal outside the paired
7993        // `as_str` dispatch, a hypothetical rebrand touching one axis
7994        // without the other) trips at caixa-core test time. Peer of the
7995        // sibling reverse-projection partition pin
7996        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7997        // — extends the round-trip discipline onto the trait-idiomatic
7998        // *forward* axis, closing the two-way `Self ↔ &'static str`
7999        // round-trip on the trait-idiomatic pair
8000        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
8001        // well as the pre-existing method-named pair
8002        // (`as_str` + `from_wire`).
8003        for &variant in RestartStrategy::ALL {
8004            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8005            let via_method: &'static str = variant.as_str();
8006            assert_eq!(
8007                via_trait, via_method,
8008                "From<RestartStrategy> for &'static str and \
8009                 RestartStrategy::as_str must resolve identically on \
8010                 RestartStrategy::{variant:?} — divergence signals the \
8011                 two forward-projection paths have drifted onto different \
8012                 emit-sets"
8013            );
8014        }
8015        // Round-trip witness: every arm's forward `From` output re-parses
8016        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8017        // to the original variant. Closes the two-way `RestartStrategy ↔
8018        // &'static str` round-trip on the trait-idiomatic axis pair,
8019        // mirroring the pre-existing method-named `as_str` + `from_wire`
8020        // round-trip on the substrate-primitive axis pair.
8021        for &variant in RestartStrategy::ALL {
8022            let emitted: &'static str = variant.into();
8023            let re_parsed: Result<RestartStrategy, ()> =
8024                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8025            assert_eq!(
8026                re_parsed,
8027                Ok(variant),
8028                "trait-idiomatic axis pair must round-trip \
8029                 RestartStrategy::{variant:?} through `.into::<&'static \
8030                 str>()` and back through `TryFrom<&str>` — a break signals \
8031                 the forward-emit and reverse-parse axes have drifted onto \
8032                 different vocabularies"
8033            );
8034        }
8035    }
8036
8037    #[test]
8038    fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
8039        // Fail-before-pass-after byte-parity pin on the newly lifted
8040        // `impl From<&RestartStrategy> for &'static str` — asserts the
8041        // borrowed-input standard-library trait impl and the substrate-
8042        // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
8043        // resolve to the same four-arm emit-set across every arm the
8044        // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
8045        // `From` trait does not auto-derive the borrowed-input sibling
8046        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8047        // where T: Copy, U: From<T>` blanket in `core`), so the
8048        // borrowed-input axis is a distinct trait-idiomatic surface
8049        // that a `.iter().map(Into::into)` shape over
8050        // [`RestartStrategy::ALL`] (whose iterator yields
8051        // `&RestartStrategy`, not `RestartStrategy`) reaches through
8052        // this impl and no other — the paired owned-input
8053        // [`From<RestartStrategy>`] impl requires an explicit
8054        // `.copied()` / dereference before the trait fires.
8055        // Materializes the `<&'static str as
8056        // From<&RestartStrategy>>::from` output in a `const`-shape
8057        // binding to make the `'static` lifetime promise a build-time
8058        // invariant.
8059        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8060        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8061        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8062        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8063        for variant in RestartStrategy::ALL {
8064            let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
8065            let via_method: &'static str = variant.as_str();
8066            assert_eq!(
8067                via_trait, via_method,
8068                "From<&RestartStrategy> for &'static str impl must \
8069                 round-trip &RestartStrategy::{variant:?} to the same \
8070                 lifted SUPERVISOR_ESTRATEGIA_* const \
8071                 RestartStrategy::as_str returns — divergence signals a \
8072                 silent detour off the substrate-primitive accessor"
8073            );
8074            let via_into: &'static str = variant.into();
8075            assert_eq!(
8076                via_into, via_method,
8077                "Into<&'static str>::into on &RestartStrategy::{variant:?} \
8078                 must byte-equal RestartStrategy::as_str on the same input — \
8079                 the blanket-derived Into shape must resolve to the same \
8080                 as_str dispatch as the explicit From impl"
8081            );
8082        }
8083        assert_eq!(
8084            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8085            [
8086                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8087                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8088                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8089                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8090            ],
8091            "const-context RestartStrategy::as_str must resolve to the \
8092             four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
8093             input From<&RestartStrategy> for &'static str impl inherits \
8094             its `'static` lifetime promise from the same accessor the \
8095             owned-input sibling routes through"
8096        );
8097    }
8098
8099    #[test]
8100    fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8101        // Cross-axis partition pin: the paired trait-idiomatic
8102        // owned-input `From<RestartStrategy> for &'static str` (523157d
8103        // campaign-shape) and borrowed-input `From<&RestartStrategy> for
8104        // &'static str` (this lift) forward projections must resolve
8105        // identically on every arm, locking the two input-shape paths
8106        // together so any future detour trips at caixa-core test time.
8107        // Then a witness that a `.iter().map(Into::into)` pipe over
8108        // [`RestartStrategy::ALL`] (whose iterator yields
8109        // `&RestartStrategy`) materializes the four-arm accept-set
8110        // through the borrowed-input axis alone — the exact shape a
8111        // future wasm-operator per-supervisor sibling-restart-strategy
8112        // diagnostic line, a future substrate-wide per-arm diagnostic
8113        // column, or a
8114        // `HashMap::<&'static str, RestartStrategy>::from_iter(
8115        //     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
8116        // per-strategy lookup reaches through — closing the two-way
8117        // owned/borrowed input-shape symmetry on the forward-projection
8118        // trait-idiomatic axis. Peer of the sibling
8119        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8120        // (64aa742) /
8121        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8122        // (5ab993a) /
8123        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8124        // (807b0b5) partition pins on the sibling closed-set typed-enum
8125        // discriminator axes — extends the borrowed-input axis
8126        // discipline onto the first M2 OTP-shape sibling-restart
8127        // closed-set typed enum on the caixa surface. Also closes the
8128        // direct two-way `&Self → &'static str → Self` round-trip via
8129        // the paired [`TryFrom<&str>`] axis — unlike the peer
8130        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
8131        // lowercase Portuguese diagnostic bytes while the reverse
8132        // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
8133        // trip through an intermediate wire-vocab hop), the
8134        // [`RestartStrategy::as_str`] emit and
8135        // [`RestartStrategy::from_wire`] parse share the same
8136        // `PascalCase` vocabulary by construction, so the borrowed-
8137        // input forward axis and the reverse axis compose directly.
8138        for &variant in RestartStrategy::ALL {
8139            let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8140            let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
8141            assert_eq!(
8142                owned, borrowed,
8143                "From<RestartStrategy> and From<&RestartStrategy> for \
8144                 &'static str must resolve identically on \
8145                 RestartStrategy::{variant:?} — divergence signals the \
8146                 owned-input and borrowed-input forward-projection paths \
8147                 have drifted onto different emit-sets"
8148            );
8149        }
8150        let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
8151        let via_method: Vec<&'static str> =
8152            RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
8153        assert_eq!(
8154            via_iter, via_method,
8155            "`.iter().map(Into::into)` over RestartStrategy::ALL must \
8156             byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
8157             borrowed-input `From<&RestartStrategy> for &'static str` \
8158             axis is what makes the `.iter().map(Into::into)` shape route \
8159             through the substrate-primitive `RestartStrategy::as_str` \
8160             accessor rather than through a per-call-site `.copied()` / \
8161             dereference detour"
8162        );
8163        for variant in RestartStrategy::ALL {
8164            let emitted: &'static str = variant.into();
8165            let re_parsed: Result<RestartStrategy, ()> =
8166                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8167            assert_eq!(
8168                re_parsed,
8169                Ok(*variant),
8170                "trait-idiomatic borrowed-input forward-projection + \
8171                 reverse-projection axis pair must round-trip \
8172                 &RestartStrategy::{variant:?} through `.into::<&'static \
8173                 str>()` (via the borrowed-input axis) and back through \
8174                 `TryFrom<&str>` — a break signals the borrowed-input \
8175                 forward-emit and reverse-parse axes have drifted onto \
8176                 different vocabularies"
8177            );
8178        }
8179    }
8180
8181    #[test]
8182    fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
8183        // Fail-before-pass-after byte-parity pin on the newly lifted
8184        // `impl From<RestartStrategy> for String` — asserts the
8185        // owned-`String`-returning standard-library trait impl and the
8186        // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
8187        // accessor resolve to the same four-arm emit-set across every
8188        // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
8189        // Rust's standard library does not carry a blanket
8190        // `impl<T: AsRef<str>> From<T> for String` (nor an
8191        // `impl<T: fmt::Display> From<T> for String`), so the
8192        // owned-`String` forward-projection axis is a distinct
8193        // trait-idiomatic surface that a
8194        // `let key: String = strategy.into();`-shaped call site
8195        // reaches through this impl and no other — the paired sibling
8196        // `From<RestartStrategy> for &'static str` impl forces every
8197        // owned-`String` call site through an explicit
8198        // `.to_owned()` / `String::from` restatement.
8199        for &variant in RestartStrategy::ALL {
8200            let via_trait: String = <String as From<RestartStrategy>>::from(variant);
8201            let via_method: &'static str = variant.as_str();
8202            assert_eq!(
8203                via_trait.as_str(),
8204                via_method,
8205                "From<RestartStrategy> for String impl must round-trip \
8206                 RestartStrategy::{variant:?} to the same lifted \
8207                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8208                 returns — divergence signals a silent detour off the \
8209                 substrate-primitive accessor"
8210            );
8211            let via_into: String = variant.into();
8212            assert_eq!(
8213                via_into.as_str(),
8214                via_method,
8215                "Into<String>::into on RestartStrategy::{variant:?} must \
8216                 byte-equal RestartStrategy::as_str on the same input — the \
8217                 blanket-derived Into shape must resolve to the same as_str \
8218                 dispatch as the explicit From impl"
8219            );
8220        }
8221    }
8222
8223    #[test]
8224    fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
8225        // Cross-axis partition pin: the paired trait-idiomatic
8226        // owned-`String` `From<RestartStrategy> for String` (this lift)
8227        // and owned-`&'static str` `From<RestartStrategy> for &'static
8228        // str` (523157d) forward projections must resolve identically
8229        // on every arm, locking the two return-type-shape paths
8230        // together so any future detour trips at caixa-core test time.
8231        // Also byte-parity witness against the sibling
8232        // [`ToString::to_string`] surface routed through
8233        // [`std::fmt::Display`] — the three owned-heap-string paths
8234        // (`.into::<String>()`, `String::from`, `.to_string()`) must
8235        // resolve identically on every arm so a future consumer that
8236        // picks any of the three lands on the same lifted
8237        // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
8238        // witness through the paired trait-idiomatic reverse
8239        // [`TryFrom<&str>`] axis on the owned-`String`'s
8240        // [`String::as_str`] borrow that closes the two-way
8241        // `Self → String → Self` round-trip on the trait-idiomatic
8242        // owned-`String` forward + reverse axis pair.
8243        for &variant in RestartStrategy::ALL {
8244            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8245            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8246            assert_eq!(
8247                owned_string.as_str(),
8248                owned_static,
8249                "From<RestartStrategy> for String and From<RestartStrategy> \
8250                 for &'static str must resolve identically on \
8251                 RestartStrategy::{variant:?} — divergence signals the \
8252                 owned-`String` and owned-`&'static str` forward-projection \
8253                 return-type-shape paths have drifted onto different \
8254                 emit-sets"
8255            );
8256            let via_to_string: String = variant.to_string();
8257            assert_eq!(
8258                owned_string, via_to_string,
8259                "From<RestartStrategy> for String must byte-equal \
8260                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8261                 divergence signals the trait-idiomatic owned-`String` \
8262                 forward-projection axis and the ToString-through-Display \
8263                 axis have drifted onto different emit-sets"
8264            );
8265        }
8266        let via_iter: Vec<String> = RestartStrategy::ALL
8267            .iter()
8268            .copied()
8269            .map(String::from)
8270            .collect();
8271        let via_method: Vec<String> = RestartStrategy::ALL
8272            .iter()
8273            .map(|s| s.as_str().to_owned())
8274            .collect();
8275        assert_eq!(
8276            via_iter, via_method,
8277            "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
8278             must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
8279             every arm — the owned-`String` `From<RestartStrategy> for \
8280             String` axis is what makes the `String::from` composition \
8281             route through the substrate-primitive `RestartStrategy::as_str` \
8282             accessor rather than through a per-call-site `.to_owned()` / \
8283             `String::from(strategy.as_str())` detour"
8284        );
8285        for &variant in RestartStrategy::ALL {
8286            let emitted: String = variant.into();
8287            let re_parsed: Result<RestartStrategy, ()> =
8288                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8289            assert_eq!(
8290                re_parsed,
8291                Ok(variant),
8292                "trait-idiomatic owned-`String` forward-projection + \
8293                 reverse-projection axis pair must round-trip \
8294                 RestartStrategy::{variant:?} through `.into::<String>()` \
8295                 and back through `TryFrom<&str>` on the owned-`String`'s \
8296                 String::as_str borrow — a break signals the owned-`String` \
8297                 forward-emit and reverse-parse axes have drifted onto \
8298                 different vocabularies"
8299            );
8300        }
8301    }
8302
8303    #[test]
8304    fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
8305        // Fail-before-pass-after byte-parity pin on the newly lifted
8306        // `impl From<&RestartStrategy> for String` — asserts the
8307        // borrowed-input owned-`String`-returning standard-library trait
8308        // impl and the substrate-primitive [`RestartStrategy::as_str`]
8309        // `pub const fn` accessor resolve to the same four-arm emit-set
8310        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
8311        // enumerates. Rust's standard library does not carry a blanket
8312        // `impl<T: AsRef<str>> From<&T> for String` (nor an
8313        // `impl<T: fmt::Display> From<&T> for String`), so the
8314        // borrowed-input owned-`String` forward-projection axis is a
8315        // distinct trait-idiomatic surface that a
8316        // `let key: String = (&strategy).into();`-shaped call site
8317        // reaches through this impl and no other — the paired sibling
8318        // `From<RestartStrategy> for String` impl forces every
8319        // borrowed-input call site through an explicit `Copy` deref
8320        // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
8321        // `.to_string()` detour.
8322        for &variant in RestartStrategy::ALL {
8323            let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
8324            let via_method: &'static str = variant.as_str();
8325            assert_eq!(
8326                via_trait.as_str(),
8327                via_method,
8328                "From<&RestartStrategy> for String impl must round-trip \
8329                 &RestartStrategy::{variant:?} to the same lifted \
8330                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8331                 returns — divergence signals a silent detour off the \
8332                 substrate-primitive accessor"
8333            );
8334            let via_into: String = (&variant).into();
8335            assert_eq!(
8336                via_into.as_str(),
8337                via_method,
8338                "Into<String>::into on &RestartStrategy::{variant:?} must \
8339                 byte-equal RestartStrategy::as_str on the same input — the \
8340                 blanket-derived Into shape must resolve to the same as_str \
8341                 dispatch as the explicit From impl"
8342            );
8343        }
8344    }
8345
8346    #[test]
8347    fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
8348        // Cross-axis partition pin: the newly lifted trait-idiomatic
8349        // borrowed-input owned-`String` `From<&RestartStrategy> for
8350        // String` (this lift), the paired owned-input owned-`String`
8351        // `From<RestartStrategy> for String` (7baa18a), the paired
8352        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8353        // for &'static str` (e941836), and the paired owned-input
8354        // owned-`&'static str` `From<RestartStrategy> for &'static str`
8355        // (523157d) — every corner of the `{Self, &Self} × {&'static
8356        // str, String}` 2×2 trait-idiomatic projection family — must
8357        // resolve identically on every arm, locking the four
8358        // return-shape × input-shape paths together so any future
8359        // detour trips at caixa-core test time. Also byte-parity
8360        // witness against the sibling [`ToString::to_string`] surface
8361        // routed through [`std::fmt::Display`] and a direct round-trip
8362        // witness through the paired trait-idiomatic reverse
8363        // [`TryFrom<&str>`] axis on the owned-`String`'s
8364        // [`String::as_str`] borrow that closes the two-way
8365        // `&Self → String → Self` round-trip on the trait-idiomatic
8366        // borrowed-input owned-`String` forward + reverse axis pair.
8367        for &variant in RestartStrategy::ALL {
8368            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
8369            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8370            let borrowed_static: &'static str =
8371                <&'static str as From<&RestartStrategy>>::from(&variant);
8372            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8373            assert_eq!(
8374                borrowed_string, owned_string,
8375                "From<&RestartStrategy> for String and From<RestartStrategy> \
8376                 for String must resolve identically on \
8377                 RestartStrategy::{variant:?} — divergence signals the \
8378                 borrowed-input and owned-input owned-`String` \
8379                 forward-projection input-shape paths have drifted onto \
8380                 different emit-sets"
8381            );
8382            assert_eq!(
8383                borrowed_string.as_str(),
8384                borrowed_static,
8385                "From<&RestartStrategy> for String and From<&RestartStrategy> \
8386                 for &'static str must resolve identically on \
8387                 RestartStrategy::{variant:?} — divergence signals the \
8388                 borrowed-input `&'static str` and owned-`String` \
8389                 return-shape paths have drifted onto different emit-sets"
8390            );
8391            assert_eq!(
8392                borrowed_string.as_str(),
8393                owned_static,
8394                "From<&RestartStrategy> for String and From<RestartStrategy> \
8395                 for &'static str must resolve identically on \
8396                 RestartStrategy::{variant:?} — divergence signals a break \
8397                 in the diagonal corner of the {{Self, &Self}} × \
8398                 {{&'static str, String}} 2×2 trait-idiomatic \
8399                 projection family"
8400            );
8401            let via_to_string: String = variant.to_string();
8402            assert_eq!(
8403                borrowed_string, via_to_string,
8404                "From<&RestartStrategy> for String must byte-equal \
8405                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8406                 divergence signals the trait-idiomatic borrowed-input \
8407                 owned-`String` forward-projection axis and the \
8408                 ToString-through-Display axis have drifted onto different \
8409                 emit-sets"
8410            );
8411        }
8412        let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
8413        let via_method: Vec<String> = RestartStrategy::ALL
8414            .iter()
8415            .map(|s| s.as_str().to_owned())
8416            .collect();
8417        assert_eq!(
8418            via_iter, via_method,
8419            "`.iter().map(String::from)` over RestartStrategy::ALL — a \
8420             call site whose iteration axis holds `&RestartStrategy` by \
8421             construction — must byte-equal `.iter().map(|s| \
8422             s.as_str().to_owned())` on every arm — the borrowed-input \
8423             owned-`String` `From<&RestartStrategy> for String` axis is \
8424             what makes the `String::from` composition route through the \
8425             substrate-primitive `RestartStrategy::as_str` accessor \
8426             without a spurious `Copy` deref (which would only be \
8427             reachable through the owned-input `From<RestartStrategy> for \
8428             String` axis by first calling `.copied()` on the iterator)"
8429        );
8430        for &variant in RestartStrategy::ALL {
8431            let emitted: String = (&variant).into();
8432            let re_parsed: Result<RestartStrategy, ()> =
8433                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8434            assert_eq!(
8435                re_parsed,
8436                Ok(variant),
8437                "trait-idiomatic borrowed-input owned-`String` \
8438                 forward-projection + reverse-projection axis pair must \
8439                 round-trip &RestartStrategy::{variant:?} through \
8440                 `.into::<String>()` on the borrowed-input surface and \
8441                 back through `TryFrom<&str>` on the owned-`String`'s \
8442                 String::as_str borrow — a break signals the \
8443                 borrowed-input owned-`String` forward-emit and \
8444                 reverse-parse axes have drifted onto different \
8445                 vocabularies"
8446            );
8447        }
8448    }
8449
8450    #[test]
8451    fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
8452        // Fail-before-pass-after byte-parity pin on the newly lifted
8453        // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
8454        // asserts the standard-library trait impl and the substrate-
8455        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
8456        // accessor resolve to the same four-arm emit-set across every
8457        // arm the exhaustive [`super::RestartStrategy::ALL`] slice
8458        // enumerates. Rust's standard library does not carry a blanket
8459        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
8460        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
8461        // the `Cow<'static, str>` forward-projection axis is a
8462        // distinct trait-idiomatic surface that a
8463        // `let key: Cow<'static, str> = strategy.into();`-shaped call
8464        // site reaches through this impl and no other — the paired
8465        // sibling `From<RestartStrategy> for &'static str` and
8466        // `From<RestartStrategy> for String` impls force every
8467        // `Cow<'static, str>`-parameterized call site through a
8468        // `Cow::Borrowed(strategy.as_str())` /
8469        // `Cow::Owned(strategy.to_string())` composition whose type
8470        // bounds have no compile-time link back to the substrate
8471        // primitive.
8472        //
8473        // Also asserts the projection lands on the zero-alloc
8474        // [`std::borrow::Cow::Borrowed`] arm (not the
8475        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8476        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8477        // return lifetime by construction makes the borrowed arm the
8478        // type-correct projection with no runtime allocation. Any
8479        // future silent detour that routes the impl through the owned
8480        // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
8481        // that would allocate on every call site where the
8482        // `&'static str` return of [`super::RestartStrategy::as_str`]
8483        // makes the zero-alloc borrowed projection type-correct) trips
8484        // at caixa-core test time under the
8485        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
8486        // than at a downstream `Cow<'static, str>`-bound consumer's
8487        // silent allocation.
8488        //
8489        // First peer on the substrate-wide trait-idiomatic
8490        // [`std::borrow::Cow<'static, str>`] forward-projection family
8491        // to extend the axis off the top-level [`super::CaixaKind`]
8492        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
8493        // first M2 OTP-shape closed-set fieldless typed enum on the
8494        // caixa surface.
8495        for &variant in RestartStrategy::ALL {
8496            let via_trait: std::borrow::Cow<'static, str> =
8497                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8498            let via_method: &'static str = variant.as_str();
8499            assert_eq!(
8500                via_trait.as_ref(),
8501                via_method,
8502                "From<RestartStrategy> for Cow<'static, str> impl must \
8503                 round-trip RestartStrategy::{variant:?} to the same \
8504                 lifted SUPERVISOR_ESTRATEGIA_* const \
8505                 RestartStrategy::as_str returns — divergence signals a \
8506                 silent detour off the substrate-primitive accessor"
8507            );
8508            assert!(
8509                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
8510                "From<RestartStrategy> for Cow<'static, str> impl must \
8511                 land on the zero-alloc Cow::Borrowed arm on \
8512                 RestartStrategy::{variant:?} — a Cow::Owned outcome \
8513                 signals the projection has silently allocated where \
8514                 the substrate-primitive RestartStrategy::as_str \
8515                 `&'static str` return makes the borrowed arm the \
8516                 type-correct projection"
8517            );
8518            let via_into: std::borrow::Cow<'static, str> = variant.into();
8519            assert_eq!(
8520                via_into.as_ref(),
8521                via_method,
8522                "Into<Cow<'static, str>>::into on \
8523                 RestartStrategy::{variant:?} must byte-equal \
8524                 RestartStrategy::as_str on the same input — the \
8525                 blanket-derived Into shape must resolve to the same \
8526                 as_str dispatch as the explicit From impl"
8527            );
8528            assert!(
8529                matches!(via_into, std::borrow::Cow::Borrowed(_)),
8530                "Into<Cow<'static, str>>::into on \
8531                 RestartStrategy::{variant:?} must land on the \
8532                 zero-alloc Cow::Borrowed arm — the blanket-derived \
8533                 Into shape must resolve to the same Cow::Borrowed \
8534                 dispatch as the explicit From impl"
8535            );
8536        }
8537    }
8538
8539    #[test]
8540    fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
8541        // Cross-axis partition pin: the newly lifted trait-idiomatic
8542        // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
8543        // (this lift), the paired owned-input `From<RestartStrategy>
8544        // for &'static str` (523157d), and the paired owned-input
8545        // `From<RestartStrategy> for String` (7baa18a) forward
8546        // projections must resolve identically on every arm, locking
8547        // the three return-shape paths together by construction so any
8548        // future detour trips at caixa-core test time. Also byte-parity
8549        // witness against the sibling [`ToString::to_string`] surface
8550        // routed through [`std::fmt::Display`] — every owned-heap-
8551        // string path (the `Cow::Owned` promotion of this axis's
8552        // `.into_owned()`, `From<RestartStrategy> for String`, and
8553        // `.to_string()`) resolves to the same lifted
8554        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
8555        //
8556        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
8557        // witness over [`super::RestartStrategy::ALL`] that
8558        // materializes the four-arm accept-set through the
8559        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
8560        // shape a future `axum::response::IntoResponse` per-strategy
8561        // rejection-body composer, a future M4 admission-webhook
8562        // per-strategy rejection-reason emitter whose typing rules out
8563        // the sibling [`AsRef<str>`] borrowed return, or a future
8564        // substrate-wide per-strategy diagnostic surface that binds
8565        // through a [`Cow<'static, str>`] boundary reaches through.
8566        // The pipe witness also pins the zero-alloc discipline: every
8567        // element in the collected vector satisfies the
8568        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
8569        // accidental silent-allocation regression on the pipe's
8570        // iteration axis is a caixa-core-test-time failure.
8571        for &variant in RestartStrategy::ALL {
8572            let via_cow: std::borrow::Cow<'static, str> =
8573                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8574            let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8575            let via_string: String = <String as From<RestartStrategy>>::from(variant);
8576            assert_eq!(
8577                via_cow.as_ref(),
8578                via_static,
8579                "From<RestartStrategy> for Cow<'static, str> and \
8580                 From<RestartStrategy> for &'static str must resolve \
8581                 identically on RestartStrategy::{variant:?} — \
8582                 divergence signals the Cow<'static, str> and \
8583                 &'static str return-shape paths have drifted onto \
8584                 different emit-sets"
8585            );
8586            assert_eq!(
8587                via_cow.as_ref(),
8588                via_string.as_str(),
8589                "From<RestartStrategy> for Cow<'static, str> and \
8590                 From<RestartStrategy> for String must resolve \
8591                 identically on RestartStrategy::{variant:?} — \
8592                 divergence signals the Cow<'static, str> and String \
8593                 return-shape paths have drifted onto different \
8594                 emit-sets"
8595            );
8596            let via_to_string: String = variant.to_string();
8597            assert_eq!(
8598                via_cow.as_ref(),
8599                via_to_string.as_str(),
8600                "From<RestartStrategy> for Cow<'static, str> must \
8601                 byte-equal RestartStrategy::to_string on \
8602                 RestartStrategy::{variant:?} — divergence signals the \
8603                 trait-idiomatic Cow<'static, str> forward-projection \
8604                 axis and the ToString-through-Display axis have \
8605                 drifted onto different emit-sets"
8606            );
8607        }
8608        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8609            .iter()
8610            .copied()
8611            .map(std::borrow::Cow::from)
8612            .collect();
8613        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8614            .iter()
8615            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
8616            .collect();
8617        assert_eq!(
8618            via_iter, via_method,
8619            "`.iter().copied().map(Cow::from)` over \
8620             RestartStrategy::ALL must byte-equal `.iter().map(|s| \
8621             Cow::Borrowed(s.as_str()))` on every arm — the \
8622             trait-idiomatic `From<RestartStrategy> for Cow<'static, \
8623             str>` axis is what makes the `Cow::from` composition \
8624             route through the substrate-primitive \
8625             `RestartStrategy::as_str` accessor with the zero-alloc \
8626             Cow::Borrowed arm by construction, rather than a \
8627             per-call-site `Cow::Owned(strategy.to_string())` \
8628             allocation"
8629        );
8630        for cow in &via_iter {
8631            assert!(
8632                matches!(cow, std::borrow::Cow::Borrowed(_)),
8633                "every element of the \
8634                 .iter().copied().map(Cow::from) pipe over \
8635                 RestartStrategy::ALL must land on the zero-alloc \
8636                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
8637                 signals the pipe's iteration axis has silently \
8638                 allocated where the substrate-primitive \
8639                 RestartStrategy::as_str `&'static str` return makes \
8640                 the borrowed arm the type-correct projection"
8641            );
8642        }
8643    }
8644
8645    #[test]
8646    fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
8647        // Fail-before-pass-after byte-parity pin on the newly lifted
8648        // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
8649        // asserts the borrowed-input standard-library trait impl and
8650        // the substrate-primitive [`super::RestartStrategy::as_str`]
8651        // `pub const fn` accessor resolve to the same four-arm emit-
8652        // set across every arm the exhaustive
8653        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
8654        // standard library does not carry a blanket
8655        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
8656        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
8657        // the borrowed-input `Cow<'static, str>` forward-projection
8658        // axis is a distinct trait-idiomatic surface that a
8659        // `let key: Cow<'static, str> = (&strategy).into();`-shaped
8660        // call site or a
8661        // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
8662        // reaches through this impl and no other — the paired owned-
8663        // input `From<RestartStrategy> for Cow<'static, str>` impl
8664        // (7dd28b3) forces every borrowed-input call site through an
8665        // explicit `Copy` deref (`Cow::from(*strategy)`) or a
8666        // `Cow::Borrowed(strategy.as_str())` open-code whose type
8667        // bounds have no compile-time link back to the substrate
8668        // primitive.
8669        //
8670        // Also asserts the projection lands on the zero-alloc
8671        // [`std::borrow::Cow::Borrowed`] arm (not the
8672        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8673        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8674        // return lifetime by construction makes the borrowed arm the
8675        // type-correct projection with no runtime allocation on the
8676        // borrowed-input surface just as on the paired owned-input
8677        // surface.
8678        //
8679        // Second peer on the substrate-wide trait-idiomatic
8680        // [`std::borrow::Cow<'static, str>`] forward-projection family
8681        // on this enum — closes the `{Self, &Self}` input-shape
8682        // corner of the [`Cow<'static, str>`] axis on the first M2
8683        // OTP-shape closed-set fieldless typed enum peer on the caixa
8684        // surface (`:supervisor :estrategia`), exactly as d45c409
8685        // closed it on the top-level [`super::CaixaKind`] one commit
8686        // after the owning half (99c1735) landed. Every future
8687        // closed-set fieldless typed enum peer on the substrate is a
8688        // future target of the campaign.
8689        for &variant in RestartStrategy::ALL {
8690            let via_trait: std::borrow::Cow<'static, str> =
8691                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
8692            let via_method: &'static str = variant.as_str();
8693            assert_eq!(
8694                via_trait.as_ref(),
8695                via_method,
8696                "From<&RestartStrategy> for Cow<'static, str> impl must \
8697                 round-trip &RestartStrategy::{variant:?} to the same \
8698                 lifted SUPERVISOR_ESTRATEGIA_* const \
8699                 RestartStrategy::as_str returns — divergence signals a \
8700                 silent detour off the substrate-primitive accessor"
8701            );
8702            assert!(
8703                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
8704                "From<&RestartStrategy> for Cow<'static, str> impl must \
8705                 land on the zero-alloc Cow::Borrowed arm on \
8706                 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
8707                 signals the projection has silently allocated where \
8708                 the substrate-primitive RestartStrategy::as_str \
8709                 `&'static str` return makes the borrowed arm the \
8710                 type-correct projection"
8711            );
8712            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
8713            assert_eq!(
8714                via_into.as_ref(),
8715                via_method,
8716                "Into<Cow<'static, str>>::into on \
8717                 &RestartStrategy::{variant:?} must byte-equal \
8718                 RestartStrategy::as_str on the same input — the \
8719                 blanket-derived Into shape must resolve to the same \
8720                 as_str dispatch as the explicit From impl"
8721            );
8722            assert!(
8723                matches!(via_into, std::borrow::Cow::Borrowed(_)),
8724                "Into<Cow<'static, str>>::into on \
8725                 &RestartStrategy::{variant:?} must land on the \
8726                 zero-alloc Cow::Borrowed arm — the blanket-derived \
8727                 Into shape must resolve to the same Cow::Borrowed \
8728                 dispatch as the explicit From impl"
8729            );
8730        }
8731    }
8732
8733    #[test]
8734    fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
8735        // Cross-axis partition pin: the newly lifted trait-idiomatic
8736        // borrowed-input `From<&RestartStrategy> for
8737        // std::borrow::Cow<'static, str>` (this lift), the paired
8738        // owned-input `From<RestartStrategy> for
8739        // std::borrow::Cow<'static, str>` (7dd28b3), the paired
8740        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8741        // for &'static str`, and the paired borrowed-input owned-
8742        // `String` `From<&RestartStrategy> for String` must resolve
8743        // identically on every arm, locking the four
8744        // return-shape × input-shape paths together by construction so
8745        // any future detour trips at caixa-core test time. Also byte-
8746        // parity witness against the sibling [`ToString::to_string`]
8747        // surface routed through [`std::fmt::Display`] — every owned-
8748        // heap-string path (this axis's `.into_owned()` promotion, the
8749        // paired [`From<&RestartStrategy> for String`], and
8750        // `.to_string()`) resolves to the same lifted
8751        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
8752        //
8753        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
8754        // over [`super::RestartStrategy::ALL`] — whose iterator yields
8755        // `&RestartStrategy` by construction, so the borrowed-input
8756        // [`Cow<'static, str>`] axis is what routes the pipe through
8757        // the substrate-primitive [`super::RestartStrategy::as_str`]
8758        // accessor without a spurious [`Copy`] deref (which would only
8759        // be reachable through the owned-input
8760        // [`From<RestartStrategy> for Cow<'static, str>`] axis by
8761        // first calling `.copied()` on the iterator). The pipe witness
8762        // also pins the zero-alloc discipline: every element in the
8763        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
8764        // arm predicate, so a future accidental silent-allocation
8765        // regression on the pipe's iteration axis is a caixa-core-
8766        // test-time failure.
8767        for &strategy in RestartStrategy::ALL {
8768            let borrowed_cow: std::borrow::Cow<'static, str> =
8769                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
8770            let owned_cow: std::borrow::Cow<'static, str> =
8771                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
8772            let borrowed_static: &'static str =
8773                <&'static str as From<&RestartStrategy>>::from(&strategy);
8774            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
8775            assert_eq!(
8776                borrowed_cow, owned_cow,
8777                "From<&RestartStrategy> for Cow<'static, str> and \
8778                 From<RestartStrategy> for Cow<'static, str> must \
8779                 resolve identically on RestartStrategy::{strategy:?} — \
8780                 divergence signals the borrowed-input and owned-input \
8781                 Cow<'static, str> forward-projection input-shape \
8782                 paths have drifted onto different emit-sets"
8783            );
8784            assert_eq!(
8785                borrowed_cow.as_ref(),
8786                borrowed_static,
8787                "From<&RestartStrategy> for Cow<'static, str> and \
8788                 From<&RestartStrategy> for &'static str must resolve \
8789                 identically on RestartStrategy::{strategy:?} — \
8790                 divergence signals the borrowed-input Cow<'static, \
8791                 str> and &'static str return-shape paths have drifted \
8792                 onto different emit-sets"
8793            );
8794            assert_eq!(
8795                borrowed_cow.as_ref(),
8796                borrowed_string.as_str(),
8797                "From<&RestartStrategy> for Cow<'static, str> and \
8798                 From<&RestartStrategy> for String must resolve \
8799                 identically on RestartStrategy::{strategy:?} — \
8800                 divergence signals the borrowed-input Cow<'static, \
8801                 str> and owned-`String` return-shape paths have \
8802                 drifted onto different emit-sets"
8803            );
8804            let via_to_string: String = strategy.to_string();
8805            assert_eq!(
8806                borrowed_cow.as_ref(),
8807                via_to_string.as_str(),
8808                "From<&RestartStrategy> for Cow<'static, str> must \
8809                 byte-equal RestartStrategy::to_string on \
8810                 RestartStrategy::{strategy:?} — divergence signals \
8811                 the trait-idiomatic borrowed-input Cow<'static, str> \
8812                 forward-projection axis and the ToString-through-\
8813                 Display axis have drifted onto different emit-sets"
8814            );
8815        }
8816        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8817            .iter()
8818            .map(std::borrow::Cow::from)
8819            .collect();
8820        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8821            .iter()
8822            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
8823            .collect();
8824        assert_eq!(
8825            via_iter, via_method,
8826            "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
8827             call site whose iteration axis holds `&RestartStrategy` \
8828             by construction — must byte-equal `.iter().map(|s| \
8829             Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
8830             input Cow<'static, str> `From<&RestartStrategy> for \
8831             Cow<'static, str>` axis is what makes the `Cow::from` \
8832             composition route through the substrate-primitive \
8833             `RestartStrategy::as_str` accessor with the zero-alloc \
8834             Cow::Borrowed arm by construction and without a spurious \
8835             `Copy` deref (which would only be reachable through the \
8836             owned-input `From<RestartStrategy> for Cow<'static, str>` \
8837             axis by first calling `.copied()` on the iterator)"
8838        );
8839        for cow in &via_iter {
8840            assert!(
8841                matches!(cow, std::borrow::Cow::Borrowed(_)),
8842                "every element of the .iter().map(Cow::from) pipe \
8843                 over RestartStrategy::ALL must land on the zero-\
8844                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
8845                 any arm signals the pipe's iteration axis has \
8846                 silently allocated where the substrate-primitive \
8847                 RestartStrategy::as_str `&'static str` return makes \
8848                 the borrowed arm the type-correct projection"
8849            );
8850        }
8851    }
8852
8853    #[test]
8854    fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
8855        // Fail-before-pass-after byte-parity pin on the newly lifted
8856        // `impl From<RestartStrategy> for Box<str>` — asserts the
8857        // owned-input standard-library trait impl and the
8858        // substrate-primitive [`super::RestartStrategy::as_str`]
8859        // `pub const fn` accessor resolve to the same four-arm emit-
8860        // set across every arm the exhaustive
8861        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
8862        // substrate-wide `Box<str>` forward-projection campaign tier
8863        // on the first M2 OTP-shape closed-set fieldless typed enum
8864        // peer on the caixa surface (`:supervisor :estrategia`),
8865        // immediately after the paired `Cow<'static, str>` axis
8866        // (7dd28b3 / ee577fd) closed the
8867        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
8868        // 2×3 corner on this enum. Rust's standard library carries
8869        // `impl From<&str> for Box<str>` and
8870        // `impl From<String> for Box<str>` but no blanket
8871        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
8872        // a distinct trait-idiomatic surface that a
8873        // `let key: Box<str> = strategy.into();`-shaped call site
8874        // reaches through this impl and no other — a paired
8875        // `Box::from(strategy.as_str())` open-code has no compile-
8876        // time link back to the substrate primitive.
8877        for &variant in RestartStrategy::ALL {
8878            let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
8879            let via_method: &'static str = variant.as_str();
8880            assert_eq!(
8881                via_trait.as_ref(),
8882                via_method,
8883                "From<RestartStrategy> for Box<str> impl must round-\
8884                 trip RestartStrategy::{variant:?} to the same lifted \
8885                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8886                 returns — divergence signals a silent detour off the \
8887                 substrate-primitive accessor"
8888            );
8889            let via_into: Box<str> = variant.into();
8890            assert_eq!(
8891                via_into.as_ref(),
8892                via_method,
8893                "Into<Box<str>>::into on RestartStrategy::{variant:?} \
8894                 must byte-equal RestartStrategy::as_str on the same \
8895                 input — the blanket-derived Into shape must resolve \
8896                 to the same as_str dispatch as the explicit From impl"
8897            );
8898        }
8899    }
8900
8901    #[test]
8902    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
8903        // Fail-before-pass-after byte-parity pin on the newly lifted
8904        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
8905        // library trait impl and the substrate-primitive
8906        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
8907        // the same three-arm accept-set across every arm the exhaustive
8908        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
8909        // detour that routes the trait impl through a divergent
8910        // projection (a per-arm inline `match s { "Permanent" =>
8911        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
8912        // link to the un-lifted arm-literal, a hypothetical
8913        // `#[serde(rename_all = "…")]` attribute drift that silently
8914        // splits the wire byte-string from every consumer that reaches
8915        // for this typed dispatch, an accidental swap onto the kebab-case
8916        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
8917        // impl parses through and which would collide the two-axis
8918        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
8919        // doc block makes load-bearing) trips at caixa-core test time
8920        // under `assert_eq!` rather than at a downstream
8921        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
8922        // every one of the three arms [`RestartPolicy::ALL`] carries so
8923        // no arm's projection is covered only by the sibling method-
8924        // named `from_wire` path. Peer of the sibling
8925        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
8926        // (5b828ed) — extends the trait-idiomatic reverse-projection
8927        // axis onto the third and final M2-OTP-shape closed-set typed
8928        // enum on the caixa surface (the paired per-child restart-
8929        // decision-policy sibling on the same M2 `:supervisor` slot).
8930        for &variant in RestartPolicy::ALL {
8931            let wire = variant.as_str();
8932            assert_eq!(
8933                <RestartPolicy as TryFrom<&str>>::try_from(wire),
8934                Ok(variant),
8935                "TryFrom<&str> impl on RestartPolicy must round-trip \
8936                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
8937                 Ok(RestartPolicy::{variant:?}) — divergence from \
8938                 RestartPolicy::from_wire signals a silent detour off \
8939                 the substrate-primitive accessor"
8940            );
8941            assert_eq!(
8942                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
8943                RestartPolicy::from_wire(wire),
8944                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
8945                 equal RestartPolicy::from_wire on the same input"
8946            );
8947        }
8948    }
8949
8950    #[test]
8951    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
8952        // Rejection witness on the `impl TryFrom<&str> for
8953        // RestartPolicy` — sweeps a candidate set of byte-strings
8954        // outside the three-arm PascalCase wire accept-set the sibling
8955        // [`RestartPolicy::as_str`] emits and asserts every one lands on
8956        // `Err(())`, so a future accidental widening of the trait impl's
8957        // accept-set (a stray additional
8958        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
8959        // path, a silent inclusion of the kebab-case dispatcher-catalog
8960        // byte-string the pre-existing [`std::str::FromStr`] impl the
8961        // [`gen_platform::FromStrKind`] derive installs parses onto the
8962        // wire axis — which would collide the two-axis
8963        // wire/dispatcher-catalog split the sibling
8964        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
8965        // an English-rebrand or plural-arm silent alias that would widen
8966        // the wire accept-set past the OTP-canonical three) trips at
8967        // caixa-core test time. The candidate set includes the empty
8968        // string, whitespace-only padding, the kebab-case dispatcher-
8969        // catalog byte-strings on the sibling axis (a caller who
8970        // confuses the two axes trips here rather than at a downstream
8971        // consumer's silent reject), a lowercase / uppercase / mixed-case
8972        // fold of each PascalCase arm (a caller who assumes case-fold
8973        // acceptance trips here), leading/trailing whitespace padding,
8974        // the trailing-newline shape, quote-wrapped candidates, and a
8975        // residual set of plausible-but-wrong English rebrand
8976        // candidates. Peer of the sibling
8977        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
8978        // (5b828ed) rejection witness.
8979        let rejected: &[&str] = &[
8980            "",
8981            " ",
8982            "\n",
8983            "\t",
8984            "permanent",
8985            "temporary",
8986            "transient",
8987            "PERMANENT",
8988            "TEMPORARY",
8989            "TRANSIENT",
8990            "Permanents",
8991            "Permanent ",
8992            " Permanent",
8993            " Temporary ",
8994            "Permanent\n",
8995            "Transient\t",
8996            "\"Permanent\"",
8997            "Ephemeral",
8998            "Always",
8999            "Never",
9000            "OnAbnormalExit",
9001            "intrinsic",
9002            "?",
9003        ];
9004        for &input in rejected {
9005            assert_eq!(
9006                <RestartPolicy as TryFrom<&str>>::try_from(input),
9007                Err(()),
9008                "TryFrom<&str> impl on RestartPolicy must reject the \
9009                 non-wire byte-string {input:?} — silent acceptance \
9010                 signals an accept-set widening off the paired \
9011                 RestartPolicy::from_wire resolver"
9012            );
9013        }
9014    }
9015
9016    #[test]
9017    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
9018        // Cross-axis partition pin: the paired `TryFrom<&str>` and
9019        // `from_wire` reverse projections must resolve identically on
9020        // *every* input, not just the ones [`RestartPolicy::ALL`]
9021        // enumerates. Sweeps a mixed candidate set spanning accepted
9022        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
9023        // case dispatcher-catalog byte-strings, empty, whitespace-
9024        // padded, quoted, English-rebrand candidates) inputs and asserts
9025        // the trait's `Result::ok()` projection byte-equals the method-
9026        // named resolver's `Option<Self>` return-shape on each, locking
9027        // the two paths together by construction so any future detour
9028        // (a stray `try_from` special-case that widens or narrows the
9029        // accept-set outside the paired `from_wire` resolver, an
9030        // accidental swap onto the kebab-case [`std::str::FromStr`]
9031        // impl the [`gen_platform::FromStrKind`] derive installs on the
9032        // sibling dispatcher-catalog axis) trips at caixa-core test
9033        // time. Peer of the sibling
9034        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
9035        // pin — extends the round-trip discipline onto the M2-OTP-shape
9036        // per-child restart-policy axis.
9037        let candidates: &[&str] = &[
9038            "Permanent",
9039            "Temporary",
9040            "Transient",
9041            "",
9042            "permanent",
9043            "temporary",
9044            "transient",
9045            "PERMANENT",
9046            "unknown",
9047            "Permanent ",
9048            " Permanent",
9049            "\"Permanent\"",
9050            "Ephemeral",
9051            "OnAbnormalExit",
9052            "?",
9053        ];
9054        for &input in candidates {
9055            let via_trait: Option<RestartPolicy> =
9056                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
9057            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
9058            assert_eq!(
9059                via_trait, via_method,
9060                "TryFrom<&str> and from_wire must resolve identically on \
9061                 input {input:?} — divergence signals the two reverse-\
9062                 projection paths have drifted onto different accept-sets"
9063            );
9064        }
9065    }
9066
9067    #[test]
9068    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
9069        // Fail-before-pass-after byte-parity pin on the newly lifted
9070        // `impl From<RestartPolicy> for &'static str` — asserts the
9071        // standard-library trait impl and the substrate-primitive
9072        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
9073        // the same three-arm emit-set across every arm the exhaustive
9074        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
9075        // detour that routes the trait impl through a divergent
9076        // projection (a per-arm inline `match policy { Permanent =>
9077        // "Permanent", … }` re-inlining that opens a compile-time link
9078        // to the un-lifted arm-literal, an accidental swap onto the
9079        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
9080        // axis that would collide the two-axis wire/catalog split the
9081        // sibling [`RestartPolicy::from_wire`] doc block makes
9082        // load-bearing) trips at caixa-core test time under
9083        // `assert_eq!` rather than at a downstream
9084        // `impl Into<&'static str>`-bound consumer's silent split.
9085        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
9086        // carries so no arm's projection is covered only by the sibling
9087        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
9088        // paths. Materializes the `<&'static str as
9089        // From<RestartPolicy>>::from` output in a `const`-shape binding
9090        // to make the `'static` lifetime promise a build-time invariant
9091        // — a future accidental downgrade of any of the three arms'
9092        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
9093        // non-`&'static str` (a `String::leak()`-produced return, a
9094        // `Box::leak`-cast) trips at caixa-core build time rather than
9095        // at a downstream `'static`-bound consumer. Peer of the sibling
9096        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
9097        // (523157d) — extends the trait-idiomatic forward-projection
9098        // axis onto the second (and second-of-two-in-M2) closed-set
9099        // typed enum on the caixa surface (the paired per-child
9100        // restart-decision-policy sibling on the same M2 `:supervisor`
9101        // slot).
9102        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
9103        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
9104        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
9105        for &variant in RestartPolicy::ALL {
9106            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9107            let via_method: &'static str = variant.as_str();
9108            assert_eq!(
9109                via_trait, via_method,
9110                "From<RestartPolicy> for &'static str impl must round-trip \
9111                 RestartPolicy::{variant:?} to the same lifted \
9112                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
9113                 divergence signals a silent detour off the substrate-primitive \
9114                 accessor"
9115            );
9116            let via_into: &'static str = variant.into();
9117            assert_eq!(
9118                via_into, via_method,
9119                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
9120                 byte-equal RestartPolicy::as_str on the same input — the \
9121                 blanket-derived Into shape must resolve to the same as_str \
9122                 dispatch as the explicit From impl"
9123            );
9124        }
9125        assert_eq!(
9126            [PERMANENT, TEMPORARY, TRANSIENT],
9127            [
9128                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9129                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9130                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9131            ],
9132            "const-context RestartPolicy::as_str must resolve to the three \
9133             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
9134             downgrade of any arm to a non-const or non-static byte-string \
9135             breaks the `&'static str`-lifetime promise the paired \
9136             From<RestartPolicy> for &'static str impl carries by \
9137             construction"
9138        );
9139    }
9140
9141    #[test]
9142    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
9143        // Cross-axis partition pin: the paired trait-idiomatic
9144        // `From<RestartPolicy> for &'static str` forward projection and
9145        // the method-named [`RestartPolicy::as_str`] forward projection
9146        // must resolve identically on *every* arm, not just the ones
9147        // named in the primary byte-parity pin above. Sweeps every
9148        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
9149        // output byte-equals the method-named accessor's return-value on
9150        // each, locking the two forward-projection paths together by
9151        // construction so any future detour (a stray `From` special-case
9152        // that lands on a divergent per-arm literal outside the paired
9153        // `as_str` dispatch, a hypothetical rebrand touching one axis
9154        // without the other) trips at caixa-core test time. Peer of the
9155        // sibling forward-projection partition pin
9156        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
9157        // (523157d) — extends the round-trip discipline onto the
9158        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
9159        // surface, closing the two-way `Self ↔ &'static str` round-trip
9160        // on the trait-idiomatic pair (`From<Self> for &'static str` +
9161        // `TryFrom<&str> for Self`) as well as the pre-existing method-
9162        // named pair (`as_str` + `from_wire`).
9163        for &variant in RestartPolicy::ALL {
9164            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9165            let via_method: &'static str = variant.as_str();
9166            assert_eq!(
9167                via_trait, via_method,
9168                "From<RestartPolicy> for &'static str and \
9169                 RestartPolicy::as_str must resolve identically on \
9170                 RestartPolicy::{variant:?} — divergence signals the \
9171                 two forward-projection paths have drifted onto different \
9172                 emit-sets"
9173            );
9174        }
9175        // Round-trip witness: every arm's forward `From` output re-parses
9176        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
9177        // to the original variant. Closes the two-way `RestartPolicy ↔
9178        // &'static str` round-trip on the trait-idiomatic axis pair,
9179        // mirroring the pre-existing method-named `as_str` + `from_wire`
9180        // round-trip on the substrate-primitive axis pair.
9181        for &variant in RestartPolicy::ALL {
9182            let emitted: &'static str = variant.into();
9183            let re_parsed: Result<RestartPolicy, ()> =
9184                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
9185            assert_eq!(
9186                re_parsed,
9187                Ok(variant),
9188                "trait-idiomatic axis pair must round-trip \
9189                 RestartPolicy::{variant:?} through `.into::<&'static \
9190                 str>()` and back through `TryFrom<&str>` — a break signals \
9191                 the forward-emit and reverse-parse axes have drifted onto \
9192                 different vocabularies"
9193            );
9194        }
9195    }
9196
9197    #[test]
9198    fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
9199        // Fail-before-pass-after byte-parity pin on the newly lifted
9200        // `impl From<&RestartPolicy> for &'static str` — asserts the
9201        // borrowed-input standard-library trait impl and the substrate-
9202        // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
9203        // resolve to the same three-arm emit-set across every arm the
9204        // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
9205        // `From` trait does not auto-derive the borrowed-input sibling
9206        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
9207        // where T: Copy, U: From<T>` blanket in `core`), so the
9208        // borrowed-input axis is a distinct trait-idiomatic surface
9209        // that a `.iter().map(Into::into)` shape over
9210        // [`RestartPolicy::ALL`] (whose iterator yields
9211        // `&RestartPolicy`, not `RestartPolicy`) reaches through this
9212        // impl and no other — the paired owned-input
9213        // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
9214        // / dereference before the trait fires. Materializes the
9215        // `<&'static str as From<&RestartPolicy>>::from` output in a
9216        // `const`-shape binding to make the `'static` lifetime promise
9217        // a build-time invariant.
9218        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
9219        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
9220        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
9221        for variant in RestartPolicy::ALL {
9222            let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
9223            let via_method: &'static str = variant.as_str();
9224            assert_eq!(
9225                via_trait, via_method,
9226                "From<&RestartPolicy> for &'static str impl must round-trip \
9227                 &RestartPolicy::{variant:?} to the same lifted \
9228                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9229                 returns — divergence signals a silent detour off the \
9230                 substrate-primitive accessor"
9231            );
9232            let via_into: &'static str = variant.into();
9233            assert_eq!(
9234                via_into, via_method,
9235                "Into<&'static str>::into on &RestartPolicy::{variant:?} \
9236                 must byte-equal RestartPolicy::as_str on the same input — \
9237                 the blanket-derived Into shape must resolve to the same \
9238                 as_str dispatch as the explicit From impl"
9239            );
9240        }
9241        assert_eq!(
9242            [PERMANENT, TEMPORARY, TRANSIENT],
9243            [
9244                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9245                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9246                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9247            ],
9248            "const-context RestartPolicy::as_str must resolve to the three \
9249             lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
9250             From<&RestartPolicy> for &'static str impl inherits its \
9251             `'static` lifetime promise from the same accessor the \
9252             owned-input sibling routes through"
9253        );
9254    }
9255
9256    #[test]
9257    fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
9258        // Cross-axis partition pin: the paired trait-idiomatic
9259        // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
9260        // campaign-shape) and borrowed-input `From<&RestartPolicy> for
9261        // &'static str` (this lift) forward projections must resolve
9262        // identically on every arm, locking the two input-shape paths
9263        // together so any future detour trips at caixa-core test time.
9264        // Then a witness that a `.iter().map(Into::into)` pipe over
9265        // [`RestartPolicy::ALL`] (whose iterator yields
9266        // `&RestartPolicy`) materializes the three-arm accept-set
9267        // through the borrowed-input axis alone — the exact shape a
9268        // future wasm-operator per-child post-exit restart-decision
9269        // diagnostic line, a future substrate-wide per-arm diagnostic
9270        // column, or a
9271        // `HashMap::<&'static str, RestartPolicy>::from_iter(
9272        //     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
9273        // per-policy lookup reaches through — closing the two-way
9274        // owned/borrowed input-shape symmetry on the forward-projection
9275        // trait-idiomatic axis. Peer of the sibling
9276        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9277        // (64aa742) /
9278        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9279        // (5ab993a) /
9280        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9281        // (807b0b5) /
9282        // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9283        // (e941836) partition pins on the sibling closed-set typed-enum
9284        // discriminator axes — extends the borrowed-input axis
9285        // discipline onto the second-of-two M2 OTP-shape closed-set
9286        // typed enum on the caixa surface (per-child restart-decision
9287        // policy). Also closes the direct two-way `&Self → &'static
9288        // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
9289        // — unlike the peer [`crate::CaixaKind`] axis pair (whose
9290        // forward `From` emits lowercase Portuguese diagnostic bytes
9291        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
9292        // forcing the round-trip through an intermediate wire-vocab
9293        // hop), the [`RestartPolicy::as_str`] emit and
9294        // [`RestartPolicy::from_wire`] parse share the same
9295        // `PascalCase` vocabulary by construction, so the borrowed-
9296        // input forward axis and the reverse axis compose directly.
9297        for &variant in RestartPolicy::ALL {
9298            let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9299            let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
9300            assert_eq!(
9301                owned, borrowed,
9302                "From<RestartPolicy> and From<&RestartPolicy> for \
9303                 &'static str must resolve identically on \
9304                 RestartPolicy::{variant:?} — divergence signals the \
9305                 owned-input and borrowed-input forward-projection paths \
9306                 have drifted onto different emit-sets"
9307            );
9308        }
9309        let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
9310        let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
9311        assert_eq!(
9312            via_iter, via_method,
9313            "`.iter().map(Into::into)` over RestartPolicy::ALL must \
9314             byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
9315             borrowed-input `From<&RestartPolicy> for &'static str` axis \
9316             is what makes the `.iter().map(Into::into)` shape route \
9317             through the substrate-primitive `RestartPolicy::as_str` \
9318             accessor rather than through a per-call-site `.copied()` / \
9319             dereference detour"
9320        );
9321        for variant in RestartPolicy::ALL {
9322            let emitted: &'static str = variant.into();
9323            let re_parsed: Result<RestartPolicy, ()> =
9324                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
9325            assert_eq!(
9326                re_parsed,
9327                Ok(*variant),
9328                "trait-idiomatic borrowed-input forward-projection + \
9329                 reverse-projection axis pair must round-trip \
9330                 &RestartPolicy::{variant:?} through `.into::<&'static \
9331                 str>()` (via the borrowed-input axis) and back through \
9332                 `TryFrom<&str>` — a break signals the borrowed-input \
9333                 forward-emit and reverse-parse axes have drifted onto \
9334                 different vocabularies"
9335            );
9336        }
9337    }
9338
9339    #[test]
9340    fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
9341        // Fail-before-pass-after byte-parity pin on the newly lifted
9342        // `impl From<RestartPolicy> for String` — asserts the
9343        // owned-`String`-returning standard-library trait impl and the
9344        // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
9345        // accessor resolve to the same three-arm emit-set across every
9346        // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
9347        // Rust's standard library does not carry a blanket
9348        // `impl<T: AsRef<str>> From<T> for String` (nor an
9349        // `impl<T: fmt::Display> From<T> for String`), so the
9350        // owned-`String` forward-projection axis is a distinct
9351        // trait-idiomatic surface that a `let key: String =
9352        // policy.into();`-shaped call site reaches through this impl
9353        // and no other — the paired sibling `From<RestartPolicy> for
9354        // &'static str` impl forces every owned-`String` call site
9355        // through an explicit `.to_owned()` / `String::from`
9356        // restatement. Peer of the first-mover
9357        // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
9358        // (7baa18a) — extends the trait-idiomatic owned-`String`
9359        // forward-projection axis onto the second-of-two M2 OTP-shape
9360        // closed-set typed enums on the caixa surface (per-child
9361        // restart-decision-policy sibling on the same M2 `:supervisor`
9362        // slot).
9363        for &variant in RestartPolicy::ALL {
9364            let via_trait: String = <String as From<RestartPolicy>>::from(variant);
9365            let via_method: &'static str = variant.as_str();
9366            assert_eq!(
9367                via_trait.as_str(),
9368                via_method,
9369                "From<RestartPolicy> for String impl must round-trip \
9370                 RestartPolicy::{variant:?} to the same lifted \
9371                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9372                 returns — divergence signals a silent detour off the \
9373                 substrate-primitive accessor"
9374            );
9375            let via_into: String = variant.into();
9376            assert_eq!(
9377                via_into.as_str(),
9378                via_method,
9379                "Into<String>::into on RestartPolicy::{variant:?} must \
9380                 byte-equal RestartPolicy::as_str on the same input — the \
9381                 blanket-derived Into shape must resolve to the same as_str \
9382                 dispatch as the explicit From impl"
9383            );
9384        }
9385    }
9386
9387    #[test]
9388    fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
9389        // Cross-axis partition pin: the paired trait-idiomatic
9390        // owned-`String` `From<RestartPolicy> for String` (this lift)
9391        // and owned-`&'static str` `From<RestartPolicy> for &'static
9392        // str` (9fb37d0) forward projections must resolve identically
9393        // on every arm, locking the two return-type-shape paths
9394        // together so any future detour trips at caixa-core test time.
9395        // Also byte-parity witness against the sibling
9396        // [`ToString::to_string`] surface routed through
9397        // [`std::fmt::Display`] — the three owned-heap-string paths
9398        // (`.into::<String>()`, `String::from`, `.to_string()`) must
9399        // resolve identically on every arm so a future consumer that
9400        // picks any of the three lands on the same lifted
9401        // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
9402        // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
9403        // that materializes the three-arm accept-set through the
9404        // owned-`String` axis alone — the exact shape a future
9405        // wasm-operator per-child post-exit restart-decision
9406        // diagnostic line composer or a
9407        // `HashMap::<String, RestartPolicy>::from_iter(
9408        //     RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
9409        // owned-key per-policy lookup reaches through — closing the
9410        // owned-`String` forward-projection axis's iterator-pipe
9411        // shape. Then a direct round-trip witness through the paired
9412        // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
9413        // owned-`String`'s [`String::as_str`] borrow that closes the
9414        // two-way `Self → String → Self` round-trip on the trait-
9415        // idiomatic owned-`String` forward + reverse axis pair —
9416        // unlike the peer [`crate::CaixaKind`] axis pair (whose
9417        // forward `From` emits lowercase Portuguese diagnostic bytes
9418        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
9419        // forcing the round-trip through an intermediate wire-vocab
9420        // hop), the [`RestartPolicy::as_str`] emit and
9421        // [`RestartPolicy::from_wire`] parse share the same
9422        // `PascalCase` vocabulary by construction, so the owned-
9423        // `String` forward axis and the reverse axis compose directly.
9424        for &variant in RestartPolicy::ALL {
9425            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
9426            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9427            assert_eq!(
9428                owned_string.as_str(),
9429                owned_static,
9430                "From<RestartPolicy> for String and From<RestartPolicy> \
9431                 for &'static str must resolve identically on \
9432                 RestartPolicy::{variant:?} — divergence signals the \
9433                 owned-`String` and owned-`&'static str` forward-projection \
9434                 return-type-shape paths have drifted onto different \
9435                 emit-sets"
9436            );
9437            let via_to_string: String = variant.to_string();
9438            assert_eq!(
9439                owned_string, via_to_string,
9440                "From<RestartPolicy> for String must byte-equal \
9441                 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
9442                 divergence signals the trait-idiomatic owned-`String` \
9443                 forward-projection axis and the ToString-through-Display \
9444                 axis have drifted onto different emit-sets"
9445            );
9446        }
9447        let via_iter: Vec<String> = RestartPolicy::ALL
9448            .iter()
9449            .copied()
9450            .map(String::from)
9451            .collect();
9452        let via_method: Vec<String> = RestartPolicy::ALL
9453            .iter()
9454            .map(|p| p.as_str().to_owned())
9455            .collect();
9456        assert_eq!(
9457            via_iter, via_method,
9458            "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
9459             must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
9460             every arm — the owned-`String` `From<RestartPolicy> for \
9461             String` axis is what makes the `String::from` composition \
9462             route through the substrate-primitive `RestartPolicy::as_str` \
9463             accessor rather than through a per-call-site `.to_owned()` / \
9464             `String::from(policy.as_str())` detour"
9465        );
9466        for &variant in RestartPolicy::ALL {
9467            let emitted: String = variant.into();
9468            let re_parsed: Result<RestartPolicy, ()> =
9469                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
9470            assert_eq!(
9471                re_parsed,
9472                Ok(variant),
9473                "trait-idiomatic owned-`String` forward-projection + \
9474                 reverse-projection axis pair must round-trip \
9475                 RestartPolicy::{variant:?} through `.into::<String>()` \
9476                 and back through `TryFrom<&str>` on the owned-`String`'s \
9477                 String::as_str borrow — a break signals the owned-`String` \
9478                 forward-emit and reverse-parse axes have drifted onto \
9479                 different vocabularies"
9480            );
9481        }
9482    }
9483
9484    #[test]
9485    fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
9486        // Fail-before-pass-after byte-parity pin on the newly lifted
9487        // `impl From<&RestartPolicy> for String` — asserts the
9488        // borrowed-input owned-`String`-returning standard-library
9489        // trait impl and the substrate-primitive
9490        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
9491        // the same three-arm emit-set across every arm the exhaustive
9492        // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
9493        // library does not carry a blanket `impl<T: AsRef<str>>
9494        // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
9495        // for String`), so the borrowed-input owned-`String` forward-
9496        // projection axis is a distinct trait-idiomatic surface that a
9497        // `let key: String = (&policy).into();`-shaped call site
9498        // reaches through this impl and no other — the paired sibling
9499        // `From<RestartPolicy> for String` impl forces every borrowed-
9500        // input call site through an explicit `Copy` deref
9501        // (`String::from(*policy)`) or an `.as_str().to_owned()` /
9502        // `.to_string()` detour. Peer of the first-mover
9503        // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
9504        // (579385f) — extends the trait-idiomatic borrowed-input
9505        // owned-`String` forward-projection axis onto the second-of-
9506        // two M2 OTP-shape closed-set typed enums on the caixa surface
9507        // (per-child restart-decision-policy sibling on the same M2
9508        // `:supervisor` slot).
9509        for &variant in RestartPolicy::ALL {
9510            let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
9511            let via_method: &'static str = variant.as_str();
9512            assert_eq!(
9513                via_trait.as_str(),
9514                via_method,
9515                "From<&RestartPolicy> for String impl must round-trip \
9516                 &RestartPolicy::{variant:?} to the same lifted \
9517                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9518                 returns — divergence signals a silent detour off the \
9519                 substrate-primitive accessor"
9520            );
9521            let via_into: String = (&variant).into();
9522            assert_eq!(
9523                via_into.as_str(),
9524                via_method,
9525                "Into<String>::into on &RestartPolicy::{variant:?} must \
9526                 byte-equal RestartPolicy::as_str on the same input — \
9527                 the blanket-derived Into shape must resolve to the \
9528                 same as_str dispatch as the explicit From impl"
9529            );
9530        }
9531    }
9532
9533    #[test]
9534    fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
9535        // Cross-axis partition pin: the newly lifted trait-idiomatic
9536        // borrowed-input owned-`String` `From<&RestartPolicy> for
9537        // String` (this lift), the paired owned-input owned-`String`
9538        // `From<RestartPolicy> for String` (7851725), the paired
9539        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
9540        // for &'static str` (842c7f3), and the paired owned-input
9541        // owned-`&'static str` `From<RestartPolicy> for &'static str`
9542        // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
9543        // str, String}` 2×2 trait-idiomatic projection family — must
9544        // resolve identically on every arm, locking the four
9545        // return-shape × input-shape paths together so any future
9546        // detour trips at caixa-core test time. Also byte-parity
9547        // witness against the sibling [`ToString::to_string`] surface
9548        // routed through [`std::fmt::Display`] and a direct round-trip
9549        // witness through the paired trait-idiomatic reverse
9550        // [`TryFrom<&str>`] axis on the owned-`String`'s
9551        // [`String::as_str`] borrow that closes the two-way
9552        // `&Self → String → Self` round-trip on the trait-idiomatic
9553        // borrowed-input owned-`String` forward + reverse axis pair.
9554        // Peer of the first-mover
9555        // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
9556        // (579385f) — closes the whole `{Self, &Self} × {&'static str,
9557        // String}` 2×2 projection corner on both M2 OTP-shape sibling
9558        // peers.
9559        for &variant in RestartPolicy::ALL {
9560            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
9561            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
9562            let borrowed_static: &'static str =
9563                <&'static str as From<&RestartPolicy>>::from(&variant);
9564            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9565            assert_eq!(
9566                borrowed_string, owned_string,
9567                "From<&RestartPolicy> for String and From<RestartPolicy> \
9568                 for String must resolve identically on \
9569                 RestartPolicy::{variant:?} — divergence signals the \
9570                 borrowed-input and owned-input owned-`String` \
9571                 forward-projection input-shape paths have drifted onto \
9572                 different emit-sets"
9573            );
9574            assert_eq!(
9575                borrowed_string.as_str(),
9576                borrowed_static,
9577                "From<&RestartPolicy> for String and From<&RestartPolicy> \
9578                 for &'static str must resolve identically on \
9579                 RestartPolicy::{variant:?} — divergence signals the \
9580                 borrowed-input `&'static str` and owned-`String` \
9581                 return-shape paths have drifted onto different \
9582                 emit-sets"
9583            );
9584            assert_eq!(
9585                borrowed_string.as_str(),
9586                owned_static,
9587                "From<&RestartPolicy> for String and From<RestartPolicy> \
9588                 for &'static str must resolve identically on \
9589                 RestartPolicy::{variant:?} — divergence signals a \
9590                 break in the diagonal corner of the {{Self, &Self}} × \
9591                 {{&'static str, String}} 2×2 trait-idiomatic \
9592                 projection family"
9593            );
9594            let via_to_string: String = variant.to_string();
9595            assert_eq!(
9596                borrowed_string, via_to_string,
9597                "From<&RestartPolicy> for String must byte-equal \
9598                 RestartPolicy::to_string on RestartPolicy::{variant:?} \
9599                 — divergence signals the trait-idiomatic borrowed-input \
9600                 owned-`String` forward-projection axis and the \
9601                 ToString-through-Display axis have drifted onto \
9602                 different emit-sets"
9603            );
9604        }
9605        let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
9606        let via_method: Vec<String> = RestartPolicy::ALL
9607            .iter()
9608            .map(|p| p.as_str().to_owned())
9609            .collect();
9610        assert_eq!(
9611            via_iter, via_method,
9612            "`.iter().map(String::from)` over RestartPolicy::ALL — a \
9613             call site whose iteration axis holds `&RestartPolicy` by \
9614             construction — must byte-equal `.iter().map(|p| \
9615             p.as_str().to_owned())` on every arm — the borrowed-input \
9616             owned-`String` `From<&RestartPolicy> for String` axis is \
9617             what makes the `String::from` composition route through \
9618             the substrate-primitive `RestartPolicy::as_str` accessor \
9619             without a spurious `Copy` deref (which would only be \
9620             reachable through the owned-input `From<RestartPolicy> \
9621             for String` axis by first calling `.copied()` on the \
9622             iterator)"
9623        );
9624        for &variant in RestartPolicy::ALL {
9625            let emitted: String = (&variant).into();
9626            let re_parsed: Result<RestartPolicy, ()> =
9627                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
9628            assert_eq!(
9629                re_parsed,
9630                Ok(variant),
9631                "trait-idiomatic borrowed-input owned-`String` \
9632                 forward-projection + reverse-projection axis pair must \
9633                 round-trip &RestartPolicy::{variant:?} through \
9634                 `.into::<String>()` on the borrowed-input surface and \
9635                 back through `TryFrom<&str>` on the owned-`String`'s \
9636                 String::as_str borrow — a break signals the \
9637                 borrowed-input owned-`String` forward-emit and \
9638                 reverse-parse axes have drifted onto different \
9639                 vocabularies"
9640            );
9641        }
9642    }
9643
9644    #[test]
9645    fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
9646        // Fail-before-pass-after byte-parity pin on the newly lifted
9647        // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
9648        // asserts the standard-library trait impl and the substrate-
9649        // primitive [`super::RestartPolicy::as_str`] `pub const fn`
9650        // accessor resolve to the same three-arm emit-set across every
9651        // arm the exhaustive [`super::RestartPolicy::ALL`] slice
9652        // enumerates. Rust's standard library does not carry a blanket
9653        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
9654        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
9655        // the `Cow<'static, str>` forward-projection axis is a
9656        // distinct trait-idiomatic surface that a
9657        // `let key: Cow<'static, str> = policy.into();`-shaped call
9658        // site reaches through this impl and no other — the paired
9659        // sibling `From<RestartPolicy> for &'static str` and
9660        // `From<RestartPolicy> for String` impls force every
9661        // `Cow<'static, str>`-parameterized call site through a
9662        // `Cow::Borrowed(policy.as_str())` /
9663        // `Cow::Owned(policy.to_string())` composition whose type
9664        // bounds have no compile-time link back to the substrate
9665        // primitive.
9666        //
9667        // Also asserts the projection lands on the zero-alloc
9668        // [`std::borrow::Cow::Borrowed`] arm (not the
9669        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9670        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
9671        // return lifetime by construction makes the borrowed arm the
9672        // type-correct projection with no runtime allocation. Any
9673        // future silent detour that routes the impl through the owned
9674        // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
9675        // that would allocate on every call site where the
9676        // `&'static str` return of [`super::RestartPolicy::as_str`]
9677        // makes the zero-alloc borrowed projection type-correct) trips
9678        // at caixa-core test time under the
9679        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
9680        // than at a downstream `Cow<'static, str>`-bound consumer's
9681        // silent allocation.
9682        //
9683        // Second peer on the substrate-wide trait-idiomatic
9684        // [`std::borrow::Cow<'static, str>`] forward-projection family
9685        // to extend the axis off the top-level [`super::CaixaKind`]
9686        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
9687        // second (and second-of-two-in-M2) M2 OTP-shape closed-set
9688        // fieldless typed enum peer on the caixa surface — closes the
9689        // M2 OTP-shape tier of the campaign on the owned-input axis
9690        // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
9691        // now carry the owned-input Cow<'static, str> forward
9692        // projection).
9693        for &variant in RestartPolicy::ALL {
9694            let via_trait: std::borrow::Cow<'static, str> =
9695                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
9696            let via_method: &'static str = variant.as_str();
9697            assert_eq!(
9698                via_trait.as_ref(),
9699                via_method,
9700                "From<RestartPolicy> for Cow<'static, str> impl must \
9701                 round-trip RestartPolicy::{variant:?} to the same \
9702                 lifted SUPERVISOR_CHILD_RESTART_* const \
9703                 RestartPolicy::as_str returns — divergence signals a \
9704                 silent detour off the substrate-primitive accessor"
9705            );
9706            assert!(
9707                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9708                "From<RestartPolicy> for Cow<'static, str> impl must \
9709                 land on the zero-alloc Cow::Borrowed arm on \
9710                 RestartPolicy::{variant:?} — a Cow::Owned outcome \
9711                 signals the projection has silently allocated where \
9712                 the substrate-primitive RestartPolicy::as_str \
9713                 `&'static str` return makes the borrowed arm the \
9714                 type-correct projection"
9715            );
9716            let via_into: std::borrow::Cow<'static, str> = variant.into();
9717            assert_eq!(
9718                via_into.as_ref(),
9719                via_method,
9720                "Into<Cow<'static, str>>::into on \
9721                 RestartPolicy::{variant:?} must byte-equal \
9722                 RestartPolicy::as_str on the same input — the \
9723                 blanket-derived Into shape must resolve to the same \
9724                 as_str dispatch as the explicit From impl"
9725            );
9726            assert!(
9727                matches!(via_into, std::borrow::Cow::Borrowed(_)),
9728                "Into<Cow<'static, str>>::into on \
9729                 RestartPolicy::{variant:?} must land on the \
9730                 zero-alloc Cow::Borrowed arm — the blanket-derived \
9731                 Into shape must resolve to the same Cow::Borrowed \
9732                 dispatch as the explicit From impl"
9733            );
9734        }
9735    }
9736
9737    #[test]
9738    fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9739        // Cross-axis partition pin: the newly lifted trait-idiomatic
9740        // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
9741        // (this lift), the paired owned-input `From<RestartPolicy>
9742        // for &'static str` (9fb37d0), and the paired owned-input
9743        // `From<RestartPolicy> for String` (7851725) forward
9744        // projections must resolve identically on every arm, locking
9745        // the three return-shape paths together by construction so any
9746        // future detour trips at caixa-core test time. Also byte-parity
9747        // witness against the sibling [`ToString::to_string`] surface
9748        // routed through [`std::fmt::Display`] — every owned-heap-
9749        // string path (the `Cow::Owned` promotion of this axis's
9750        // `.into_owned()`, `From<RestartPolicy> for String`, and
9751        // `.to_string()`) resolves to the same lifted
9752        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
9753        //
9754        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
9755        // witness over [`super::RestartPolicy::ALL`] that
9756        // materializes the three-arm accept-set through the
9757        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
9758        // shape a future `axum::response::IntoResponse` per-policy
9759        // rejection-body composer, a future M4 admission-webhook
9760        // per-policy rejection-reason emitter whose typing rules out
9761        // the sibling [`AsRef<str>`] borrowed return, or a future
9762        // substrate-wide per-policy diagnostic surface that binds
9763        // through a [`Cow<'static, str>`] boundary reaches through.
9764        // The pipe witness also pins the zero-alloc discipline: every
9765        // element in the collected vector satisfies the
9766        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
9767        // accidental silent-allocation regression on the pipe's
9768        // iteration axis is a caixa-core-test-time failure. Peer of
9769        // the first-mover
9770        // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
9771        // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
9772        // — closes the whole owned-input `Cow<'static, str>` +
9773        // paired `{&'static str, String}` cross-axis-parity corner on
9774        // both M2 OTP-shape sibling peers.
9775        for &variant in RestartPolicy::ALL {
9776            let via_cow: std::borrow::Cow<'static, str> =
9777                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
9778            let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9779            let via_string: String = <String as From<RestartPolicy>>::from(variant);
9780            assert_eq!(
9781                via_cow.as_ref(),
9782                via_static,
9783                "From<RestartPolicy> for Cow<'static, str> and \
9784                 From<RestartPolicy> for &'static str must resolve \
9785                 identically on RestartPolicy::{variant:?} — \
9786                 divergence signals the Cow<'static, str> and \
9787                 &'static str return-shape paths have drifted onto \
9788                 different emit-sets"
9789            );
9790            assert_eq!(
9791                via_cow.as_ref(),
9792                via_string.as_str(),
9793                "From<RestartPolicy> for Cow<'static, str> and \
9794                 From<RestartPolicy> for String must resolve \
9795                 identically on RestartPolicy::{variant:?} — \
9796                 divergence signals the Cow<'static, str> and String \
9797                 return-shape paths have drifted onto different \
9798                 emit-sets"
9799            );
9800            let via_to_string: String = variant.to_string();
9801            assert_eq!(
9802                via_cow.as_ref(),
9803                via_to_string.as_str(),
9804                "From<RestartPolicy> for Cow<'static, str> must \
9805                 byte-equal RestartPolicy::to_string on \
9806                 RestartPolicy::{variant:?} — divergence signals the \
9807                 trait-idiomatic Cow<'static, str> forward-projection \
9808                 axis and the ToString-through-Display axis have \
9809                 drifted onto different emit-sets"
9810            );
9811        }
9812        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
9813            .iter()
9814            .copied()
9815            .map(std::borrow::Cow::from)
9816            .collect();
9817        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
9818            .iter()
9819            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
9820            .collect();
9821        assert_eq!(
9822            via_iter, via_method,
9823            "`.iter().copied().map(Cow::from)` over \
9824             RestartPolicy::ALL must byte-equal `.iter().map(|p| \
9825             Cow::Borrowed(p.as_str()))` on every arm — the \
9826             trait-idiomatic `From<RestartPolicy> for Cow<'static, \
9827             str>` axis is what makes the `Cow::from` composition \
9828             route through the substrate-primitive \
9829             `RestartPolicy::as_str` accessor with the zero-alloc \
9830             Cow::Borrowed arm by construction, rather than a \
9831             per-call-site `Cow::Owned(policy.to_string())` \
9832             allocation"
9833        );
9834        for cow in &via_iter {
9835            assert!(
9836                matches!(cow, std::borrow::Cow::Borrowed(_)),
9837                "every element of the \
9838                 .iter().copied().map(Cow::from) pipe over \
9839                 RestartPolicy::ALL must land on the zero-alloc \
9840                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
9841                 signals the pipe's iteration axis has silently \
9842                 allocated where the substrate-primitive \
9843                 RestartPolicy::as_str `&'static str` return makes \
9844                 the borrowed arm the type-correct projection"
9845            );
9846        }
9847    }
9848
9849    #[test]
9850    fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
9851        // Fail-before-pass-after byte-parity pin on the newly lifted
9852        // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
9853        // asserts the borrowed-input standard-library trait impl and
9854        // the substrate-primitive [`super::RestartPolicy::as_str`]
9855        // `pub const fn` accessor resolve to the same three-arm emit-
9856        // set across every arm the exhaustive
9857        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
9858        // standard library does not carry a blanket
9859        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
9860        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
9861        // the borrowed-input `Cow<'static, str>` forward-projection
9862        // axis is a distinct trait-idiomatic surface that a
9863        // `let key: Cow<'static, str> = (&policy).into();`-shaped
9864        // call site or a
9865        // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
9866        // reaches through this impl and no other — the paired owned-
9867        // input `From<RestartPolicy> for Cow<'static, str>` impl
9868        // (0612398) forces every borrowed-input call site through an
9869        // explicit `Copy` deref (`Cow::from(*policy)`) or a
9870        // `Cow::Borrowed(policy.as_str())` open-code whose type
9871        // bounds have no compile-time link back to the substrate
9872        // primitive.
9873        //
9874        // Also asserts the projection lands on the zero-alloc
9875        // [`std::borrow::Cow::Borrowed`] arm (not the
9876        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9877        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
9878        // return lifetime by construction makes the borrowed arm the
9879        // type-correct projection with no runtime allocation on the
9880        // borrowed-input surface just as on the paired owned-input
9881        // surface.
9882        //
9883        // Closes the `{Self, &Self}` input-shape corner on the M2
9884        // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
9885        // the second-of-two-in-M2 closed-set fieldless typed enum peer
9886        // on the caixa surface (`:supervisor :children :restart`),
9887        // exactly as d45c409 closed it on the top-level
9888        // [`super::CaixaKind`] one commit after the owning half
9889        // (99c1735) landed and as 9b3e4b3 closed it on the sibling
9890        // M2 OTP-shape [`super::RestartStrategy`] one commit after
9891        // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
9892        // tier of the substrate-wide Cow<'static, str> forward-
9893        // projection campaign on both input-shape corners
9894        // ({Self, &Self}) of both M2 OTP-shape sibling peers.
9895        for &variant in RestartPolicy::ALL {
9896            let via_trait: std::borrow::Cow<'static, str> =
9897                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
9898            let via_method: &'static str = variant.as_str();
9899            assert_eq!(
9900                via_trait.as_ref(),
9901                via_method,
9902                "From<&RestartPolicy> for Cow<'static, str> impl must \
9903                 round-trip &RestartPolicy::{variant:?} to the same \
9904                 lifted SUPERVISOR_CHILD_RESTART_* const \
9905                 RestartPolicy::as_str returns — divergence signals a \
9906                 silent detour off the substrate-primitive accessor"
9907            );
9908            assert!(
9909                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9910                "From<&RestartPolicy> for Cow<'static, str> impl must \
9911                 land on the zero-alloc Cow::Borrowed arm on \
9912                 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
9913                 signals the projection has silently allocated where \
9914                 the substrate-primitive RestartPolicy::as_str \
9915                 `&'static str` return makes the borrowed arm the \
9916                 type-correct projection"
9917            );
9918            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
9919            assert_eq!(
9920                via_into.as_ref(),
9921                via_method,
9922                "Into<Cow<'static, str>>::into on \
9923                 &RestartPolicy::{variant:?} must byte-equal \
9924                 RestartPolicy::as_str on the same input — the \
9925                 blanket-derived Into shape must resolve to the same \
9926                 as_str dispatch as the explicit From impl"
9927            );
9928            assert!(
9929                matches!(via_into, std::borrow::Cow::Borrowed(_)),
9930                "Into<Cow<'static, str>>::into on \
9931                 &RestartPolicy::{variant:?} must land on the \
9932                 zero-alloc Cow::Borrowed arm — the blanket-derived \
9933                 Into shape must resolve to the same Cow::Borrowed \
9934                 dispatch as the explicit From impl"
9935            );
9936        }
9937    }
9938
9939    #[test]
9940    fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9941        // Cross-axis partition pin: the newly lifted trait-idiomatic
9942        // borrowed-input `From<&RestartPolicy> for
9943        // std::borrow::Cow<'static, str>` (this lift), the paired
9944        // owned-input `From<RestartPolicy> for
9945        // std::borrow::Cow<'static, str>` (0612398), the paired
9946        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
9947        // for &'static str`, and the paired borrowed-input owned-
9948        // `String` `From<&RestartPolicy> for String` must resolve
9949        // identically on every arm, locking the four
9950        // return-shape × input-shape paths together by construction so
9951        // any future detour trips at caixa-core test time. Also byte-
9952        // parity witness against the sibling [`ToString::to_string`]
9953        // surface routed through [`std::fmt::Display`] — every owned-
9954        // heap-string path (this axis's `.into_owned()` promotion, the
9955        // paired [`From<&RestartPolicy> for String`], and
9956        // `.to_string()`) resolves to the same lifted
9957        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
9958        //
9959        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
9960        // over [`super::RestartPolicy::ALL`] — whose iterator yields
9961        // `&RestartPolicy` by construction, so the borrowed-input
9962        // [`Cow<'static, str>`] axis is what routes the pipe through
9963        // the substrate-primitive [`super::RestartPolicy::as_str`]
9964        // accessor without a spurious [`Copy`] deref (which would only
9965        // be reachable through the owned-input
9966        // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
9967        // calling `.copied()` on the iterator). The pipe witness also
9968        // pins the zero-alloc discipline: every element in the
9969        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
9970        // arm predicate, so a future accidental silent-allocation
9971        // regression on the pipe's iteration axis is a caixa-core-
9972        // test-time failure. Peer of the sibling
9973        // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
9974        // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
9975        // the whole borrowed-input `Cow<'static, str>` +
9976        // paired `{&'static str, String}` cross-axis-parity corner on
9977        // both M2 OTP-shape sibling peers.
9978        for &policy in RestartPolicy::ALL {
9979            let borrowed_cow: std::borrow::Cow<'static, str> =
9980                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
9981            let owned_cow: std::borrow::Cow<'static, str> =
9982                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
9983            let borrowed_static: &'static str =
9984                <&'static str as From<&RestartPolicy>>::from(&policy);
9985            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
9986            assert_eq!(
9987                borrowed_cow, owned_cow,
9988                "From<&RestartPolicy> for Cow<'static, str> and \
9989                 From<RestartPolicy> for Cow<'static, str> must \
9990                 resolve identically on RestartPolicy::{policy:?} — \
9991                 divergence signals the borrowed-input and owned-input \
9992                 Cow<'static, str> forward-projection input-shape \
9993                 paths have drifted onto different emit-sets"
9994            );
9995            assert_eq!(
9996                borrowed_cow.as_ref(),
9997                borrowed_static,
9998                "From<&RestartPolicy> for Cow<'static, str> and \
9999                 From<&RestartPolicy> for &'static str must resolve \
10000                 identically on RestartPolicy::{policy:?} — \
10001                 divergence signals the borrowed-input Cow<'static, \
10002                 str> and &'static str return-shape paths have drifted \
10003                 onto different emit-sets"
10004            );
10005            assert_eq!(
10006                borrowed_cow.as_ref(),
10007                borrowed_string.as_str(),
10008                "From<&RestartPolicy> for Cow<'static, str> and \
10009                 From<&RestartPolicy> for String must resolve \
10010                 identically on RestartPolicy::{policy:?} — \
10011                 divergence signals the borrowed-input Cow<'static, \
10012                 str> and owned-`String` return-shape paths have \
10013                 drifted onto different emit-sets"
10014            );
10015            let via_to_string: String = policy.to_string();
10016            assert_eq!(
10017                borrowed_cow.as_ref(),
10018                via_to_string.as_str(),
10019                "From<&RestartPolicy> for Cow<'static, str> must \
10020                 byte-equal RestartPolicy::to_string on \
10021                 RestartPolicy::{policy:?} — divergence signals \
10022                 the trait-idiomatic borrowed-input Cow<'static, str> \
10023                 forward-projection axis and the ToString-through-\
10024                 Display axis have drifted onto different emit-sets"
10025            );
10026        }
10027        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10028            .iter()
10029            .map(std::borrow::Cow::from)
10030            .collect();
10031        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10032            .iter()
10033            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
10034            .collect();
10035        assert_eq!(
10036            via_iter, via_method,
10037            "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
10038             call site whose iteration axis holds `&RestartPolicy` \
10039             by construction — must byte-equal `.iter().map(|p| \
10040             Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
10041             input Cow<'static, str> `From<&RestartPolicy> for \
10042             Cow<'static, str>` axis is what makes the `Cow::from` \
10043             composition route through the substrate-primitive \
10044             `RestartPolicy::as_str` accessor with the zero-alloc \
10045             Cow::Borrowed arm by construction and without a spurious \
10046             `Copy` deref (which would only be reachable through the \
10047             owned-input `From<RestartPolicy> for Cow<'static, str>` \
10048             axis by first calling `.copied()` on the iterator)"
10049        );
10050        for cow in &via_iter {
10051            assert!(
10052                matches!(cow, std::borrow::Cow::Borrowed(_)),
10053                "every element of the .iter().map(Cow::from) pipe \
10054                 over RestartPolicy::ALL must land on the zero-\
10055                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
10056                 any arm signals the pipe's iteration axis has \
10057                 silently allocated where the substrate-primitive \
10058                 RestartPolicy::as_str `&'static str` return makes \
10059                 the borrowed arm the type-correct projection"
10060            );
10061        }
10062    }
10063
10064    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
10065
10066    #[test]
10067    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
10068        // The fail-before-pass-after pin: pre-lift there was no
10069        // single-source binding between the [`RestartPolicy`] variant
10070        // name the un-`rename`d `Serialize` derive emits under
10071        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
10072        // byte-string every downstream cluster-side dispatcher (the
10073        // future wasm-operator's per-child post-exit restart-decision
10074        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
10075        // materializer's admission-time enum-arm bind, the
10076        // `caixa-operator`'s hierarchical reconciliation scheduler's
10077        // per-child-policy fan-out) probes verbatim. A future
10078        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
10079        // or a per-variant `#[serde(rename = "…")]` override, or a
10080        // variant rename in the source — would silently rebrand the
10081        // emitted scalar under one spelling while every downstream
10082        // dispatcher still probed the other, with the failure surfacing
10083        // at the operator's reconcile posture (children coming up under
10084        // the `default()` `Permanent` arm rather than the typed slot's
10085        // declared policy — a `:temporary` `oneShot` child would be
10086        // restarted on clean exit, treating the successful-completion
10087        // signal as failure and re-running the completion-terminal
10088        // one-shot indefinitely; a `:transient` child that clean-exited
10089        // would be restarted, masking the clean-completion contract)
10090        // far from the source rebrand commit and with no field naming
10091        // the drift. Pinning the two paths (the `Serialize` derive's
10092        // serialized string AND the [`RestartPolicy::as_str`] helper)
10093        // to the same three lifted
10094        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
10095        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
10096        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
10097        // byte-strings makes any future drift on either endpoint fail
10098        // here at caixa-core build time. Peer of the sibling
10099        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
10100        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
10101        // and the M3
10102        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
10103        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
10104        // same three-path-convergence discipline, extended to close the
10105        // third OTP-shaped closed-enum discriminator axis on the caixa
10106        // typed surface (per-child restart-decision policy).
10107        for (variant, expected) in [
10108            (
10109                RestartPolicy::Permanent,
10110                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10111            ),
10112            (
10113                RestartPolicy::Temporary,
10114                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10115            ),
10116            (
10117                RestartPolicy::Transient,
10118                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10119            ),
10120        ] {
10121            let json = serde_json::to_string(&variant).unwrap();
10122            assert_eq!(
10123                json,
10124                format!("\"{expected}\""),
10125                "RestartPolicy::{variant:?} must serialize to {expected:?}"
10126            );
10127            assert_eq!(
10128                variant.as_str(),
10129                expected,
10130                "RestartPolicy::{variant:?}.as_str() must return the lifted \
10131                 SUPERVISOR_CHILD_RESTART_* constant"
10132            );
10133        }
10134    }
10135
10136    #[test]
10137    fn supervisor_child_restart_consts_are_pairwise_distinct() {
10138        // Cross-arm drift-detection pin: a future collapse of two
10139        // canonical variant byte-strings onto the same value (e.g. an
10140        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
10141        // to also read `"Permanent"`) would silently reroute every
10142        // downstream operator's per-child-policy dispatch onto the
10143        // sibling arm's reconcile branch and pass every propagation-probe
10144        // test that expected only the stale arm's value — a `:transient`
10145        // child would come up under the `:permanent` restart-decision
10146        // posture on every subsequent clean exit, so a completion-terminal
10147        // child would be restarted indefinitely against its declared
10148        // policy. Peer of the sibling
10149        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
10150        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
10151        // and the four-way distinct pin
10152        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
10153        // top-level `SUPERVISOR_KEY_*` axis.
10154        let all = [
10155            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10156            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10157            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10158        ];
10159        for (i, a) in all.iter().enumerate() {
10160            for (j, b) in all.iter().enumerate() {
10161                if i != j {
10162                    assert_ne!(
10163                        a, b,
10164                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
10165                         — got duplicate {a:?} at indices {i} and {j}",
10166                    );
10167                }
10168            }
10169        }
10170    }
10171
10172    #[test]
10173    fn restart_policy_display_routes_through_as_str_helper() {
10174        // The fail-before-pass-after pin on the first half of the
10175        // three-path convergence: pre-convergence [`RestartPolicy`]
10176        // carried a [`std::fmt::Display`] surface via its
10177        // `#[discriminant(also_display)]` gen-platform derive route,
10178        // which arrived kebab-case as `"permanent"` / `"temporary"`
10179        // / `"transient"` on this three-arm enum (whose variant
10180        // names each collapse to their own lowercase form under the
10181        // kebab-case transform) while the wire format ran as
10182        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
10183        // through the un-`rename`d serde derive. Every consumer
10184        // reaching for a policy byte-string past the wire format had
10185        // to pick between three paths ([`RestartPolicy::as_str`],
10186        // the `Serialize` derive's serialized string, or
10187        // `format!("{v}")` on the discriminant-Display route), any
10188        // two of which a future variant rename or
10189        // `#[serde(rename_all = "kebab-case")]` attribute would
10190        // silently desynchronize. Wiring [`std::fmt::Display`]
10191        // through [`RestartPolicy::as_str`] closes the third path:
10192        // every `format!("{v}")` call reaches the same lifted
10193        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
10194        // wire format and the [`RestartPolicy::as_str`] helper
10195        // already route through, so a future variant rename lands at
10196        // exactly one place. Pin the routing here so a future
10197        // `impl std::fmt::Display for RestartPolicy`
10198        // reimplementation that hand-rolls the arms instead of
10199        // delegating to [`RestartPolicy::as_str`] fails at
10200        // caixa-core build time. Peer of the sibling
10201        // [`restart_strategy_display_routes_through_as_str_helper`]
10202        // on the per-supervisor sibling-restart-strategy axis and
10203        // the M3
10204        // `placement_strategy_display_routes_through_as_str_helper`
10205        // (cc8f749) — the third of three OTP-shape closed-enum
10206        // discriminator axes on the caixa typed surface now
10207        // converged onto the same three-path
10208        // (Display → as_str → lifted const) discipline.
10209        for variant in [
10210            RestartPolicy::Permanent,
10211            RestartPolicy::Temporary,
10212            RestartPolicy::Transient,
10213        ] {
10214            assert_eq!(
10215                variant.to_string(),
10216                variant.as_str(),
10217                "RestartPolicy::{variant:?} Display must route through \
10218                 RestartPolicy::as_str (single source of truth: the lifted \
10219                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
10220            );
10221        }
10222    }
10223
10224    #[test]
10225    fn restart_policy_display_matches_serialized_wire_byte_string() {
10226        // The fail-before-pass-after pin on the second half of the
10227        // three-path convergence: `Display` (user-facing text) agrees
10228        // byte-for-byte with the `Serialize` derive's wire format
10229        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
10230        // scalar) on every variant. Pre-convergence the two paths
10231        // were structurally independent — a future
10232        // `#[serde(rename_all = "kebab-case")]` attribute on the
10233        // enum would silently rebrand the emitted wire scalar
10234        // (`permanent`, `temporary`, `transient`) while every
10235        // consumer that pretty-prints the policy (the future
10236        // wasm-operator's per-child post-exit restart-decision
10237        // diagnostic line, the future `feira app graph` per-child
10238        // restart column, the future M4
10239        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
10240        // per-child admission-webhook rejection body) would still
10241        // emit the PascalCase form the `as_str` / `Display` route
10242        // returns, with the mismatch surfacing at consumer parse
10243        // time / operator dispatch time far from the source rebrand
10244        // commit. Pin the two paths byte-for-byte here so any future
10245        // serde-attribute or variant-rename drift is a
10246        // caixa-core-build-time test failure at this call, not a
10247        // silent per-consumer dispatch miss. Peer of the sibling
10248        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
10249        // on the per-supervisor sibling-restart-strategy axis and
10250        // the M3
10251        // `placement_strategy_display_matches_serialized_wire_byte_string`
10252        // (cc8f749).
10253        for variant in [
10254            RestartPolicy::Permanent,
10255            RestartPolicy::Temporary,
10256            RestartPolicy::Transient,
10257        ] {
10258            let wire = serde_json::to_string(&variant).unwrap();
10259            let unquoted = wire
10260                .strip_prefix('"')
10261                .and_then(|s| s.strip_suffix('"'))
10262                .expect("serialized RestartPolicy is a JSON string");
10263            assert_eq!(
10264                variant.to_string(),
10265                unquoted,
10266                "RestartPolicy::{variant:?} Display byte-string must match the \
10267                 Serialize derive's wire byte-string (three-path convergence: \
10268                 Display + as_str + Serialize all resolve to the same \
10269                 SUPERVISOR_CHILD_RESTART_* const)"
10270            );
10271        }
10272    }
10273
10274    #[test]
10275    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
10276        // Fail-before-pass-after byte-parity pin on the lifted
10277        // `impl AsRef<str> for RestartPolicy` — asserts the
10278        // standard-library trait impl and the substrate-primitive
10279        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
10280        // to the same `&str` per instance across the three-arm
10281        // closed set, so any future silent detour that routes the
10282        // impl through a divergent projection (a per-arm inline
10283        // `match self { RestartPolicy::Permanent => "Permanent", … }`
10284        // re-inlining that opens a compile-time link to the un-lifted
10285        // arm-literal, a swap onto the kebab-case
10286        // [`gen_platform::Discriminant`] catalog identity that would
10287        // collide the wire axis with the dispatcher-catalog axis) trips
10288        // at caixa-core test time under `PartialEq` rather than at a
10289        // downstream `impl AsRef<str>`-bound consumer's silent split.
10290        // Sweeps every one of the three arms
10291        // [`RestartPolicy::ALL`] carries so no arm's projection is
10292        // covered only by the sibling wire-format `Serialize` derive
10293        // path. Peer of the sibling
10294        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
10295        // (63eb1a4) on the paired per-supervisor sibling-restart-
10296        // strategy axis and the [`crate::CaixaVersion`]
10297        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
10298        // top-level `:versao` typed newtype — the three pins together
10299        // cover the substrate primitive's `AsRef<str>` projection axis
10300        // on the paired newtype + M2 closed-set-typed-enum surface.
10301        for &variant in RestartPolicy::ALL {
10302            assert_eq!(
10303                <RestartPolicy as AsRef<str>>::as_ref(&variant),
10304                variant.as_str(),
10305                "AsRef<str> impl on RestartPolicy::{variant:?} must \
10306                 byte-equal RestartPolicy::as_str on the same instance \
10307                 — divergence signals a silent detour off the substrate-\
10308                 primitive accessor"
10309            );
10310        }
10311    }
10312
10313    #[test]
10314    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
10315        // Fail-before-pass-after byte-parity pin on the three-path
10316        // convergence discipline the M2 per-child-restart-policy
10317        // primitive now carries on the `&str`-projection axis:
10318        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
10319        // lifted impl), `format!("{v}")` (the pre-existing
10320        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
10321        // primitive `pub const fn` accessor both trait impls delegate
10322        // through) must resolve to the same byte-string on every
10323        // instance across the three-arm closed set. Refuses any future
10324        // divergence between the two trait impls (a stray
10325        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
10326        // rather than delegating through the shared accessor; a
10327        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
10328        // literal cascade) that would silently split the two
10329        // projection paths of the same closed-set typed enum. Mirrors
10330        // the sibling three-path-convergence discipline the peer
10331        // [`RestartStrategy`] typed enum carries on its
10332        // `AsRef<str>` / `Display` / `as_str` triple
10333        // (supervisor.rs pin
10334        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
10335        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
10336        // carries on the same triple (version.rs pin
10337        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
10338        // 16d5c7e).
10339        for &variant in RestartPolicy::ALL {
10340            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
10341            let via_display: String = format!("{variant}");
10342            let via_accessor: &str = variant.as_str();
10343            assert_eq!(via_as_ref, via_accessor);
10344            assert_eq!(via_display, via_accessor);
10345            assert_eq!(via_as_ref, via_display.as_str());
10346        }
10347    }
10348
10349    #[test]
10350    fn restart_policy_all_enumerates_every_variant_exactly_once() {
10351        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
10352        // exhaustive-iteration surface: every variant appears exactly
10353        // once, and the slice length matches the arm count of the
10354        // closed set. Every consumer that walks the accepted-policy
10355        // set (a future `feira supervisor --restart …` CLI-side
10356        // arg-parse's "did you mean" hint, a future M4 admission-
10357        // webhook's per-child rejection body naming the accepted-
10358        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
10359        // projection consumers that iterate the accept-set for
10360        // diagnostic rendering) reads through this slice, so a future
10361        // arm addition that grows the enum but forgets to grow
10362        // [`Self::ALL`] silently truncates every downstream consumer's
10363        // accept-set at the same pre-addition boundary — this pin
10364        // fails at caixa-core build time on the pairwise-distinct +
10365        // arm-count invariants.
10366        //
10367        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
10368        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
10369        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
10370        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
10371        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
10372        // pins on the peer closed-set typed-enum axes.
10373        let all: &[RestartPolicy] = RestartPolicy::ALL;
10374        assert_eq!(
10375            all.len(),
10376            3,
10377            "RestartPolicy::ALL must enumerate every variant of the \
10378             three-arm closed set (Permanent, Temporary, Transient); \
10379             got {all:?}"
10380        );
10381        for (i, a) in all.iter().enumerate() {
10382            for (j, b) in all.iter().enumerate() {
10383                if i != j {
10384                    assert_ne!(
10385                        a, b,
10386                        "RestartPolicy::ALL must carry every variant exactly \
10387                         once — got duplicate {a:?} at indices {i} and {j}"
10388                    );
10389                }
10390            }
10391        }
10392        for variant in [
10393            RestartPolicy::Permanent,
10394            RestartPolicy::Temporary,
10395            RestartPolicy::Transient,
10396        ] {
10397            assert!(
10398                all.contains(&variant),
10399                "RestartPolicy::ALL must contain {variant:?} — a future arm \
10400                 addition that grows the enum but forgets to grow the ALL slice \
10401                 silently truncates every downstream consumer's accept-set at \
10402                 the pre-addition boundary"
10403            );
10404        }
10405    }
10406
10407    #[test]
10408    fn restart_policy_from_wire_accepts_every_lifted_constant() {
10409        // Fail-before-pass-after pin on the forward accept-set of the
10410        // [`RestartPolicy::from_wire`] reverse projection: every
10411        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
10412        // constant the [`RestartPolicy::as_str`] emitter walks parses
10413        // back to its paired variant. Any future arm addition that
10414        // grows the emitter's `as_str` match but forgets to grow the
10415        // parser's `from_wire` match silently splits the two halves of
10416        // the round-trip — the wire byte-string one non-serde consumer
10417        // parses from the one the emitter wrote — with the failure
10418        // surfacing at the operator's reconcile posture (a `:temporary`
10419        // `oneShot` child restarted on clean exit, a `:transient` child
10420        // restarted after clean completion) far from the rebrand
10421        // commit. Pinning the three-arm accept-set here catches the
10422        // drift at caixa-core build time.
10423        //
10424        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
10425        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
10426        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
10427        // accept-set pins on the peer closed-set typed-enum `str → Self`
10428        // axes.
10429        for (wire, expected) in [
10430            (
10431                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10432                RestartPolicy::Permanent,
10433            ),
10434            (
10435                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10436                RestartPolicy::Temporary,
10437            ),
10438            (
10439                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10440                RestartPolicy::Transient,
10441            ),
10442        ] {
10443            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
10444                panic!(
10445                    "RestartPolicy::from_wire({wire:?}) must accept every \
10446                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
10447                     lifted canonical byte-string that RestartPolicy::{expected:?} \
10448                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
10449                )
10450            });
10451            assert_eq!(
10452                parsed, expected,
10453                "RestartPolicy::from_wire({wire:?}) must return \
10454                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
10455            );
10456        }
10457    }
10458
10459    #[test]
10460    fn restart_policy_from_wire_round_trips_through_as_str() {
10461        // Fail-before-pass-after pin on the closed round-trip between
10462        // the forward [`RestartPolicy::as_str`] emitter and the
10463        // reverse [`RestartPolicy::from_wire`] parser: for every
10464        // variant in [`RestartPolicy::ALL`], parsing the emitter's
10465        // output must return exactly the same variant. Any per-arm
10466        // divergence — a future arm added to `as_str` but not
10467        // `from_wire`, an accidental copy-paste flip in one but not
10468        // the other — silently splits the emit and parse halves and
10469        // the failure surfaces at consumer parse time far from the
10470        // drift site. The `ALL`-iterating shape means a future arm
10471        // addition picks up the coverage by construction.
10472        //
10473        // Peer of the sibling
10474        // [`restart_strategy_from_wire_round_trips_through_as_str`]
10475        // (4eec29c) round-trip pin on
10476        // [`RestartStrategy::from_wire`] and the M3
10477        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
10478        // (18c7342) round-trip pin on
10479        // [`crate::aplicacao::PlacementStrategy::from_wire`].
10480        for &variant in RestartPolicy::ALL {
10481            let wire = variant.as_str();
10482            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
10483                panic!(
10484                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
10485                     must be Some({variant:?}) — the two halves of the round-trip \
10486                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
10487                     got None on wire byte-string {wire:?}"
10488                )
10489            });
10490            assert_eq!(
10491                parsed, variant,
10492                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
10493                 must round-trip to the same variant; got {parsed:?}"
10494            );
10495        }
10496    }
10497
10498    #[test]
10499    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
10500        // Fail-before-pass-after pin on the closed-set refusal
10501        // discipline of [`RestartPolicy::from_wire`]: every
10502        // byte-string outside the three-arm accept-set returns `None`
10503        // rather than silently collapsing onto the [`Default`]
10504        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
10505        // exercised here sweeps the load-bearing drift shapes: the
10506        // empty string (a stripped serde-attribute drift), all-
10507        // whitespace strings (the canonical text-editor accidental
10508        // padding shape), the kebab-case dispatcher-catalog identities
10509        // (`"permanent"` / `"temporary"` / `"transient"` — the
10510        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
10511        // accept-set, which parses the *other* axis of this enum's
10512        // two-axis split and must not leak into the `from_wire`
10513        // PascalCase-wire accept-set — a lowercase leak here would
10514        // silently accept the operator's kebab-case
10515        // dispatcher-catalog probe under the wire-axis parser and mis-
10516        // route a `:permanent` intent), the padded canonical scalar
10517        // (`" Permanent "`), the trailing-newline shapes
10518        // (`"Permanent\n"`), the uppercase-single-word forms
10519        // (`"PERMANENT"`), and neighboring-but-unknown arms
10520        // (`"Restart"` — the canonical typo direction toward the
10521        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
10522        //
10523        // Peer of the sibling
10524        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
10525        // (4eec29c) +
10526        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
10527        // (2aa6d23) +
10528        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
10529        // (18c7342) refusal pins on the peer closed-set typed-enum
10530        // axes.
10531        for bad in [
10532            "",
10533            " ",
10534            "\n",
10535            "\t",
10536            "permanent",
10537            "temporary",
10538            "transient",
10539            "PERMANENT",
10540            "TEMPORARY",
10541            "TRANSIENT",
10542            "Permanents",
10543            "Permanent ",
10544            " Permanent",
10545            " Transient ",
10546            "Permanent\n",
10547            "perma",
10548            "Trans",
10549            "OneForOne",
10550            "Restart",
10551            "?",
10552        ] {
10553            assert!(
10554                RestartPolicy::from_wire(bad).is_none(),
10555                "RestartPolicy::from_wire({bad:?}) must return None — the \
10556                 parser's accept-set is exactly the three RestartPolicy::as_str \
10557                 outputs (Permanent, Temporary, Transient), and this \
10558                 byte-string is outside that closed set"
10559            );
10560        }
10561    }
10562
10563    #[test]
10564    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
10565        // Fail-before-pass-after pin on the fourth path of the four-path
10566        // convergence: `from_wire` (the reverse projection) inverts the
10567        // `Serialize` derive's wire byte-string on every variant.
10568        // Together with the pre-existing three-path convergence
10569        // (`Display` + `as_str` + `Serialize` all resolve to the same
10570        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
10571        // pinned by
10572        // [`restart_policy_display_matches_serialized_wire_byte_string`])
10573        // this closes the round-trip: the wire byte-string the
10574        // `Serialize` derive emits parses back to the same variant
10575        // through `from_wire`, so any future serde-attribute or variant-
10576        // rename drift on the emit half now surfaces as a matched drift
10577        // on the parse half at caixa-core build time — the two halves
10578        // migrate as a unit through the lifted consts on any future
10579        // rename, and the round-trip cannot silently split.
10580        //
10581        // Peer of the sibling
10582        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
10583        // (4eec29c) wire-format pin on
10584        // [`RestartStrategy::from_wire`] and the M3
10585        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
10586        // (18c7342) wire-format pin on
10587        // [`crate::aplicacao::PlacementStrategy::from_wire`].
10588        for &variant in RestartPolicy::ALL {
10589            let wire = serde_json::to_string(&variant).unwrap();
10590            let unquoted = wire
10591                .strip_prefix('"')
10592                .and_then(|s| s.strip_suffix('"'))
10593                .expect("serialized RestartPolicy is a JSON string");
10594            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
10595                panic!(
10596                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
10597                     Serialize derive's wire byte-string for \
10598                     RestartPolicy::{variant:?} — the four-path convergence \
10599                     (Display + as_str + Serialize + from_wire) resolves through \
10600                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
10601                )
10602            });
10603            assert_eq!(
10604                parsed, variant,
10605                "RestartPolicy::from_wire of the Serialize derive's wire \
10606                 byte-string for RestartPolicy::{variant:?} must round-trip \
10607                 to the same variant; got {parsed:?}"
10608            );
10609        }
10610    }
10611
10612    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
10613    //
10614    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
10615    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
10616    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
10617    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
10618    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
10619    // the peer per-`:upgrade-from :from` axis. The three pins jointly
10620    // brace the accessor against every future silent detour that would
10621    // desynchronize it from the raw `.caixa` field access every consumer
10622    // previously open-coded.
10623
10624    #[test]
10625    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
10626        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
10627        // [`ChildSpec::nome`] must return the `:children :caixa` field
10628        // byte-for-byte across every DNS-1123-label value the upstream
10629        // [`crate::render::require_valid_dns_1123_label`] gate at
10630        // `SupervisorSpec::validate` admits. Peer of the sibling
10631        // `membro_nome_returns_caixa_byte_equal_across_permutations`
10632        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
10633        // substrate-primitive accessor must byte-equal the raw field
10634        // access verbatim across every author-declared value" discipline
10635        // extended to the M2 supervisor-tree per-`:children` arm. Pins
10636        // against a future silent detour that re-normalized the child
10637        // identity (an accidental `.to_lowercase()` — every `:children
10638        // :caixa` is validated as a DNS-1123 label upstream, so any
10639        // re-normalization is redundant + a drift surface between the
10640        // validator and the accessor), a namespace-prefix rewrite (an
10641        // accidental `format!("{namespace}/{caixa}")` per-CR
10642        // fully-qualified rewrite that didn't land on the peer axes), or
10643        // a per-cluster alias stamp the future wasm-operator's
10644        // hierarchical reconciliation scheduler authors on one consumer
10645        // without the others. Five values sweep the accept-set the
10646        // DNS-1123 gate upstream admits (short single-word / dashed /
10647        // v-suffixed / mixed-digit child names).
10648        for name in [
10649            "worker",
10650            "cache-server",
10651            "scratch-job",
10652            "orders-v2",
10653            "session-8080",
10654        ] {
10655            let c = ChildSpec {
10656                caixa: name.into(),
10657                versao: "^0.1".into(),
10658                restart: RestartPolicy::Permanent,
10659            };
10660            assert_eq!(
10661                c.nome(),
10662                name,
10663                "ChildSpec::nome must return :children :caixa verbatim \
10664                 (got {:?}, expected {name:?})",
10665                c.nome(),
10666            );
10667            assert_eq!(
10668                c.nome(),
10669                c.caixa.as_str(),
10670                "ChildSpec::nome must byte-equal the .caixa field access",
10671            );
10672        }
10673    }
10674
10675    #[test]
10676    fn child_spec_nome_borrows_from_caixa_storage() {
10677        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
10678        // `&str` slice that borrows from the typed slot's own [`String`]
10679        // storage — same-address invariant with `c.caixa.as_str()`. Pins
10680        // against a future silent detour that allocated a fresh `String`
10681        // (`self.caixa.clone()` in the body would type-check but silently
10682        // drop the borrow, and every downstream consumer that assumed
10683        // the returned slice outlives `&self` would break on a stale-
10684        // reference use-after-free — the [`crate::render::insert_first_seen`]
10685        // dedup key at [`SupervisorSpec::validate`], the
10686        // [`validate_no_self_supervision`] equality check against the
10687        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
10688        // borrow — each would silently misbehave if this accessor
10689        // produced a detached copy). Peer of the sibling
10690        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
10691        // M3 per-`:membros` axis and the
10692        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
10693        // first M2 slot scalar accessor.
10694        let c = ChildSpec {
10695            caixa: "worker".into(),
10696            versao: "^0.1".into(),
10697            restart: RestartPolicy::Permanent,
10698        };
10699        let name = c.nome();
10700        let caixa_slice = c.caixa.as_str();
10701        assert_eq!(
10702            name.as_ptr(),
10703            caixa_slice.as_ptr(),
10704            "ChildSpec::nome must borrow from the .caixa String's backing \
10705             storage — a fresh allocation here means the accessor no \
10706             longer names the substrate-primitive typed dispatch and \
10707             every downstream consumer would silently carry a detached \
10708             copy",
10709        );
10710        assert_eq!(
10711            name.len(),
10712            caixa_slice.len(),
10713            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
10714             as well as in address",
10715        );
10716    }
10717
10718    #[test]
10719    fn validate_gates_child_nome_through_lifted_accessor() {
10720        // Bilateral coherence pin: every `:children :caixa` that
10721        // [`SupervisorSpec::validate`] accepts is one
10722        // [`crate::render::require_valid_dns_1123_label`] accepts on the
10723        // accessor-projected value, and vice versa on the reject side.
10724        // This closes the "the validator reads through the accessor"
10725        // contract structurally — a future silent detour that made the
10726        // accessor return a different byte-string than the validator
10727        // gates against would surface here as a coverage mismatch, not
10728        // as an apply-time DNS-1123 rejection at
10729        // `metadata.name: Invalid value` far from the caixa.lisp source.
10730        // Peer of the M2 sibling
10731        // `validate_parses_prior_versao_through_lifted_accessor`
10732        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
10733        // `validate_membros` peer discipline.
10734        //
10735        // Accept-set sweep: five DNS-1123-label values the upstream gate
10736        // admits.
10737        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
10738            let s = SupervisorSpec {
10739                children: vec![ChildSpec {
10740                    caixa: ok_name.into(),
10741                    versao: "^0.1".into(),
10742                    restart: RestartPolicy::Permanent,
10743                }],
10744                ..SupervisorSpec::default()
10745            };
10746            s.validate().unwrap_or_else(|e| {
10747                panic!(
10748                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
10749                     (upstream DNS-1123 gate accepts it): got {e:?}",
10750                );
10751            });
10752            let c = ChildSpec {
10753                caixa: ok_name.into(),
10754                versao: "^0.1".into(),
10755                restart: RestartPolicy::Permanent,
10756            };
10757            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
10758                .unwrap_or_else(|()| {
10759                    panic!(
10760                        "require_valid_dns_1123_label must accept the accessor-projected \
10761                     :children :caixa {ok_name:?}",
10762                    );
10763                });
10764        }
10765        // Reject-set sweep: five DNS-1123-label-violating shapes the
10766        // upstream gate refuses (empty / uppercase / underscore / dot /
10767        // leading-hyphen). Every rejection at the validator must
10768        // correspond to a rejection when the accessor's projected value
10769        // is fed back through the shared gate.
10770        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
10771            let s = SupervisorSpec {
10772                children: vec![ChildSpec {
10773                    caixa: bad_name.into(),
10774                    versao: "^0.1".into(),
10775                    restart: RestartPolicy::Permanent,
10776                }],
10777                ..SupervisorSpec::default()
10778            };
10779            let err = s.validate().unwrap_err();
10780            assert!(
10781                matches!(
10782                    err,
10783                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
10784                ),
10785                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
10786                 via the DNS-1123 gate: got {err:?}",
10787            );
10788            let c = ChildSpec {
10789                caixa: bad_name.into(),
10790                versao: "^0.1".into(),
10791                restart: RestartPolicy::Permanent,
10792            };
10793            assert!(
10794                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
10795                    .is_err(),
10796                "require_valid_dns_1123_label must reject the accessor-projected \
10797                 :children :caixa {bad_name:?}",
10798            );
10799        }
10800    }
10801
10802    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
10803    //
10804    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
10805    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
10806    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
10807    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
10808    // trio on the peer per-`:children` `String`-carry axis. The three pins
10809    // jointly brace the accessor against every future silent detour that
10810    // would desynchronize it from the raw `.versao` field access the
10811    // requirement gate + error carrier previously open-coded.
10812    //
10813    // Closes the last unlifted per-`:children` `String`-carry axis: the
10814    // pair (`nome`, `versao_requirement`) now jointly projects the
10815    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
10816    // consumer that fans on per-child identity + version pin reads,
10817    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
10818    // pair discipline verbatim.
10819    #[test]
10820    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
10821        // The canonical per-`:children` child-`:versao`-scalar pin:
10822        // [`ChildSpec::versao_requirement`] must return the `:children
10823        // :versao` field byte-for-byte across every Cargo-shaped semver
10824        // requirement value the upstream
10825        // [`crate::render::require_valid_versao_requirement`] gate admits.
10826        // Peer of the sibling
10827        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
10828        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
10829        // substrate-primitive accessor must byte-equal the raw field
10830        // access verbatim across every author-declared value" discipline
10831        // extended to the M2 supervisor-tree per-`:children` arm. Pins
10832        // against a future silent detour that re-canonicalized the
10833        // requirement (an accidental `.to_string()` via
10834        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
10835        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
10836        // silently drifted the error carrier's quoted requirement away
10837        // from the source `caixa.lisp`, an accidental whitespace trim on
10838        // `"^ 0.1"` that no consumer ever produced from the field-access
10839        // side, an accidental per-cluster lacre-projected concrete-version
10840        // rewrite that didn't land on the peer requirement-gate call).
10841        // Five values sweep the accept-set the shared
10842        // [`crate::render::require_valid_versao_requirement`] gate admits
10843        // (caret / tilde / exact / wildcard / bare-major).
10844        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
10845            let c = ChildSpec {
10846                caixa: "worker".into(),
10847                versao: req.into(),
10848                restart: RestartPolicy::Permanent,
10849            };
10850            assert_eq!(
10851                c.versao_requirement(),
10852                req,
10853                "ChildSpec::versao_requirement must return :children :versao \
10854                 verbatim (got {:?}, expected {req:?})",
10855                c.versao_requirement(),
10856            );
10857            assert_eq!(
10858                c.versao_requirement(),
10859                c.versao.as_str(),
10860                "ChildSpec::versao_requirement must byte-equal the .versao \
10861                 field access",
10862            );
10863        }
10864    }
10865
10866    #[test]
10867    fn child_spec_versao_requirement_borrows_from_versao_storage() {
10868        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
10869        // return a `&str` slice that borrows from the typed slot's own
10870        // [`String`] storage — same-address invariant with
10871        // `c.versao.as_str()`. Pins against a future silent detour that
10872        // allocated a fresh `String` (`self.versao.clone()` in the body
10873        // would type-check but silently drop the borrow, and every
10874        // downstream consumer that assumed the returned slice outlives
10875        // `&self` — the [`crate::render::require_valid_versao_requirement`]
10876        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
10877        // `.to_string()` carrier's byte-length assumption — would silently
10878        // misbehave if this accessor produced a detached copy). Peer of
10879        // the sibling `child_spec_nome_borrows_from_caixa_storage`
10880        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
10881        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
10882        // pin on the peer per-`:membros` `:versao` axis.
10883        let c = ChildSpec {
10884            caixa: "worker".into(),
10885            versao: "^0.1".into(),
10886            restart: RestartPolicy::Permanent,
10887        };
10888        let req = c.versao_requirement();
10889        let versao_slice = c.versao.as_str();
10890        assert_eq!(
10891            req.as_ptr(),
10892            versao_slice.as_ptr(),
10893            "ChildSpec::versao_requirement must borrow from the .versao \
10894             String's backing storage — a fresh allocation here means the \
10895             accessor no longer names the substrate-primitive typed \
10896             dispatch and every downstream consumer would silently carry \
10897             a detached copy",
10898        );
10899        assert_eq!(
10900            req.len(),
10901            versao_slice.len(),
10902            "ChildSpec::versao_requirement and .versao.as_str() must \
10903             byte-equal in length as well as in address",
10904        );
10905    }
10906
10907    #[test]
10908    fn validate_gates_child_versao_through_lifted_accessor() {
10909        // Bilateral coherence pin: every `:children :versao` that
10910        // [`SupervisorSpec::validate`] accepts is one
10911        // [`crate::render::require_valid_versao_requirement`] accepts on
10912        // the accessor-projected value, and vice versa on the reject side.
10913        // This closes the "the validator reads through the accessor"
10914        // contract structurally — a future silent detour that made the
10915        // accessor return a different byte-string than the validator gates
10916        // against would surface here as a coverage mismatch, not as a
10917        // resolver-time semver-parse rejection at lacre-closure time far
10918        // from the caixa.lisp source. Peer of the sibling
10919        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
10920        // the per-`:children :caixa` axis and the M2
10921        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
10922        // on the peer per-`:upgrade-from :from` axis.
10923        //
10924        // Accept-set sweep: five Cargo-shaped semver requirement values
10925        // the upstream gate admits (caret / tilde / exact / wildcard /
10926        // bare-major).
10927        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
10928            let s = SupervisorSpec {
10929                children: vec![ChildSpec {
10930                    caixa: "worker".into(),
10931                    versao: ok_req.into(),
10932                    restart: RestartPolicy::Permanent,
10933                }],
10934                ..SupervisorSpec::default()
10935            };
10936            s.validate().unwrap_or_else(|e| {
10937                panic!(
10938                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
10939                     (upstream versao-requirement gate accepts it): got {e:?}",
10940                );
10941            });
10942            let c = ChildSpec {
10943                caixa: "worker".into(),
10944                versao: ok_req.into(),
10945                restart: RestartPolicy::Permanent,
10946            };
10947            crate::render::require_valid_versao_requirement(
10948                c.versao_requirement(),
10949                || (),
10950                |_reason| (),
10951            )
10952            .unwrap_or_else(|()| {
10953                panic!(
10954                    "require_valid_versao_requirement must accept the accessor-projected \
10955                     :children :versao {ok_req:?}",
10956                );
10957            });
10958        }
10959        // Reject-set sweep: five requirement-violating shapes the upstream
10960        // gate refuses. The empty string closes the empty-first arm of the
10961        // shared [`crate::render::require_valid_versao_requirement`]
10962        // cascade; the four non-empty arms exercise distinct semver-parse
10963        // failure modes the M3 peer per-`:membros` reject-set already pins
10964        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
10965        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
10966        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
10967        // shared parser routing means the same reject-set must fail
10968        // identically at the M2 supervisor-tree per-`:children` accessor
10969        // arm here. Every rejection at the validator must correspond to a
10970        // rejection when the accessor's projected value is fed back
10971        // through the shared gate.
10972        //
10973        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
10974        // `"not-a-semver"` are intentionally *not* in the reject-set: the
10975        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
10976        // and the identifier-tail arm's grammar admits some non-canonical
10977        // shapes — matching what the M3 peer test suite already documents
10978        // as the shared parser's accept-set edges.)
10979        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
10980            let s = SupervisorSpec {
10981                children: vec![ChildSpec {
10982                    caixa: "worker".into(),
10983                    versao: bad_req.into(),
10984                    restart: RestartPolicy::Permanent,
10985                }],
10986                ..SupervisorSpec::default()
10987            };
10988            let err = s.validate().unwrap_err();
10989            assert!(
10990                matches!(
10991                    err,
10992                    SupervisorError::EmptyChildVersion { .. }
10993                        | SupervisorError::ChildVersaoInvalid { .. }
10994                ),
10995                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
10996                 via the versao-requirement gate: got {err:?}",
10997            );
10998            let c = ChildSpec {
10999                caixa: "worker".into(),
11000                versao: bad_req.into(),
11001                restart: RestartPolicy::Permanent,
11002            };
11003            assert!(
11004                crate::render::require_valid_versao_requirement(
11005                    c.versao_requirement(),
11006                    || (),
11007                    |_reason| (),
11008                )
11009                .is_err(),
11010                "require_valid_versao_requirement must reject the accessor-projected \
11011                 :children :versao {bad_req:?}",
11012            );
11013        }
11014    }
11015
11016    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
11017    //
11018    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
11019    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
11020    // already project the `String`-carry `(caixa, versao)` fields; the
11021    // `Copy`-composite-enum `restart` field is the third and final axis).
11022    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
11023    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
11024    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
11025    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
11026    // strategy scalar accessor — same "one typed dispatch on the substrate
11027    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
11028    // extended onto the M2 supervisor-slot per-`:children` restart-decision
11029    // axis. The pin below covers the accessor's byte-equal projection
11030    // against the raw field access across every variant in the closed
11031    // accept-set (`Permanent`, `Transient`, `Temporary`).
11032
11033    #[test]
11034    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
11035        // The canonical per-`:children` restart-decision-policy-scalar
11036        // pin: [`ChildSpec::restart`] must return the `:children :restart`
11037        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
11038        // typed slot's own [`RestartPolicy`] storage across every variant
11039        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
11040        // Pins against a future silent detour that re-derived the policy
11041        // from a peer axis (an accidental fallback to
11042        // `if is_supervisor_child { Permanent } else { Temporary }` that
11043        // collapsed the child's kind axis into the restart discriminator),
11044        // a variant remap the operator authors on one consumer without the
11045        // other, or a stale-derive detour that substituted
11046        // [`RestartPolicy::default`] when the field held any explicit
11047        // variant (which would silently collapse the distinction between
11048        // "author explicitly declared `:restart Permanent`" and "author
11049        // omitted the slot and inherited the default" the future
11050        // per-cluster restart-decision override slot depends on).
11051        //
11052        // Peer of the sibling per-`:supervisor`
11053        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
11054        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
11055        // axis and the M3
11056        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
11057        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
11058        // — same "the substrate-primitive accessor must byte-equal the raw
11059        // field access verbatim across every author-declared value"
11060        // discipline extended onto the M2 supervisor-slot per-`:children`
11061        // restart-decision-policy axis, closing the last unlifted axis on
11062        // the per-`:children` [`ChildSpec`] type.
11063        for restart in [
11064            RestartPolicy::Permanent,
11065            RestartPolicy::Transient,
11066            RestartPolicy::Temporary,
11067        ] {
11068            let c = ChildSpec {
11069                caixa: "worker".into(),
11070                versao: "^0.1".into(),
11071                restart,
11072            };
11073            assert_eq!(
11074                c.restart(),
11075                restart,
11076                "ChildSpec::restart must return :children :restart \
11077                 verbatim (got {:?}, expected {restart:?})",
11078                c.restart(),
11079            );
11080            assert_eq!(
11081                c.restart(),
11082                c.restart,
11083                "ChildSpec::restart accessor and .restart field access \
11084                 must byte-equal — the accessor is the substrate-primitive \
11085                 typed dispatch every downstream per-child restart-\
11086                 decision consumer must route through",
11087            );
11088        }
11089    }
11090
11091    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
11092    //
11093    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
11094    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
11095    // distribution-strategy accessor discipline onto the M2 supervisor-slot
11096    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
11097    // scalar axis. The two pins below cover (1) the accessor's byte-equal
11098    // projection against the raw field access across every variant in the
11099    // closed accept-set, and (2) the two-consumer coherence between the
11100    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
11101    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
11102    // carrier's `estrategia:` field — peer of the sibling M3
11103    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
11104    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
11105    // pair on the per-`:placement` distribution-strategy axis.
11106
11107    #[test]
11108    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
11109        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
11110        // pin: [`SupervisorSpec::estrategia`] must return the
11111        // `:supervisor :estrategia` field verbatim as a
11112        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
11113        // [`RestartStrategy`] storage across every variant in the closed
11114        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
11115        // `SimpleOneForOne`). Pins against a future silent detour that
11116        // re-derived the strategy from a peer axis (an accidental
11117        // fallback to `if children.is_empty() { SimpleOneForOne } else {
11118        // OneForOne }` collapse that read the children-count axis into
11119        // the strategy discriminator), a variant remap the operator
11120        // authors on one consumer without the other, or a stale-derive
11121        // detour that substituted [`RestartStrategy::default`] when the
11122        // field held any explicit variant (which would silently collapse
11123        // the distinction between "author explicitly declared
11124        // `:estrategia OneForOne`" and "author omitted the slot and
11125        // inherited the default" the future per-cluster strategy override
11126        // slot depends on). Peer of the sibling M3
11127        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
11128        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
11129        // axis — same "the substrate-primitive accessor must byte-equal
11130        // the raw field access verbatim across every author-declared
11131        // value" discipline extended onto the M2 supervisor-slot
11132        // per-`:supervisor` sibling-restart-strategy axis.
11133        for &estrategia in RestartStrategy::ALL {
11134            // `SimpleOneForOne` requires `children.is_empty()`; the peer
11135            // three strategies require a non-empty static children list.
11136            // Build each shape coherently so the pin's fixture would
11137            // itself pass [`SupervisorSpec::validate`] once fed through
11138            // the sibling coherence pin below — the byte-equal projection
11139            // asserted here is a strictly weaker property (a `Copy` field
11140            // read) that does not depend on `validate` running, but
11141            // keeping the fixture validate-clean means a future extension
11142            // of the pin to exercise `validate` end-to-end does not have
11143            // to re-author the children shape.
11144            //
11145            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
11146            // shape partition through the [`gen_platform::IsVariant`]
11147            // derive-generated
11148            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
11149            // than the raw `matches!(estrategia, RestartStrategy::
11150            // SimpleOneForOne)` open-coded pattern-match — same closed-
11151            // set-typed-enum arm-discriminator dispatch discipline the
11152            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
11153            // convergence (915a934) extended onto its two paired positive
11154            // / negated `matches!` sites and the peer
11155            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
11156            // predicate convergence (766ec63) extended onto the M3 mesh-
11157            // slot per-`:placement` distribution-strategy discriminator
11158            // axis. See the sibling `round_trip_all_strategies` and the
11159            // peer `manifest::tests::
11160            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
11161            // fixture for the two peer sites the same lift closes on.
11162            let children = if estrategia.is_simple_one_for_one() {
11163                Vec::new()
11164            } else {
11165                vec![ChildSpec {
11166                    caixa: "worker".into(),
11167                    versao: "^0.1".into(),
11168                    restart: RestartPolicy::Permanent,
11169                }]
11170            };
11171            let s = SupervisorSpec {
11172                estrategia,
11173                children,
11174                ..SupervisorSpec::default()
11175            };
11176            assert_eq!(
11177                s.estrategia(),
11178                estrategia,
11179                "SupervisorSpec::estrategia must return :supervisor :estrategia \
11180                 verbatim (got {:?}, expected {estrategia:?})",
11181                s.estrategia(),
11182            );
11183            assert_eq!(
11184                s.estrategia(),
11185                s.estrategia,
11186                "SupervisorSpec::estrategia accessor and .estrategia field \
11187                 access must byte-equal — the accessor is the substrate-\
11188                 primitive typed dispatch every downstream sibling-restart-\
11189                 strategy consumer must route through",
11190            );
11191        }
11192    }
11193
11194    #[test]
11195    fn validate_reads_through_lifted_estrategia_accessor() {
11196        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
11197        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
11198        // dispatch (which reads through [`SupervisorSpec::estrategia`]
11199        // to fan across the strategy-arm shape-gate cascades) and the
11200        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
11201        // error carrier's `estrategia:` field (which reads through
11202        // [`SupervisorSpec::estrategia`] to name the strategy the empty
11203        // `:children` list was declared against) must both key off the
11204        // lifted accessor, so any future rebrand on the typed slot's
11205        // reader shape lands at exactly one place. Pins the two-site
11206        // coherence by exercising the `NoChildren` error surface end-to-
11207        // end across every non-`SimpleOneForOne` variant and asserting
11208        // the surfaced `estrategia:` field byte-equals the accessor's
11209        // return. Peer of the sibling M3
11210        // `validate_placement_reads_through_lifted_estrategia_accessor`
11211        // (921fe1b) three-consumer coherence pin on the per-`:placement`
11212        // distribution-strategy axis.
11213        for estrategia in [
11214            RestartStrategy::OneForOne,
11215            RestartStrategy::OneForAll,
11216            RestartStrategy::RestForOne,
11217        ] {
11218            let s = SupervisorSpec {
11219                estrategia,
11220                children: Vec::new(),
11221                ..SupervisorSpec::default()
11222            };
11223            let err = s.validate().unwrap_err();
11224            match err {
11225                SupervisorError::NoChildren { estrategia: e } => {
11226                    assert_eq!(
11227                        e,
11228                        s.estrategia(),
11229                        "NoChildren.estrategia must byte-equal \
11230                         SupervisorSpec::estrategia() — the empty-`:children` \
11231                         refusal reads through the lifted accessor",
11232                    );
11233                    assert_eq!(
11234                        e, estrategia,
11235                        "NoChildren.estrategia must carry the author-declared \
11236                         :supervisor :estrategia variant verbatim (got {e:?}, \
11237                         expected {estrategia:?})",
11238                    );
11239                }
11240                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
11241            }
11242        }
11243    }
11244
11245    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
11246    //
11247    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
11248    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
11249    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
11250    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
11251    // The two pins below cover (1) the accessor's byte-equal projection
11252    // against the raw field access across every representative value in
11253    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
11254    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
11255    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
11256    // zero-floor / cap composition — the validate gate and the accessor
11257    // must route through the same substrate-primitive typed dispatch, so
11258    // any future silent detour that had the accessor perform a
11259    // bounds-collapsing clamp would fail here at caixa-core build time.
11260    // Peer of the sibling M3
11261    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
11262    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
11263
11264    #[test]
11265    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
11266        // The canonical per-`:supervisor` restart-budget-count scalar pin:
11267        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
11268        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
11269        // typed slot's own `u32` storage, byte-equal to the raw field
11270        // access across every representative value in the accept-set —
11271        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
11272        // accept-set the surrounding [`SupervisorSpec::validate`] gate
11273        // carves out on the sibling `ZeroMaxRestarts` refusal),
11274        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
11275        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
11276        // (a past-the-guard sentinel that pins the accessor doesn't
11277        // perform a silent bounds-collapse into `1` on the zero arm —
11278        // validate rejects zero but the accessor must ship the raw slot
11279        // verbatim so a validate-time gate regression surfaces at the
11280        // emit boundary rather than being silently absorbed), `u32::MAX`
11281        // (a past-the-guard sentinel that pins the accessor doesn't
11282        // perform a silent bounds-collapse through
11283        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
11284        //
11285        // Peer of the sibling M3
11286        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
11287        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
11288        // required-scalar axis — same "the substrate-primitive accessor
11289        // must byte-equal the raw field access verbatim across every
11290        // value in the `u32` accept-set" discipline extended onto the M2
11291        // supervisor-slot per-`:supervisor` restart-budget-count axis.
11292        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
11293            let s = SupervisorSpec {
11294                max_restarts,
11295                ..SupervisorSpec::default()
11296            };
11297            assert_eq!(
11298                s.max_restarts(),
11299                max_restarts,
11300                "SupervisorSpec::max_restarts must return :supervisor \
11301                 :max-restarts verbatim (got {}, expected {max_restarts})",
11302                s.max_restarts(),
11303            );
11304            assert_eq!(
11305                s.max_restarts(),
11306                s.max_restarts,
11307                "SupervisorSpec::max_restarts accessor and .max_restarts \
11308                 field access must byte-equal — the accessor is the \
11309                 substrate-primitive typed dispatch every downstream \
11310                 restart-budget-count consumer must route through",
11311            );
11312        }
11313    }
11314
11315    #[test]
11316    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
11317        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
11318        // zero-floor + upper-cap bracket must key off
11319        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
11320        // field access. Structurally: a `SupervisorSpec { max_restarts:
11321        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
11322        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
11323        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
11324        // (with the offending count carried verbatim from the accessor
11325        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
11326        // lower boundary of the accept-set) plus a `SupervisorSpec {
11327        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
11328        // boundary) must pass validate. The four together jointly pin the
11329        // accessor + validate-gate composition: any future silent detour
11330        // that had the accessor return a fresh `1` on the zero arm (a
11331        // `.max_restarts().max(1)` collapse) would silently absorb the
11332        // `ZeroMaxRestarts` refusal at the accessor boundary and the
11333        // validate gate would accept a struct-literal `SupervisorSpec {
11334        // max_restarts: 0, .. }` — the composition pin catches that at
11335        // caixa-core build time.
11336        //
11337        // Peer of the sibling M3
11338        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
11339        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
11340        // composition axis — same "the validate / shape-gate predicate
11341        // must route through the substrate-primitive typed dispatch"
11342        // discipline extended onto the peer M2 supervisor-slot
11343        // required-`u32` composition axis.
11344        let child = ChildSpec {
11345            caixa: "worker".into(),
11346            versao: "^0.1".into(),
11347            restart: RestartPolicy::Permanent,
11348        };
11349        // Zero-floor arm.
11350        let s = SupervisorSpec {
11351            max_restarts: 0,
11352            children: vec![child.clone()],
11353            ..SupervisorSpec::default()
11354        };
11355        assert_eq!(
11356            s.validate().unwrap_err(),
11357            SupervisorError::ZeroMaxRestarts,
11358            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
11359             — the accessor and the validate gate must route through the \
11360             same substrate-primitive typed dispatch on the zero-floor arm",
11361        );
11362        // Cap arm — the surfaced `max_restarts:` field must byte-equal
11363        // the accessor's return so a future rebrand on the accessor
11364        // lands in the diagnostic without a coordinated rewrite.
11365        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
11366        let s = SupervisorSpec {
11367            max_restarts: over_cap,
11368            children: vec![child.clone()],
11369            ..SupervisorSpec::default()
11370        };
11371        match s.validate().unwrap_err() {
11372            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
11373                assert_eq!(
11374                    max_restarts,
11375                    s.max_restarts(),
11376                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
11377                     SupervisorSpec::max_restarts() — the cap-arm refusal \
11378                     reads through the lifted accessor",
11379                );
11380                assert_eq!(
11381                    max_restarts, over_cap,
11382                    "MaxRestartsExceedsCap.max_restarts must carry the \
11383                     author-declared :supervisor :max-restarts value \
11384                     verbatim (got {max_restarts}, expected {over_cap})",
11385                );
11386            }
11387            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
11388        }
11389        // Lower + upper accept-set boundaries.
11390        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
11391            let s = SupervisorSpec {
11392                max_restarts,
11393                children: vec![child.clone()],
11394                ..SupervisorSpec::default()
11395            };
11396            assert!(
11397                s.validate().is_ok(),
11398                "validate must accept max_restarts == {max_restarts} \
11399                 (an accept-set boundary of \
11400                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
11401            );
11402        }
11403    }
11404
11405    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
11406    //
11407    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
11408    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
11409    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
11410    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
11411    // supervisor-slot per-`:supervisor` restart-intensity-denominator
11412    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
11413    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
11414    // per-`:supervisor` scalar-value axis. The three pins below cover
11415    // (1) the accessor's byte-equal projection against the raw field
11416    // access across every representative value in the `Option<Duration>`
11417    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
11418    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
11419    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
11420    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
11421    // `if let Some(w) = self.restart_window() { … }` bracket-arm
11422    // composition — the validate gate and the accessor must route through
11423    // the same substrate-primitive typed dispatch, so any future silent
11424    // detour that had the accessor perform a bounds-collapsing clamp
11425    // would fail here at caixa-core build time, and (3) the accessor's
11426    // by-copy idempotence pin — the returned `Option<Duration>` must
11427    // outlive `&self` and two successive calls must return byte-equal
11428    // values. Peer of the sibling M2
11429    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
11430    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
11431    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
11432    // (7073d0f) pin on the per-`:politicas :timeout` axis.
11433
11434    #[test]
11435    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
11436        // The canonical per-`:supervisor` restart-intensity-denominator
11437        // scalar pin: [`SupervisorSpec::restart_window`] must return the
11438        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
11439        // `Option<Duration>`, `Copy`-projected from the typed slot's own
11440        // `Option<Duration>` storage, byte-equal to the raw field access
11441        // across every representative value in the accept-set — `None`
11442        // (the "never reset — every restart across the supervisor's
11443        // lifetime counts against the sibling `:max-restarts` budget"
11444        // sentinel the field's own docstring names and the peer
11445        // `validate_accepts_none_restart_window` pin locks in on the
11446        // [`SupervisorSpec::validate`] entry-side),
11447        // `Some(Duration::from_millis(1))` (the structural minimum a
11448        // validated `:restart-window` may carry, the integer-millisecond
11449        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
11450        // everything sub-ms; `Duration::ZERO` is separately rejected by
11451        // [`SupervisorError::RestartWindowZero`]),
11452        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
11453        // surrounding [`SupervisorSpec::validate`] gate carves out on the
11454        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
11455        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
11456        // accessor doesn't perform a silent bounds-collapse into `None` on
11457        // the zero-Duration arm — validate rejects zero but the accessor
11458        // must ship the raw slot verbatim so a validate-time gate
11459        // regression surfaces at the emit boundary rather than being
11460        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
11461        // sentinel that pins the accessor doesn't perform a silent
11462        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
11463        // return path).
11464        //
11465        // Peer of the sibling M2
11466        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
11467        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
11468        // sibling M3
11469        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
11470        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
11471        // substrate-primitive accessor must byte-equal the raw field
11472        // access verbatim across every value in the `Option<Duration>`
11473        // accept-set" discipline extended onto the M2 supervisor-slot
11474        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
11475        // silent detour that re-derived the restart-window from a peer
11476        // axis (an accidental `.max_restarts.into()` collapse that read
11477        // the restart-budget-count as a duration — the two axes serve
11478        // different halves of the `MaxIntensity / Period` restart-
11479        // intensity ratio, and confusing them silently inverts the
11480        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
11481        // "zero means never reset" collapse (the canonical
11482        // `Option<Duration>` → `Duration` collapse footgun the
11483        // [`SupervisorError::RestartWindowZero`] validate arm guards on
11484        // the peer zero-floor axis; a zero period either trips on the
11485        // first failure or never trips depending on operator
11486        // interpretation, neither of which is the author's "never reset"
11487        // intent that `None` expresses structurally), or a per-arm
11488        // variant swap that landed on one consumer without the other.
11489        for restart_window in [
11490            None,
11491            Some(Duration::from_millis(1)),
11492            Some(SUPERVISOR_RESTART_WINDOW_MAX),
11493            Some(Duration::ZERO),
11494            Some(Duration::MAX),
11495        ] {
11496            let s = SupervisorSpec {
11497                restart_window,
11498                ..SupervisorSpec::default()
11499            };
11500            assert_eq!(
11501                s.restart_window(),
11502                restart_window,
11503                "SupervisorSpec::restart_window must return :supervisor \
11504                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
11505                s.restart_window(),
11506            );
11507            assert_eq!(
11508                s.restart_window(),
11509                s.restart_window,
11510                "SupervisorSpec::restart_window accessor and \
11511                 .restart_window field access must byte-equal — the \
11512                 accessor is the substrate-primitive typed dispatch every \
11513                 downstream restart-intensity-denominator consumer must \
11514                 route through",
11515            );
11516        }
11517    }
11518
11519    #[test]
11520    fn validate_restart_window_bracket_arm_routes_through_accessor() {
11521        // Composition pin: [`SupervisorSpec::validate`]'s
11522        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
11523        // zero-floor + integer-millisecond canonical-form + upper-cap
11524        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
11525        // the raw `.restart_window` field access. Structurally: a
11526        // `SupervisorSpec { restart_window: None, .. }` must pass the
11527        // arm gate structurally (the `if let Some(_)` shape returns
11528        // early on the `None` arm — the accessor and the validate gate
11529        // must agree on `None → skip the bracket cascade` so an authored
11530        // `:restart-window ()` structurally routes through the "never
11531        // reset" sentinel path), a `SupervisorSpec { restart_window:
11532        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
11533        // refusal exactly, a `SupervisorSpec { restart_window:
11534        // Some(Duration::from_micros(1500)), .. }` must surface the
11535        // `RestartWindowNotCanonical` refusal exactly (with the offending
11536        // duration carried verbatim from the accessor return), a
11537        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
11538        // + Duration::from_millis(1)), .. }` must surface the
11539        // `RestartWindowExceedsCap` refusal exactly (with the offending
11540        // duration carried verbatim from the accessor return), and a
11541        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
11542        // .. }` (the lower boundary of the accept-set) plus a
11543        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
11544        // .. }` (the upper boundary) must pass validate. The six together
11545        // jointly pin the accessor + validate-gate composition: any future
11546        // silent detour that had the accessor return a fresh `None` on any
11547        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
11548        // collapse) would silently absorb the `RestartWindowZero` refusal
11549        // at the accessor boundary and the validate gate would accept a
11550        // struct-literal `SupervisorSpec { restart_window:
11551        // Some(Duration::ZERO), .. }` — the composition pin catches that
11552        // at caixa-core build time.
11553        //
11554        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
11555        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
11556        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
11557        // accessor-composition pin on the per-`:politicas :timeout` axis —
11558        // same "the validate / shape-gate predicate must route through
11559        // the substrate-primitive typed dispatch" discipline extended
11560        // onto the peer M2 supervisor-slot optional-`Duration` axis.
11561        let child = ChildSpec {
11562            caixa: "worker".into(),
11563            versao: "^0.1".into(),
11564            restart: RestartPolicy::Permanent,
11565        };
11566        // None arm — must not surface any :restart-window-shaped refusal;
11567        // the `if let Some(_)` bracket returns early on `None` structurally.
11568        let s = SupervisorSpec {
11569            restart_window: None,
11570            children: vec![child.clone()],
11571            ..SupervisorSpec::default()
11572        };
11573        assert!(
11574            s.validate().is_ok(),
11575            "validate must accept restart_window: None (the never-reset \
11576             sentinel) — the `if let Some(_)` bracket returns early on \
11577             the None arm and the accessor must agree",
11578        );
11579        // Zero-floor arm.
11580        let s = SupervisorSpec {
11581            restart_window: Some(Duration::ZERO),
11582            children: vec![child.clone()],
11583            ..SupervisorSpec::default()
11584        };
11585        assert_eq!(
11586            s.validate().unwrap_err(),
11587            SupervisorError::RestartWindowZero,
11588            "validate must reject restart_window == Some(Duration::ZERO) \
11589             with RestartWindowZero — the accessor and the validate gate \
11590             must route through the same substrate-primitive typed \
11591             dispatch on the zero-floor arm",
11592        );
11593        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
11594        // byte-equal the accessor's return so a future rebrand on the
11595        // accessor lands in the diagnostic without a coordinated rewrite.
11596        let sub_ms = Duration::from_micros(1500);
11597        let s = SupervisorSpec {
11598            restart_window: Some(sub_ms),
11599            children: vec![child.clone()],
11600            ..SupervisorSpec::default()
11601        };
11602        match s.validate().unwrap_err() {
11603            SupervisorError::RestartWindowNotCanonical { window } => {
11604                assert_eq!(
11605                    Some(window),
11606                    s.restart_window(),
11607                    "RestartWindowNotCanonical.window must byte-equal \
11608                     SupervisorSpec::restart_window().unwrap() — the \
11609                     non-canonical-arm refusal reads through the lifted \
11610                     accessor",
11611                );
11612                assert_eq!(
11613                    window, sub_ms,
11614                    "RestartWindowNotCanonical.window must carry the \
11615                     author-declared :supervisor :restart-window value \
11616                     verbatim (got {window:?}, expected {sub_ms:?})",
11617                );
11618            }
11619            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
11620        }
11621        // Cap arm — the surfaced `window:` field must byte-equal the
11622        // accessor's return.
11623        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
11624        let s = SupervisorSpec {
11625            restart_window: Some(over_cap),
11626            children: vec![child.clone()],
11627            ..SupervisorSpec::default()
11628        };
11629        match s.validate().unwrap_err() {
11630            SupervisorError::RestartWindowExceedsCap { window } => {
11631                assert_eq!(
11632                    Some(window),
11633                    s.restart_window(),
11634                    "RestartWindowExceedsCap.window must byte-equal \
11635                     SupervisorSpec::restart_window().unwrap() — the \
11636                     cap-arm refusal reads through the lifted accessor",
11637                );
11638                assert_eq!(
11639                    window, over_cap,
11640                    "RestartWindowExceedsCap.window must carry the \
11641                     author-declared :supervisor :restart-window value \
11642                     verbatim (got {window:?}, expected {over_cap:?})",
11643                );
11644            }
11645            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
11646        }
11647        // Lower + upper accept-set boundaries.
11648        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
11649            let s = SupervisorSpec {
11650                restart_window: Some(restart_window),
11651                children: vec![child.clone()],
11652                ..SupervisorSpec::default()
11653            };
11654            assert!(
11655                s.validate().is_ok(),
11656                "validate must accept restart_window == Some({restart_window:?}) \
11657                 (an accept-set boundary of \
11658                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
11659            );
11660        }
11661    }
11662
11663    #[test]
11664    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
11665        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
11666        // `Option<Duration>` by copy — `Duration` is `Copy` (so
11667        // `Option<Duration>` is `Copy`) and the accessor must return by
11668        // value, not by reference. Peer of the sibling M2
11669        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
11670        // per-`:limits :wall-clock` axis and the sibling M3
11671        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
11672        // per-`:politicas :timeout` axis, extended onto the peer M2
11673        // supervisor-slot `Option<Duration>` copy-invariant shape — the
11674        // accessor's returned `Option<Duration>` must outlive `&self`
11675        // (multiple calls must return equal values from a dropped-`&self`
11676        // copy, since the returned Option carries no borrow), and calling
11677        // the accessor twice on the same SupervisorSpec must yield the
11678        // same `Option<Duration>` verbatim (idempotent, no side effects
11679        // on `&self`).
11680        //
11681        // Pins against a future silent detour that returned
11682        // `Option<&Duration>` (which would type-check but silently break
11683        // every downstream caller — the future wasm-operator's
11684        // per-supervisor restart-intensity counter consumes `Duration` by
11685        // value and `&Duration` would fold to a detached copy at the call
11686        // site), an accidental `Option::as_ref()` projection
11687        // (`self.restart_window.as_ref()` would also type-check but
11688        // return `Option<&Duration>`), or a one-arm-only accessor that
11689        // reads `Some(*w)` in the Some arm but reads a fresh
11690        // `Default::default()` (which would collapse to `Duration::ZERO`,
11691        // not `None`) in the None arm — a footgun the
11692        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
11693        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
11694        // requires `Period > 0` and `None` structurally expresses "never
11695        // reset" instead.
11696        for restart_window in [
11697            None,
11698            Some(Duration::from_millis(1)),
11699            Some(Duration::from_secs(60)),
11700            Some(SUPERVISOR_RESTART_WINDOW_MAX),
11701        ] {
11702            let s = SupervisorSpec {
11703                restart_window,
11704                ..SupervisorSpec::default()
11705            };
11706            let first = s.restart_window();
11707            let second = s.restart_window();
11708            assert_eq!(
11709                first, second,
11710                "SupervisorSpec::restart_window must be idempotent — two \
11711                 successive calls on the same &self must return the \
11712                 same Option<Duration>",
11713            );
11714            assert_eq!(
11715                first, restart_window,
11716                "SupervisorSpec::restart_window must return :supervisor \
11717                 :restart-window verbatim by copy — got {first:?}, \
11718                 expected {restart_window:?}",
11719            );
11720        }
11721    }
11722
11723    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
11724    //
11725    // The [`SupervisorSpec::children`] accessor lift is the seed of the
11726    // slice-return (`&[T]`) accessor discipline on the substrate — the four
11727    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
11728    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
11729    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
11730    // access at the time of this seed, and inherit this pin family's
11731    // discipline as future compounding runs migrate their consumers. The
11732    // three pins below cover (1) the accessor's byte-equal projection
11733    // against the raw field access across the empty / singleton / cohort
11734    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
11735    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
11736    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
11737    // consumer routing through the accessor on both arms, and (3) the
11738    // per-child validate loop's traversal reading the same slice-view the
11739    // accessor projects. Peer of the sibling M2
11740    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
11741    // two-consumer coherence pin on the per-`:supervisor`
11742    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
11743    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
11744
11745    #[test]
11746    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
11747        // The canonical per-`:supervisor` static-child-list scalar-shape
11748        // pin: [`SupervisorSpec::children`] must return the `:supervisor
11749        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
11750        // slice-view over the same backing buffer the raw
11751        // `self.children.as_slice()` field access borrows from, byte-
11752        // equal across every representative fixture in the accept-set —
11753        // the empty slice (the `SimpleOneForOne`-arm sentinel),
11754        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
11755        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
11756        // with the peer three restart-policy variants in play).
11757        //
11758        // Pins against a future silent detour that returned
11759        // `&Vec<ChildSpec>` (which would type-check but leak the
11760        // storage-side `Vec`'s grow/push/reserve surface no consumer of
11761        // the typed view reaches for), a fresh-allocated
11762        // `Vec<ChildSpec>` copy (which would type-check via a coercion
11763        // but silently break every downstream caller that relied on the
11764        // slice sharing the backing buffer's identity), or an
11765        // out-of-order or length-drifted projection (which would silently
11766        // split the per-child validate loop's traversal input from the
11767        // paired partition-dispatch `.is_empty()` probe's input).
11768        //
11769        // Peer of the sibling
11770        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
11771        // (eafb619) `Copy`-composite-enum byte-equal pin on the
11772        // per-`:supervisor` sibling-restart-strategy axis, extended onto
11773        // the per-`:supervisor` static-child-list `Vec`-carry axis.
11774        let fixtures: Vec<Vec<ChildSpec>> = vec![
11775            Vec::new(),
11776            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
11777            vec![
11778                child("worker", "^0.1", RestartPolicy::Permanent),
11779                child("cache-server", "^0.1", RestartPolicy::Transient),
11780            ],
11781            vec![
11782                child("worker", "^0.1", RestartPolicy::Permanent),
11783                child("cache-server", "^0.1", RestartPolicy::Transient),
11784                child("scratch-job", "^0.1", RestartPolicy::Temporary),
11785            ],
11786        ];
11787        for children in fixtures {
11788            let s = SupervisorSpec {
11789                children: children.clone(),
11790                ..SupervisorSpec::default()
11791            };
11792            assert_eq!(
11793                s.children(),
11794                children.as_slice(),
11795                "SupervisorSpec::children must return :supervisor \
11796                 :children verbatim (got {:?}, expected {:?})",
11797                s.children(),
11798                children.as_slice(),
11799            );
11800            assert_eq!(
11801                s.children(),
11802                s.children.as_slice(),
11803                "SupervisorSpec::children accessor and \
11804                 .children.as_slice() field access must byte-equal — \
11805                 the accessor is the substrate-primitive typed \
11806                 dispatch every downstream static-child-list consumer \
11807                 must route through",
11808            );
11809            assert_eq!(
11810                s.children().len(),
11811                s.children.len(),
11812                "SupervisorSpec::children().len() must byte-equal \
11813                 self.children.len() — a length-drift would silently \
11814                 split the paired partition-dispatch `.is_empty()` \
11815                 probe input from the per-child validate loop's \
11816                 traversal input",
11817            );
11818        }
11819    }
11820
11821    #[test]
11822    fn validate_reads_through_lifted_children_accessor() {
11823        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
11824        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
11825        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
11826        // when the accessor projects a non-empty slice under a
11827        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
11828        // `self.children().is_empty()` refusal probe (which must trip
11829        // [`SupervisorError::NoChildren`] when the accessor projects the
11830        // empty slice under any peer estrategia), and the per-child
11831        // validate loop's `for child in self.children()` traversal
11832        // (which must reach every entry in the same order the accessor
11833        // projects) must all key off the lifted accessor, so any future
11834        // rebrand on the typed slot's reader shape lands at exactly one
11835        // place. Pins the three-site coherence by exercising each
11836        // production consumer end-to-end: (1) the
11837        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
11838        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
11839        // refusal under the empty slice + non-`SimpleOneForOne`
11840        // estrategia across every peer variant, and (3) the per-child
11841        // duplicate-detection surface fires on the second entry of a
11842        // two-child cohort that shares a `:caixa` name (which requires
11843        // the loop to reach both entries — a first-entry-only projection
11844        // would silently pass since the dedup HashSet has room for the
11845        // first insert).
11846        //
11847        // Peer of the sibling M2
11848        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
11849        // two-consumer coherence pin on the per-`:supervisor`
11850        // sibling-restart-strategy axis, extended onto the
11851        // per-`:supervisor` static-child-list `Vec`-carry axis.
11852
11853        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
11854        // `SimpleOneForOne` estrategia must trip
11855        // `SimpleOneForOneWithStaticChildren`.
11856        let s = SupervisorSpec {
11857            estrategia: RestartStrategy::SimpleOneForOne,
11858            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
11859            ..SupervisorSpec::default()
11860        };
11861        assert_eq!(
11862            s.validate().unwrap_err(),
11863            SupervisorError::SimpleOneForOneWithStaticChildren,
11864            "SimpleOneForOne + non-empty children must trip \
11865             SimpleOneForOneWithStaticChildren — the accessor projects \
11866             a non-empty slice, and the SimpleOneForOne-arm refusal \
11867             probe reads through the lifted accessor",
11868        );
11869        assert!(
11870            !s.children().is_empty(),
11871            "the SimpleOneForOne-arm refusal input must be a non-empty \
11872             slice per the accessor's projection",
11873        );
11874
11875        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
11876        // under any peer estrategia must trip `NoChildren`.
11877        for estrategia in [
11878            RestartStrategy::OneForOne,
11879            RestartStrategy::OneForAll,
11880            RestartStrategy::RestForOne,
11881        ] {
11882            let s = SupervisorSpec {
11883                estrategia,
11884                children: Vec::new(),
11885                ..SupervisorSpec::default()
11886            };
11887            match s.validate().unwrap_err() {
11888                SupervisorError::NoChildren { estrategia: e } => {
11889                    assert_eq!(
11890                        e, estrategia,
11891                        "NoChildren.estrategia must carry the author-\
11892                         declared :supervisor :estrategia variant \
11893                         verbatim (got {e:?}, expected {estrategia:?})",
11894                    );
11895                }
11896                other => panic!(
11897                    "expected NoChildren, got {other:?} for \
11898                     estrategia={estrategia:?}"
11899                ),
11900            }
11901            assert!(
11902                s.children().is_empty(),
11903                "the non-SimpleOneForOne-arm refusal input must be the \
11904                 empty slice per the accessor's projection",
11905            );
11906        }
11907
11908        // (3) Per-child validate loop: a two-child cohort that shares a
11909        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
11910        // reach both entries through the accessor.
11911        let s = SupervisorSpec {
11912            estrategia: RestartStrategy::OneForOne,
11913            children: vec![
11914                child("worker", "^0.1", RestartPolicy::Permanent),
11915                child("worker", "^0.2", RestartPolicy::Transient),
11916            ],
11917            ..SupervisorSpec::default()
11918        };
11919        match s.validate().unwrap_err() {
11920            SupervisorError::DuplicateChildCaixa { caixa } => {
11921                assert_eq!(
11922                    caixa, "worker",
11923                    "DuplicateChildCaixa.caixa must carry the shared \
11924                     child `:caixa` name verbatim",
11925                );
11926            }
11927            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
11928        }
11929        assert_eq!(
11930            s.children().len(),
11931            2,
11932            "the per-child validate loop's traversal input must be a \
11933             two-element slice per the accessor's projection",
11934        );
11935    }
11936
11937    // Shared helper for the M2 per-`:children` per-slot-gate ≡
11938    // `validate` equivalence pins: builds an `OneForOne`-estrategia
11939    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
11940    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
11941    // bracket all pass cleanly so the sole failing surface is the
11942    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
11943    // pins the two-altitude equivalence on the paired probe.
11944    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
11945        let s = SupervisorSpec {
11946            estrategia: RestartStrategy::OneForOne,
11947            children,
11948            ..SupervisorSpec::default()
11949        };
11950        let via_gate = s.validate_children().unwrap_err();
11951        let via_validate = s.validate().unwrap_err();
11952        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
11953        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
11954        assert_eq!(
11955            via_gate, via_validate,
11956            "per-slot gate ≡ validate() must discriminate the same \
11957             refusal shape",
11958        );
11959    }
11960
11961    #[test]
11962    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
11963        // Fail-before-pass-after equivalence pin on the M2
11964        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
11965        // convergence — sibling of the M3 mesh-slot
11966        // `validate_membros_*` / `validate_contratos_*` /
11967        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
11968        // peer per-entry axes. Sweeps four of the five refusal shapes
11969        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
11970        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
11971        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
11972        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
11973        // duplicate-`:caixa` fan-out. Companion pin
11974        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
11975        // covers `ChildVersaoInvalid` (whose parser-owned reason string
11976        // needs pattern-matching, not equality) and the clean-pass
11977        // canonical fixture; together the two pins guarantee the
11978        // per-slot gate and `validate` discriminate the same set on
11979        // every per-child-covered input.
11980        assert_validate_children_matches_gate(
11981            vec![child("", "^0.1", RestartPolicy::Permanent)],
11982            &SupervisorError::EmptyChildName,
11983        );
11984        assert_validate_children_matches_gate(
11985            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
11986            &SupervisorError::ChildCaixaInvalid {
11987                caixa: "Worker".into(),
11988                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
11989            },
11990        );
11991        assert_validate_children_matches_gate(
11992            vec![child("worker", "", RestartPolicy::Permanent)],
11993            &SupervisorError::EmptyChildVersion {
11994                caixa: "worker".into(),
11995            },
11996        );
11997        assert_validate_children_matches_gate(
11998            vec![
11999                child("worker", "^0.1", RestartPolicy::Permanent),
12000                child("worker", "^0.2", RestartPolicy::Transient),
12001            ],
12002            &SupervisorError::DuplicateChildCaixa {
12003                caixa: "worker".into(),
12004            },
12005        );
12006    }
12007
12008    #[test]
12009    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
12010        // Second half of the two-altitude equivalence pin — covers the
12011        // one refusal shape whose reason string is parser-owned
12012        // (`ChildVersaoInvalid`, whose reason comes from the shared
12013        // [`crate::version::parse_requirement`] impl and may drift) and
12014        // the clean-pass canonical fixture. Sibling pin
12015        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
12016        // covers the four equality-comparable refusal shapes.
12017        let s_bad_versao = SupervisorSpec {
12018            estrategia: RestartStrategy::OneForOne,
12019            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
12020            ..SupervisorSpec::default()
12021        };
12022        let via_gate = s_bad_versao.validate_children().unwrap_err();
12023        let via_validate = s_bad_versao.validate().unwrap_err();
12024        match (&via_gate, &via_validate) {
12025            (
12026                SupervisorError::ChildVersaoInvalid {
12027                    caixa: cg,
12028                    versao: vg,
12029                    ..
12030                },
12031                SupervisorError::ChildVersaoInvalid {
12032                    caixa: cv,
12033                    versao: vv,
12034                    ..
12035                },
12036            ) => {
12037                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
12038                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
12039                assert_eq!(cv, "worker", "validate() :caixa carrier");
12040                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
12041            }
12042            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
12043        }
12044        assert_eq!(
12045            via_gate, via_validate,
12046            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
12047        );
12048
12049        let s_ok = SupervisorSpec {
12050            estrategia: RestartStrategy::OneForOne,
12051            children: vec![
12052                child("worker-a", "^0.1", RestartPolicy::Permanent),
12053                child("worker-b", "~0.2.3", RestartPolicy::Transient),
12054                child("collector", "*", RestartPolicy::Temporary),
12055            ],
12056            ..SupervisorSpec::default()
12057        };
12058        s_ok.validate_children()
12059            .expect("per-slot gate must accept the clean-pass fixture");
12060        s_ok.validate()
12061            .expect("validate() must accept the clean-pass fixture");
12062    }
12063
12064    #[test]
12065    fn validate_children_is_self_contained_on_children_slot() {
12066        // Self-containment pin: [`SupervisorSpec::validate_children`]
12067        // resolves the per-child cascade against `&self` alone, without
12068        // depending on the peer `:estrategia`/`:max-restarts`/
12069        // `:restart-window` gates having run first — same posture the M3
12070        // peer per-slot gates carry (`validate_membros`,
12071        // `validate_contratos`, `validate_entrada`, `validate_placement`,
12072        // routing through their own oracles rather than borrowing state
12073        // threaded down from `validate`). A future consumer that reaches
12074        // the per-slot gate directly on a spec whose peer slots would
12075        // fail `validate` still surfaces the per-child refusal, not the
12076        // peer refusal.
12077        //
12078        // Construct a spec whose `:max-restarts` is `0` (which would
12079        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
12080        // the partition-dispatch) and whose `:children` carries a
12081        // `DuplicateChildCaixa` shape: the per-slot gate called directly
12082        // must surface `DuplicateChildCaixa`, proving it does not depend
12083        // on the peer `:max-restarts` gate running first.
12084        let s = SupervisorSpec {
12085            estrategia: RestartStrategy::OneForOne,
12086            max_restarts: 0,
12087            restart_window: Some(Duration::from_secs(60)),
12088            children: vec![
12089                child("worker", "^0.1", RestartPolicy::Permanent),
12090                child("worker", "^0.2", RestartPolicy::Transient),
12091            ],
12092        };
12093        assert_eq!(
12094            s.validate_children().unwrap_err(),
12095            SupervisorError::DuplicateChildCaixa {
12096                caixa: "worker".into(),
12097            },
12098            "per-slot gate must resolve per-child refusal directly against \
12099             `&self` — a dependency on the peer `:max-restarts` gate \
12100             running first would surface ZeroMaxRestarts here instead",
12101        );
12102        // The peer gate is still the surface `validate` reaches — pin
12103        // the ordering to establish that `validate_children` truly runs
12104        // last in `validate`'s dispatch, so a direct call bypasses the
12105        // peer gates on any spec whose per-child cascade would fail.
12106        assert_eq!(
12107            s.validate().unwrap_err(),
12108            SupervisorError::ZeroMaxRestarts,
12109            "validate() must surface the peer `:max-restarts` gate before \
12110             reaching the per-child cascade — this pins the dispatch \
12111             ordering the per-slot gate's self-containment complements",
12112        );
12113    }
12114
12115    #[test]
12116    fn child_spec_restart_accessor_is_const_fn() {
12117        // The [`ChildSpec::restart`] per-`:children` restart-decision-
12118        // policy `Copy`-return scalar accessor is declared
12119        // `#[must_use] pub const fn` — matching the sibling M2
12120        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
12121        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
12122        // both converted in this commit), the sibling M2
12123        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
12124        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
12125        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
12126        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
12127        // `Copy`-return `pub const fn` scalar accessors on the sibling
12128        // M3 surface. Pin the `const`-eval posture here so a future
12129        // accidental downgrade to non-`const` (an added runtime helper
12130        // reachable only from a non-`const` context, an
12131        // `Option<RestartPolicy>`-shape migration on the per-child
12132        // restart-decision axis once heterogeneous per-cluster
12133        // restart-policy overlays land that would silently drop the
12134        // `const` qualifier, a manual hand-rolled shadow) trips at
12135        // caixa-core build time rather than surfacing as a downstream
12136        // `const`-context regression far from the declaration.
12137        //
12138        // Same shape as the sibling M3
12139        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
12140        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
12141        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
12142        // accessor axis — the load-bearing witness lives in the
12143        // module-scope `const fn` wrapper `restart_via_const_fn` below:
12144        // a body that calls [`ChildSpec::restart`] under a `const fn`
12145        // signature is well-formed only when the callee is itself
12146        // `const fn`, so any future accidental downgrade of
12147        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
12148        // build time (const-eval E0015 `cannot call non-const method`),
12149        // strictly stronger than a runtime `assert!(CONST)` and
12150        // side-stepping the destructor-in-const restriction that
12151        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
12152        // items on `ChildSpec`'s `String` carriers.
12153        //
12154        // The runtime body sweeps every closed-set [`RestartPolicy`]
12155        // arm and asserts the wrapped and direct dispatches agree.
12156        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
12157            c.restart()
12158        }
12159        for restart in [
12160            RestartPolicy::Permanent,
12161            RestartPolicy::Transient,
12162            RestartPolicy::Temporary,
12163        ] {
12164            let c = ChildSpec {
12165                caixa: "worker".into(),
12166                versao: "^0.1".into(),
12167                restart,
12168            };
12169            assert_eq!(
12170                restart_via_const_fn(&c),
12171                c.restart(),
12172                "const-fn-wrapped and direct dispatch on \
12173                 ChildSpec::restart must agree for {restart:?}",
12174            );
12175            assert_eq!(
12176                c.restart(),
12177                restart,
12178                "ChildSpec::restart must return the storage-side \
12179                 RestartPolicy verbatim for {restart:?} (a violation \
12180                 means the accessor stopped being a raw field-return \
12181                 copy)",
12182            );
12183        }
12184    }
12185
12186    #[test]
12187    fn supervisor_spec_estrategia_accessor_is_const_fn() {
12188        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
12189        // sibling-restart-strategy `Copy`-return scalar accessor is
12190        // declared `#[must_use] pub const fn` — matching the sibling M2
12191        // per-`:children` [`ChildSpec::restart`] (pinned by
12192        // [`child_spec_restart_accessor_is_const_fn`] above, both
12193        // converted in this commit), the sibling M2 per-`:supervisor`
12194        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
12195        // accessor already `pub const fn`, and mirroring the peer M3
12196        // mesh-slot per-`:placement`
12197        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
12198        // `pub const fn` scalar accessor whose method-name discipline
12199        // the [`SupervisorSpec::estrategia`] method was authored to
12200        // match. Pin the `const`-eval posture here so a future
12201        // accidental downgrade to non-`const` (an added runtime helper
12202        // reachable only from a non-`const` context, an
12203        // `Option<RestartStrategy>`-shape migration once the substrate
12204        // grows per-cluster strategy overlays that would silently drop
12205        // the `const` qualifier, a manual hand-rolled shadow) trips at
12206        // caixa-core build time rather than surfacing as a downstream
12207        // `const`-context regression far from the declaration.
12208        //
12209        // Same shape as the sibling
12210        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
12211        // load-bearing witness lives in the module-scope `const fn`
12212        // wrapper `estrategia_via_const_fn` below: a body that calls
12213        // [`SupervisorSpec::estrategia`] under a `const fn` signature
12214        // is well-formed only when the callee is itself `const fn`,
12215        // side-stepping the destructor-in-const restriction that would
12216        // otherwise block a direct
12217        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
12218        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
12219        // carriers.
12220        //
12221        // The runtime body sweeps every closed-set [`RestartStrategy`]
12222        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
12223        // direct dispatches agree.
12224        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
12225            s.estrategia()
12226        }
12227        for &estrategia in RestartStrategy::ALL {
12228            let s = SupervisorSpec {
12229                estrategia,
12230                max_restarts: 5,
12231                restart_window: Some(Duration::from_secs(60)),
12232                children: Vec::new(),
12233            };
12234            assert_eq!(
12235                estrategia_via_const_fn(&s),
12236                s.estrategia(),
12237                "const-fn-wrapped and direct dispatch on \
12238                 SupervisorSpec::estrategia must agree for {estrategia:?}",
12239            );
12240            assert_eq!(
12241                s.estrategia(),
12242                estrategia,
12243                "SupervisorSpec::estrategia must return the storage-side \
12244                 RestartStrategy verbatim for {estrategia:?} (a violation \
12245                 means the accessor stopped being a raw field-return \
12246                 copy)",
12247            );
12248        }
12249    }
12250
12251    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
12252    // macro definition (see the paired doc-block above the macro
12253    // definition) — every generated `<ctor>(caixa: &str) -> Self`
12254    // constructor folds the uniform `Self::<Variant> { caixa:
12255    // caixa.to_string() }` one-field struct-literal onto one substrate
12256    // primitive. The three per-variant equivalence pins below
12257    // (fail-before-pass-after by construction — a byte-mismatched macro
12258    // arm would trip its equivalence pin first) lock each generated
12259    // constructor to its struct-literal peer under `PartialEq`, so
12260    // every wire-up in [`SupervisorSpec::validate_children`] and
12261    // [`validate_no_self_supervision`] on that variant produces a
12262    // byte-equal `SupervisorError` to the pre-lift open-coded
12263    // struct-literal. The cross-axis pin that follows (non-default
12264    // caixa name) routes the sole constructor input axis through
12265    // `.to_string()`, so the fold does not silently collapse onto a
12266    // fixed name.
12267    //
12268    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
12269    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
12270    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
12271    // `missing_entry_ctor_matches_struct_literal_wrap` /
12272    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
12273    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
12274    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
12275    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
12276    // on the six sibling ctor families the recent trajectory closed
12277    // on the peer `LayoutError` / `AplicacaoError` envelopes.
12278
12279    #[test]
12280    fn empty_child_version_ctor_matches_struct_literal_wrap() {
12281        assert_eq!(
12282            SupervisorError::empty_child_version("worker"),
12283            SupervisorError::EmptyChildVersion {
12284                caixa: "worker".to_string(),
12285            },
12286            "generated empty_child_version ctor must produce byte-equal \
12287             SupervisorError to the open-coded struct-literal wrap on the \
12288             same &str fixture",
12289        );
12290    }
12291
12292    #[test]
12293    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
12294        assert_eq!(
12295            SupervisorError::duplicate_child_caixa("worker"),
12296            SupervisorError::DuplicateChildCaixa {
12297                caixa: "worker".to_string(),
12298            },
12299            "generated duplicate_child_caixa ctor must produce byte-equal \
12300             SupervisorError to the open-coded struct-literal wrap on the \
12301             same &str fixture",
12302        );
12303    }
12304
12305    #[test]
12306    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
12307        assert_eq!(
12308            SupervisorError::child_supervises_self("orquestra"),
12309            SupervisorError::ChildSupervisesSelf {
12310                caixa: "orquestra".to_string(),
12311            },
12312            "generated child_supervises_self ctor must produce byte-equal \
12313             SupervisorError to the open-coded struct-literal wrap on the \
12314             same &str fixture",
12315        );
12316    }
12317
12318    // Per-variant equivalence pins for the two lifted
12319    // [`SupervisorError::child_caixa_invalid`] /
12320    // [`SupervisorError::child_versao_invalid`] inherent constructors
12321    // (fail-before-pass-after by construction — a byte-mismatched ctor body
12322    // would trip its equivalence pin first). Each pins the ctor output to
12323    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
12324    // in [`SupervisorSpec::validate_children`] on the two variants
12325    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
12326    // struct-literal on the same scalar fixtures. Peers of the sibling
12327    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
12328    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
12329    // the peer `AplicacaoError` envelope's
12330    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
12331
12332    #[test]
12333    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
12334        let caixa = "Worker";
12335        let reason = "sample reason text";
12336        assert_eq!(
12337            SupervisorError::child_caixa_invalid(caixa, reason),
12338            SupervisorError::ChildCaixaInvalid {
12339                caixa: caixa.to_string(),
12340                reason: reason.to_string(),
12341            },
12342            "lifted child_caixa_invalid ctor must produce byte-equal \
12343             SupervisorError to the open-coded struct-literal wrap on the \
12344             same (&str, reason) fixture",
12345        );
12346    }
12347
12348    #[test]
12349    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
12350        let caixa = "worker";
12351        let versao = "not-a-req";
12352        let reason = "sample reason text";
12353        assert_eq!(
12354            SupervisorError::child_versao_invalid(caixa, versao, reason),
12355            SupervisorError::ChildVersaoInvalid {
12356                caixa: caixa.to_string(),
12357                versao: versao.to_string(),
12358                reason: reason.to_string(),
12359            },
12360            "lifted child_versao_invalid ctor must produce byte-equal \
12361             SupervisorError to the open-coded struct-literal wrap on the \
12362             same (&str, &str, reason) fixture",
12363        );
12364    }
12365
12366    #[test]
12367    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
12368        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
12369        // against a `&str`-literal vs. `format!(…)` reason input to pin
12370        // both constructors accept the `impl Into<String>` bound
12371        // uniformly, so neither wire-up site drifts under a per-arm
12372        // wrapper transformation on the caller-side `reason` axis. Peer
12373        // of the sibling
12374        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
12375        // sweep on the peer `AplicacaoError` envelope.
12376        let via_literal = "literal reason text";
12377        let via_format = format!("{} reason text", "literal");
12378        assert_eq!(
12379            SupervisorError::child_caixa_invalid("Worker", via_literal),
12380            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
12381        );
12382        assert_eq!(
12383            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
12384            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
12385        );
12386    }
12387
12388    #[test]
12389    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
12390        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
12391        // &str`) through a non-default fixture name against every
12392        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
12393        // so any wrapper-side lowercase / trim / truncate / re-order on
12394        // the `caixa.to_string()` sole-field construction surfaces
12395        // here rather than at a downstream diagnostic-shape mismatch.
12396        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
12397        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
12398        // through_to_string` / `contrato_target_ctors_route_edge_
12399        // triple_through_verbatim` / `contrato_empty_pair_ctors_
12400        // route_edge_pair_through_verbatim` cross-axis routing pins on
12401        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
12402        // here onto the `SupervisorError` `{ caixa: String }` envelope
12403        // so every substrate-primitive ctor family in caixa-core
12404        // guarantees the sole-field construction routes the caller's
12405        // `&str` through `.to_string()` verbatim.
12406        let name = "cache-v2";
12407        assert_eq!(
12408            SupervisorError::empty_child_version(name),
12409            SupervisorError::EmptyChildVersion {
12410                caixa: name.to_string(),
12411            },
12412        );
12413        assert_eq!(
12414            SupervisorError::duplicate_child_caixa(name),
12415            SupervisorError::DuplicateChildCaixa {
12416                caixa: name.to_string(),
12417            },
12418        );
12419        assert_eq!(
12420            SupervisorError::child_supervises_self(name),
12421            SupervisorError::ChildSupervisesSelf {
12422                caixa: name.to_string(),
12423            },
12424        );
12425    }
12426
12427    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
12428    //
12429    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
12430    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
12431    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
12432    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
12433    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
12434    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
12435    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
12436    // / silent constant-substitution on any one variant surfaces here rather
12437    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
12438    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
12439    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
12440    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
12441    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
12442    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
12443    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
12444    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
12445    #[test]
12446    fn no_children_ctor_matches_struct_literal_wrap() {
12447        let estrategia = RestartStrategy::OneForAll;
12448        assert_eq!(
12449            SupervisorError::no_children(estrategia),
12450            SupervisorError::NoChildren { estrategia },
12451            "generated no_children ctor must produce byte-equal \
12452             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
12453             on the same `Copy`-`RestartStrategy` fixture",
12454        );
12455    }
12456
12457    #[test]
12458    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
12459        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
12460        assert_eq!(
12461            SupervisorError::max_restarts_exceeds_cap(max_restarts),
12462            SupervisorError::MaxRestartsExceedsCap { max_restarts },
12463            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
12464             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
12465             struct-literal wrap on the same `Copy`-`u32` fixture",
12466        );
12467    }
12468
12469    #[test]
12470    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
12471        let window = Duration::from_micros(1_500);
12472        assert_eq!(
12473            SupervisorError::restart_window_not_canonical(window),
12474            SupervisorError::RestartWindowNotCanonical { window },
12475            "generated restart_window_not_canonical ctor must produce \
12476             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
12477             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
12478        );
12479    }
12480
12481    #[test]
12482    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
12483        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
12484        assert_eq!(
12485            SupervisorError::restart_window_exceeds_cap(window),
12486            SupervisorError::RestartWindowExceedsCap { window },
12487            "generated restart_window_exceeds_cap ctor must produce \
12488             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
12489             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
12490        );
12491    }
12492
12493    #[test]
12494    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
12495        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
12496        // constructor input axis through a non-default `Copy` fixture against
12497        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
12498        // side silent `.into()` / silent constant-substitution / silent field
12499        // re-name away from the canonical `estrategia | max_restarts | window`
12500        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
12501        // axis silently rerouted through some other `Copy` coercion, surfaces
12502        // here rather than at a downstream per-`:supervisor` diagnostic-shape
12503        // drift. Peer of the sibling
12504        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
12505        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
12506        // envelope's per-`:politicas` per-axis ctor family, extended here onto
12507        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
12508        // variant family folded onto a substrate primitive.
12509        //
12510        // Fixtures picked out of each variant's accept-set boundary rather
12511        // than the default value so a silent constant-substitution to a per-
12512        // variant sentinel surfaces here on the structural-equality assertion.
12513        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
12514        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
12515        // isn't the `SimpleOneForOne` arm the sibling
12516        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
12517        // `max_restarts` fixture picks an above-cap magnitude the cap arm
12518        // rejects; the two `Duration` fixtures pick the sub-millisecond and
12519        // above-cap ends of the `:restart-window` canonical-form + cap
12520        // bracket respectively.
12521        let estrategia = RestartStrategy::RestForOne;
12522        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
12523        let sub_ms = Duration::from_micros(1_500);
12524        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
12525        assert_eq!(
12526            SupervisorError::no_children(estrategia),
12527            SupervisorError::NoChildren { estrategia },
12528        );
12529        assert_eq!(
12530            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
12531            SupervisorError::MaxRestartsExceedsCap {
12532                max_restarts: above_cap_restarts,
12533            },
12534        );
12535        assert_eq!(
12536            SupervisorError::restart_window_not_canonical(sub_ms),
12537            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
12538        );
12539        assert_eq!(
12540            SupervisorError::restart_window_exceeds_cap(above_hour),
12541            SupervisorError::RestartWindowExceedsCap { window: above_hour },
12542        );
12543    }
12544
12545    #[test]
12546    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
12547        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
12548        // generated ctor `const fn` so a caller can pin a `SupervisorError`
12549        // at compile time — the same zero-runtime-work property the pre-lift
12550        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
12551        // its `Copy`-pass-through construction path (no `.to_string()` /
12552        // `.into()` allocation, no branching). If any future edit silently
12553        // drops the `const` qualifier from the macro body the per-arm `const`
12554        // bindings below fail to compile, which surfaces the regression at
12555        // the substrate-primitive definition rather than at some downstream
12556        // consumer that had come to rely on the `const`-constructibility.
12557        // Peer of the sibling
12558        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
12559        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
12560        // per-`:politicas` per-axis ctor family.
12561        const NO_CHILDREN: SupervisorError =
12562            SupervisorError::no_children(RestartStrategy::OneForAll);
12563        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
12564        const WINDOW_NC: SupervisorError =
12565            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
12566        const WINDOW_CAP: SupervisorError =
12567            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
12568        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
12569        assert!(matches!(
12570            MAX_RESTARTS_CAP,
12571            SupervisorError::MaxRestartsExceedsCap { .. }
12572        ));
12573        assert!(matches!(
12574            WINDOW_NC,
12575            SupervisorError::RestartWindowNotCanonical { .. }
12576        ));
12577        assert!(matches!(
12578            WINDOW_CAP,
12579            SupervisorError::RestartWindowExceedsCap { .. }
12580        ));
12581    }
12582}