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/// Per-child restart policy.
956///
957/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
958#[derive(
959    Serialize,
960    Deserialize,
961    Debug,
962    Clone,
963    Copy,
964    PartialEq,
965    Eq,
966    Hash,
967    gen_platform::TypedDispatcher,
968    gen_platform::Discriminant,
969    gen_platform::IsVariant,
970    gen_platform::FromStrKind,
971)]
972pub enum RestartPolicy {
973    /// Always restart the child, regardless of how it died. Used for
974    /// long-running services that must always be up.
975    Permanent,
976    /// Never restart. Used for one-shot work whose completion is
977    /// itself the success signal (`oneShot` triggers map here).
978    Temporary,
979    /// Restart only when the child died *abnormally* (non-zero exit
980    /// or unhandled exception). A clean exit completes the child.
981    Transient,
982}
983
984impl Default for RestartPolicy {
985    fn default() -> Self {
986        // Route the [`Default for RestartPolicy`] impl's return arm through
987        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
988        // `pub const` rather than a raw `Self::Permanent` arm — one source
989        // of truth for the Erlang/OTP-canonical `permanent` worker-child
990        // default across the two production consumers that currently
991        // dispatch on it (this impl at the [`RestartPolicy::default`] call
992        // and the serde-side `#[serde(default)]` on
993        // [`ChildSpec::restart`] that resolves an author-omitted
994        // `:children :restart` slot through `RestartPolicy::default()`).
995        // Peer of the sibling per-`:supervisor` axis
996        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
997        // route (95ffacc) — the two impls now share one substrate-primitive
998        // lift discipline, so any future coherent rebrand of the OTP-shape
999        // supervisor+child default set migrates through typed constants in
1000        // lockstep instead of splitting a lifted supervisor half against
1001        // an open-coded child half. Pinned by
1002        // `restart_policy_default_routes_through_lifted_default` +
1003        // `child_spec_serde_default_restart_routes_through_lifted_default`
1004        // in the tests module.
1005        SUPERVISOR_CHILD_RESTART_DEFAULT
1006    }
1007}
1008
1009impl RestartPolicy {
1010    /// Exhaustive iteration surface for every consumer that walks the
1011    /// closed three-arm [`RestartPolicy`] discriminator set (the future
1012    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1013    /// per-child admission-webhook rejection body naming the accepted-
1014    /// `:restart` list, a future `feira supervisor --restart …` CLI
1015    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
1016    /// over the slice, the future `feira app graph` per-child restart
1017    /// column, any future round-trip fuzz harness that sweeps every
1018    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
1019    /// theory
1020    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1021    /// might reach for once the three canonical OTP restart policies
1022    /// stop covering the substrate's discovered load-shape) extends
1023    /// this slice as one edit and every consumer picks up the new entry
1024    /// by construction; the compiler-checked exhaustiveness on the
1025    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
1026    /// is the build-time guarantee that no arm forgets to grow.
1027    ///
1028    /// Peer of the sibling closed-set typed enums'
1029    /// [`RestartStrategy::ALL`] (4eec29c) /
1030    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
1031    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
1032    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
1033    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
1034    /// surfaces — the sixth (and the third and final M2 OTP-shape)
1035    /// closed-set typed enum on the caixa surface to converge onto the
1036    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
1037    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
1038    /// sibling-restart-strategy axis; this closes the per-child
1039    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
1040    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
1041
1042    /// Canonical PascalCase discriminator scalar this variant serializes
1043    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
1044    /// arms return the paired
1045    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1046    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1047    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1048    /// constants so every substrate consumer that dispatches on the
1049    /// per-child restart-decision policy (the future wasm-operator's
1050    /// per-child post-exit restart-decision branch, the future M4
1051    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1052    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
1053    /// reconciliation scheduler's per-child-policy fan-out) reads the
1054    /// same byte-string the `Serialize` derive emits — the pin test in
1055    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1056    /// asserts the two paths agree, peer of the M2
1057    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
1058    /// sibling-restart-strategy axis and the M3
1059    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
1060    /// per-Aplicacao distribution-strategy axis — the third of three
1061    /// OTP-shaped closed-enum discriminator axes on the caixa typed
1062    /// surface to converge onto the same three-path-convergence
1063    /// (`Serialize` derive → `as_str` helper → lifted constant)
1064    /// drift-detection posture.
1065    #[must_use]
1066    pub const fn as_str(self) -> &'static str {
1067        match self {
1068            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1069            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1070            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1071        }
1072    }
1073
1074    /// Substrate-canonical reverse projection on the `:children :restart`
1075    /// closed-set axis — parses the `PascalCase` discriminator scalar
1076    /// back to the typed variant, or `None` when `s` is outside the
1077    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
1078    /// the same lifted
1079    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1080    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1081    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
1082    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
1083    /// of the round-trip migrate through one caixa-core edit on any
1084    /// future arm addition.
1085    ///
1086    /// Prior to this lift the substrate carried only the forward
1087    /// `Self → &str` projection on the OTP per-child restart-policy
1088    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
1089    /// impl routed through it, the `Serialize` derive that emits the
1090    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
1091    /// plus the kebab-case dispatcher-catalog identity via
1092    /// [`Self::discriminant`] — every non-serde consumer that wanted to
1093    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
1094    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
1095    /// "Transient" => …, _ => … }` cascade that expressed no
1096    /// compile-time link back to the typed variant's canonical lifted
1097    /// constant. A future variant rename or per-arm serde-attribute
1098    /// drift would silently split the wire byte-string one non-serde
1099    /// consumer parsed from the one the emitter wrote, with the failure
1100    /// surfacing at the operator's reconcile posture (a `:temporary`
1101    /// `oneShot` child being restarted on clean exit, treating the
1102    /// successful-completion signal as failure and re-running the
1103    /// completion-terminal one-shot indefinitely; a `:transient` child
1104    /// that clean-exited being restarted, masking the clean-completion
1105    /// contract) far from the rebrand commit and with no field naming
1106    /// the drift.
1107    ///
1108    /// Distinct axis from the [`std::str::FromStr`] impl the
1109    /// [`gen_platform::FromStrKind`] derive already installs on this
1110    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
1111    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
1112    /// `"transient"` — the inverse of [`Self::discriminant`]), while
1113    /// this method inverts the `PascalCase` wire byte-string
1114    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
1115    /// catalog identity live in kebab-case (where every peer catalog
1116    /// identifier already lives) without forcing a wire-format rename
1117    /// on the tatara-lisp author surface (`:restart Permanent`,
1118    /// `PascalCase`) — the same two-axis distinction the sibling
1119    /// [`RestartStrategy::from_wire`] (4eec29c) /
1120    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1121    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
1122    /// carry on their peer closed-set typed-enum wire round-trips.
1123    ///
1124    /// Same closed-set-reverse-projection discipline the sibling
1125    /// [`RestartStrategy::from_wire`] (4eec29c) /
1126    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1127    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
1128    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
1129    /// carry on the peer wire-side `str → Self` axes — extended onto
1130    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
1131    /// sixth substrate-side closed-set typed enum (and the third and
1132    /// final OTP-shape closed-enum discriminator axis) to converge on
1133    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
1134    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
1135    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
1136    /// derive already installs on the sibling kebab-case axis. Returns
1137    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
1138    /// shapes: the caller picks the diagnostic form appropriate for
1139    /// its use site.
1140    #[must_use]
1141    pub fn from_wire(s: &str) -> Option<Self> {
1142        match s {
1143            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
1144            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
1145            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
1146            _ => None,
1147        }
1148    }
1149}
1150
1151/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
1152/// pretty-printed byte-string every consumer that formats the policy as
1153/// user-facing text lands on (the future wasm-operator's per-child
1154/// post-exit restart-decision diagnostic line, the future `feira app
1155/// graph` per-child restart column, the future M4
1156/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1157/// admission-webhook rejection body) reaches for the same lifted
1158/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1159/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1160/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1161/// wire-format `Serialize` derive already emits under
1162/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
1163/// [`RestartPolicy::as_str`] helper already returns.
1164///
1165/// Pre-convergence the two paths structurally disagreed — the
1166/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1167/// route (now retired here) sent [`std::fmt::Display`] through the
1168/// gen-platform discriminant catalog string, which arrives kebab-case as
1169/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1170/// (whose variant names each collapse to their own lowercase form under
1171/// the kebab-case transform), while the wire format ran as `PascalCase`
1172/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1173/// serde derive. Every consumer that formatted the policy for a
1174/// diagnostic line, a graph column, or a rejection body under
1175/// `format!("{v}")` therefore landed under a different byte-string than
1176/// the wire format the operator's per-child-policy dispatch keyed off —
1177/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1178/// diagnostic quoting `"permanent"` while the wire scalar the operator
1179/// probed was `"Permanent"`) surfaced as a confused correlate at
1180/// operator-log time far from the two-declaration site.
1181///
1182/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1183/// path: every `format!("{v}")` call reaches the same lifted
1184/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1185/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1186/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1187/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1188/// byte-string per variant. A future variant rename or
1189/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1190/// exactly one place, structurally.
1191///
1192/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1193/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1194/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1195/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1196/// registration keys the catalog off the same kebab identity. The two
1197/// naming worlds now live on separate typed methods (`Display` /
1198/// `as_str` for the wire byte-string, `discriminant` for the catalog
1199/// identity) rather than sharing one `Display` route that structurally
1200/// disagrees with the wire format.
1201///
1202/// Pin tests
1203/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1204/// and
1205/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1206/// assert the three paths agree byte-for-byte on every variant, so a
1207/// future variant rename or per-arm serde attribute drift is a build
1208/// error visible at caixa-core test time, not a silent per-consumer
1209/// dispatch miss at apply / reconcile time.
1210///
1211/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1212/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1213/// and the sibling [`RestartStrategy`] `Display` impl on the
1214/// per-supervisor sibling-restart-strategy axis — same three-path-
1215/// convergence discipline, extended to close the third and final of
1216/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1217/// surface.
1218impl std::fmt::Display for RestartPolicy {
1219    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1220        f.write_str(self.as_str())
1221    }
1222}
1223
1224/// Substrate-canonical [`AsRef<str>`] projection on the M2
1225/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1226/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1227/// scalar accessor the paired [`std::fmt::Display`] impl and the
1228/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1229/// future consumer that binds a [`RestartPolicy`] through the
1230/// standard-library `impl AsRef<str>` bound (a future
1231/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1232/// composes the emitted `PascalCase` wire scalar into a
1233/// [`std::process::Command::arg`] shell-out of the future
1234/// wasm-operator's per-child admission gate, a per-child structured-
1235/// log recorder on the future `caixa-operator`'s hierarchical
1236/// reconciliation surface that accepts `impl AsRef<str>` at the
1237/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1238/// lookup keyed on the restart-policy wire byte through
1239/// `map.get::<str>(policy.as_ref())` on a future per-policy
1240/// dispatch table) reaches the paired
1241/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1242/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1243/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1244/// lifted-const through one substrate-primitive dispatch rather
1245/// than an open-coded `.as_str()` projection at every wire-up.
1246///
1247/// Peer of the sibling [`std::fmt::Display`] impl on the same
1248/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1249/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1250/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1251/// byte-string per instance by construction. A future variant rename
1252/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1253/// enum reaches every one of the three paths (plus the wire-format
1254/// `Serialize` derive that already routes through the same lifted
1255/// const) through exactly one caixa-core edit.
1256///
1257/// Same "route the trait impl through the substrate-primitive
1258/// accessor" discipline the sibling [`crate::CaixaVersion`]
1259/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1260/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1261/// the axis onto the paired per-child-restart-decision-policy
1262/// sibling on the same M2 `:supervisor` slot (the second M2
1263/// OTP-shape closed-set typed enum to converge onto the standard-
1264/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1265/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1266/// primitive so a caller who has one has both; before this lift,
1267/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1268/// [`AsRef<str>`] impl the convention names.
1269///
1270/// Pinned load-bearing by
1271/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1272/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1273/// three-arm closed set) and
1274/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1275/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1276/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1277/// arm) — any future silent detour that routes the impl through a
1278/// divergent projection (a per-arm inline `match self { … }`
1279/// re-inlining that opens a compile-time link to the un-lifted
1280/// arm-literal, a swap onto the kebab-case
1281/// [`gen_platform::Discriminant`] catalog identity that would
1282/// collide the wire axis with the dispatcher-catalog axis) trips at
1283/// caixa-core test time under `assert_eq!` rather than at a
1284/// downstream `impl AsRef<str>`-bound consumer's silent split.
1285impl AsRef<str> for RestartPolicy {
1286    fn as_ref(&self) -> &str {
1287        self.as_str()
1288    }
1289}
1290
1291/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1292/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1293/// byte-for-byte through the paired substrate-primitive
1294/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1295/// consumer that binds a `PascalCase` `:children :restart` wire
1296/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1297/// axis (a future [`caixa-feira`] `feira supervisor --restart
1298/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1299/// `let restart: RestartPolicy = s.try_into()?`, a future
1300/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1301/// `spec.children[*].restart: String` field through
1302/// `RestartPolicy::try_from(&s)?`, a generic
1303/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1304/// set typed enums) reaches the same three-arm accept-set the sibling
1305/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1306/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1307/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1308/// … }` cascade whose arm-set has no compile-time link back to the
1309/// substrate primitive.
1310///
1311/// Complements the pre-existing forward-projection triple
1312/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1313/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1314/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1315/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1316/// caller who can project *out to* a `&str` can also project *in from*
1317/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1318/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1319/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1320/// trigger under a `FromStr` impl and to avoid colliding with the
1321/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1322/// already installs on the paired *kebab-case dispatcher-catalog* axis
1323/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1324/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1325/// idiomatic reverse axis on the *`PascalCase` wire* half without
1326/// disturbing either the method-named `from_wire` shape every sibling
1327/// closed-set typed enum on the substrate already carries or the
1328/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1329/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1330///
1331/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1332/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1333/// caller picks the diagnostic form appropriate for its use site (a
1334/// future `feira supervisor --restart` arg-parse composes its own
1335/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1336/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1337/// wraps the `Err(())` outcome with the accepted-set enumeration for
1338/// operator diagnostics, a `Result::map_err` at the call site lifts the
1339/// unit-error to a per-verb error type). Same shape the peer
1340/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1341/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1342/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1343/// their peer closed-set typed enums' reverse projections.
1344///
1345/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1346/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1347/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1348/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1349/// might reach for once the three canonical OTP restart policies stop
1350/// covering the substrate's discovered load-shape) grows the trait-
1351/// idiomatic axis by construction — one caixa-core edit on
1352/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1353/// projection every existing consumer keys off and the trait-idiomatic
1354/// reverse projection this impl exposes, without a coordinated rewrite
1355/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1356///
1357/// Extends the substrate-wide closed-set-enum reverse-projection family
1358/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1359/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1360/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1361/// closed-enum discriminator axis on the caixa surface — the paired
1362/// per-child `:children :restart` closed set the future wasm-operator's
1363/// hierarchical reconciliation scheduler's per-child post-exit
1364/// restart-decision branch keys off end-to-end.
1365///
1366/// Pinned load-bearing by
1367/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1368/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1369/// three-arm accept-set),
1370/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1371/// (rejection witness against silent accept-set widening), and
1372/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1373/// (cross-axis partition pin locking the trait and method-named
1374/// projections onto one accept-set).
1375impl TryFrom<&str> for RestartPolicy {
1376    type Error = ();
1377
1378    fn try_from(s: &str) -> Result<Self, Self::Error> {
1379        Self::from_wire(s).ok_or(())
1380    }
1381}
1382
1383/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1384/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1385/// byte-for-byte through the paired substrate-primitive
1386/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1387/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1388/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1389/// &str` with `'static` lifetime, so the trait's return-type promise is
1390/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1391/// literal.
1392///
1393/// Every future consumer that specifically needs `&'static str` lifetime
1394/// bytes on the per-child restart-decision axis (a
1395/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1396/// arm's typing demands `&'static str`, a
1397/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1398/// on the future M4 admission-webhook rejection body where the
1399/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1400/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1401/// or error formatter that requires the `'static` bound) reaches the same
1402/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1403/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1404/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1405/// primitive dispatch rather than an open-coded per-arm literal cascade
1406/// whose arm-set has no compile-time link back to the substrate primitive.
1407///
1408/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1409/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1410/// the second (and second-of-two-in-M2) closed-set typed enum on the
1411/// caixa surface to converge onto the paired trait-idiomatic forward-
1412/// projection axis. With this lift the paired per-child
1413/// `:children :restart` closed-set typed enum carries the full sibling
1414/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1415/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1416/// lift) plus the round-trip witness through both the trait-idiomatic
1417/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1418/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1419/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1420/// (an OTP-`intrinsic` fourth arm the theory
1421/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1422/// might reach for once the three canonical OTP restart policies stop
1423/// covering the substrate's discovered load-shape) grows the trait-
1424/// idiomatic forward axis by construction: one caixa-core edit on
1425/// [`RestartPolicy::as_str`] extends every one of the five sibling
1426/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1427/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1428/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1429/// bytes) without a coordinated rewrite across every future
1430/// `Into<&'static str>`-bound consumer's arm-set.
1431///
1432/// Pinned load-bearing by
1433/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1434/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1435/// three-arm emit-set, plus a `const`-context materialization witness for
1436/// the `&'static str` lifetime promise) and
1437/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1438/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1439/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1440/// round-trip witness through the paired trait-idiomatic reverse-
1441/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1442/// `policy.into::<&'static str>()` output re-parses back through
1443/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1444/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1445impl From<RestartPolicy> for &'static str {
1446    fn from(policy: RestartPolicy) -> &'static str {
1447        policy.as_str()
1448    }
1449}
1450
1451/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
1452/// *borrowed* input onto the `&'static str` axis — the borrowed-input
1453/// companion to the paired owned-input [`From<RestartPolicy> for
1454/// &'static str`] impl immediately above. Routes byte-for-byte through
1455/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
1456/// fn` accessor so every consumer that binds a `&RestartPolicy`
1457/// through the standard-library `.into()` / [`From<&Self> for &'static
1458/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
1459/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
1460/// whose iterator over `&'static [RestartPolicy]` yields
1461/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
1462/// [`From<RestartPolicy>`] axis alone forces every call site through
1463/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
1464/// rather than the direct trait-idiomatic projection; a future generic
1465/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
1466/// that walks the `iter().map(Into::into)` shape verbatim across every
1467/// substrate-wide closed-set typed enum; the future wasm-operator's
1468/// per-child post-exit restart-decision diagnostic line that composes
1469/// the accepted-set enumeration from an iterated
1470/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1471/// per-arm `match p { … }` cascade; a future
1472/// `HashMap::<&'static str, RestartPolicy>::from_iter(
1473///     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
1474/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
1475/// cannot compose without this borrowed-input axis in place) reaches
1476/// the same three-arm lifted
1477/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1478/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1479/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1480/// paired owned-input [`From<RestartPolicy> for &'static str`], the
1481/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
1482/// [`RestartPolicy::as_str`] surfaces already return.
1483///
1484/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
1485/// forward-projection family opened on [`crate::dep::DepList`]
1486/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
1487/// [`crate::CaixaDialeto`] (807b0b5), and the paired
1488/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
1489/// (e941836). Rust's `From` trait does not auto-derive the
1490/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
1491/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
1492/// exist in `core`), so every closed-set typed enum that carries the
1493/// owned-input axis but not the borrowed-input axis forces every
1494/// borrowed-input call site through a `.copied()` /
1495/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
1496/// type bounds have no compile-time link to the substrate primitive.
1497/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
1498/// OTP-shape peer to converge onto this campaign — sibling of the
1499/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
1500/// with this lift both closed-set typed enums on the M2 `:supervisor`
1501/// slot now carry the full sibling quintet ([`std::fmt::Display`],
1502/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
1503/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
1504/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
1505/// forward-projection axis on the M2 OTP-shape slot as a unit.
1506///
1507/// Same three-path convergence discipline as the paired owned-input
1508/// impl (this borrowed-input axis, the paired owned-input
1509/// [`From<RestartPolicy> for &'static str`], and
1510/// [`RestartPolicy::as_str`] all route through the same lifted
1511/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
1512/// variant rename or per-arm serde-attribute drift reaches every one
1513/// of the six sibling forward-projection paths
1514/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1515/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
1516/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
1517/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
1518/// edit.
1519///
1520/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
1521/// parse share the same `PascalCase` vocabulary by construction, so
1522/// the borrowed-input forward axis and the reverse axis compose
1523/// directly — the round-trip witness pin below locks this direct
1524/// composition without the intermediate wire-vocab hop the peer
1525/// [`crate::CaixaKind`] axis pair requires.
1526///
1527/// Pinned load-bearing by
1528/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
1529/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1530/// three-arm emit-set via a borrowed input, plus a `const`-context
1531/// materialization witness for the `&'static str` lifetime promise,
1532/// plus a blanket `.into()` shape) and
1533/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
1534/// (cross-axis partition pin against the paired owned-input
1535/// [`From<RestartPolicy> for &'static str`] impl, plus a
1536/// `.iter().map(Into::into)` pipe witness over
1537/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1538/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
1539/// Self` round-trip without the wire-vocab intermediate the peer
1540/// [`crate::CaixaKind`] axis pair requires).
1541impl From<&RestartPolicy> for &'static str {
1542    fn from(policy: &RestartPolicy) -> &'static str {
1543        policy.as_str()
1544    }
1545}
1546
1547/// Trait-idiomatic *owned-`String`* forward projection on the second
1548/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
1549/// owned-heap-string companion to the paired `&'static str`-returning
1550/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
1551/// for &'static str`] impls immediately above. Routes byte-for-byte
1552/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
1553/// const fn` accessor (via [`str::to_owned`]) so every consumer that
1554/// binds a [`RestartPolicy`] through the standard-library `.into()` /
1555/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
1556/// future `serde_json::Value::String(policy.into())` structured-payload
1557/// composer where the `Value::String` arm typing demands an owned
1558/// [`String`] and the sibling [`&'static str`]-returning axis forces
1559/// an explicit `.to_owned()` / `String::from` restatement at every
1560/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
1561/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
1562/// lookup where the map's key type is owned [`String`] rather than
1563/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
1564/// composer on the future M4 admission-webhook rejection body's
1565/// owned-arm, the future wasm-operator's per-child post-exit
1566/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
1567/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
1568/// — reaches the same three-arm lifted
1569/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1570/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1571/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1572/// paired [`std::fmt::Display`], [`AsRef<str>`],
1573/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
1574/// forward-projection impls already return.
1575///
1576/// Extends the trait-idiomatic *owned-`String`* forward-projection
1577/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
1578/// the caixa surface — mirror of the first-mover
1579/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
1580/// axis on the sibling supervisor-level strategy enum. Rust's standard
1581/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
1582/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
1583/// every closed-set typed enum that carries the paired `AsRef<str>` /
1584/// `Display` / `From<Self> for &'static str` triple but not the
1585/// owned-[`String`] axis forces every owned-string call site through a
1586/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
1587/// detour whose type bounds have no compile-time link to the
1588/// substrate primitive.
1589///
1590/// Deliberately routes through the human-readable
1591/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1592/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1593/// the diagnostic byte-string share the same vocabulary by
1594/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1595/// two axes diverge), so the owned-[`String`] projection lands
1596/// byte-identically on both the wire vocabulary the paired
1597/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
1598/// [`RestartPolicy::as_str`] helper returns, and — because the paired
1599/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
1600/// axis parses the same `PascalCase` vocabulary — the direct two-way
1601/// `Self → String → Self` round-trip composes without the wire-vocab
1602/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
1603/// axis pair requires.
1604///
1605/// Pinned load-bearing by
1606/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
1607/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1608/// three-arm emit-set, plus a blanket `.into::<String>()` shape
1609/// witness) and
1610/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
1611/// (cross-axis partition pin against the paired owned-input
1612/// [`From<RestartPolicy> for &'static str`] impl and the sibling
1613/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
1614/// plus a `.iter().copied().map(String::from)` pipe witness over
1615/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1616/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
1617/// borrow that closes the two-way `Self → String → Self` round-trip
1618/// on the trait-idiomatic owned-[`String`] forward + reverse axis
1619/// pair).
1620impl From<RestartPolicy> for String {
1621    fn from(policy: RestartPolicy) -> String {
1622        policy.as_str().to_owned()
1623    }
1624}
1625
1626/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
1627/// projection on the second-of-two M2 OTP-shape closed-set typed enum
1628/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
1629/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1630/// projection family on this enum, mirror of the first-mover
1631/// [`From<&RestartStrategy> for String`] (579385f) that opened the
1632/// 2×2-completion corner on the sibling supervisor-level strategy
1633/// enum. Routes byte-for-byte through the substrate-primitive
1634/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
1635/// [`str::to_owned`]) so every consumer that holds a borrowed
1636/// [`&RestartPolicy`] and needs an owned [`String`] — a future
1637/// `serde_json::Value::String(String::from(&policy))` structured-payload
1638/// composer over a borrowed field, a future `Iterator::map` over
1639/// `&[RestartPolicy]` that projects to owned keys through
1640/// `.iter().map(String::from)`, a future `HashMap::<String,
1641/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
1642/// where dereferencing the policy would force an unnecessary `Copy` at
1643/// every step, the future wasm-operator's per-supervisor
1644/// `child_policies.iter().map(String::from).collect()` per-child post-
1645/// exit restart-decision diagnostic emit whose iteration axis is
1646/// borrowed by construction — reaches the same three-arm lifted
1647/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1648/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1649/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1650/// paired [`std::fmt::Display`], [`AsRef<str>`],
1651/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
1652/// forward-projection impls
1653/// ([`From<RestartPolicy> for &'static str`],
1654/// [`From<&RestartPolicy> for &'static str`],
1655/// [`From<RestartPolicy> for String`]) already return.
1656///
1657/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
1658/// owned-`String` output* forward-projection family opened on
1659/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
1660/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
1661/// both M2 OTP-shape sibling peers (the paired supervisor-level
1662/// sibling-restart-strategy axis and the per-child restart-decision-
1663/// policy axis), so the whole M2 OTP-shape axis pair now carries the
1664/// full four-corner family by construction. Rust's standard library
1665/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
1666/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
1667/// closed-set typed enum that carries the paired `AsRef<str>` /
1668/// `Display` / `From<Self> for &'static str` / `From<&Self> for
1669/// &'static str` / `From<Self> for String` quintuple but not the
1670/// borrowed-input owned-[`String`] axis forces every borrowed-input
1671/// owned-string call site through a `policy.as_str().to_owned()` /
1672/// `String::from(*policy)` (with a spurious `Copy`) /
1673/// `policy.to_string()` (through `Display`) detour whose type bounds
1674/// have no compile-time link to the substrate primitive.
1675///
1676/// Deliberately routes through the human-readable
1677/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1678/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1679/// the diagnostic byte-string share the same vocabulary by
1680/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1681/// two axes diverge), so the borrowed-input owned-[`String`]
1682/// projection lands byte-identically on both the wire vocabulary the
1683/// paired [`serde::Serialize`] derive emits and the diagnostic
1684/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
1685/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
1686/// reverse-projection axis parses the same `PascalCase` vocabulary —
1687/// the direct two-way `&Self → String → Self` round-trip composes
1688/// without the wire-vocab intermediate hop the peer
1689/// [`crate::CaixaKind`] axis pair requires.
1690///
1691/// The remaining thirteen closed-set typed enums on the caixa
1692/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
1693/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
1694/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
1695/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
1696/// of this 2×2-completion campaign — each carries the same paired
1697/// quintuple that this borrowed-input owned-[`String`] axis extends
1698/// onto.
1699///
1700/// Pinned load-bearing by
1701/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
1702/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1703/// three-arm emit-set through the borrowed-input surface) and
1704/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
1705/// (cross-axis partition pin against the paired owned-input owned-
1706/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
1707/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
1708/// &'static str`] impl, and the sibling [`ToString::to_string`]
1709/// surface routed through [`std::fmt::Display`], plus a direct round-
1710/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
1711/// [`String::as_str`] borrow that closes the two-way
1712/// `&Self → String → Self` round-trip on the trait-idiomatic
1713/// borrowed-input owned-[`String`] forward + reverse axis pair).
1714impl From<&RestartPolicy> for String {
1715    fn from(policy: &RestartPolicy) -> String {
1716        policy.as_str().to_owned()
1717    }
1718}
1719
1720/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
1721/// output* forward projection on the M2 OTP-shape per-child-restart
1722/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
1723/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
1724/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
1725/// borrowed-input) and first extended off it onto the sibling M2
1726/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
1727/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
1728/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
1729/// surface (`:children :restart`). Routes byte-for-byte through the
1730/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
1731/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
1732/// that binds a [`RestartPolicy`] through the trait-idiomatic
1733/// [`std::borrow::Cow<'static, str>`] axis — a future
1734/// `axum::response::IntoResponse` composer whose per-policy
1735/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
1736/// borrowed return, a future M4 admission-webhook rejection body
1737/// that composes the accepted-policy enumeration through the same
1738/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
1739/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
1740/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
1741/// emitter on a per-child-policy diagnostic column — reaches the same
1742/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
1743/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1744/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1745/// paired [`std::fmt::Display`], [`AsRef<str>`],
1746/// [`RestartPolicy::as_str`], and the four
1747/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1748/// forward-projection corners already return.
1749///
1750/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
1751/// [`std::borrow::Cow::Owned`] — the substrate-primitive
1752/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
1753/// str` lifetime by construction (each `match` arm resolves to a
1754/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
1755/// with static lifetime), so the zero-alloc borrowed arm is the
1756/// type-correct projection with no runtime allocation.
1757///
1758/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
1759/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
1760/// From<T> for Cow<'static, str>`), so the paired sibling
1761/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
1762/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
1763/// [`std::fmt::Display`] surfaces do not implicitly extend to a
1764/// [`Cow<'static, str>`]-bound call site — every such site is forced
1765/// through a `Cow::Borrowed(policy.as_str())` /
1766/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
1767/// no compile-time link back to the substrate primitive until this
1768/// lift.
1769///
1770/// Second peer to extend the substrate-wide trait-idiomatic
1771/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
1772/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
1773/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
1774/// tier of the campaign (both sibling peers, `RestartStrategy` and
1775/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
1776/// forward projection) so the remaining eleven peers
1777/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
1778/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
1779/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
1780/// `FerriteRuntime`) are the future targets. Every future arm addition
1781/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
1782/// might reach for once the three canonical OTP restart policies stop
1783/// covering the substrate's discovered load-shape) grows the
1784/// Cow<'static, str> axis by construction through one caixa-core edit
1785/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
1786/// across every future Cow<'static, str>-bound consumer site.
1787///
1788/// Pinned load-bearing by
1789/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
1790/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
1791/// against [`RestartPolicy::as_str`] across the three-arm
1792/// [`RestartPolicy::ALL`]) and
1793/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
1794/// (cross-axis partition pin against the paired [`From<RestartPolicy>
1795/// for &'static str`], [`From<RestartPolicy> for String`], and
1796/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
1797/// `.iter().copied().map(Cow::from)` pipe witness over
1798/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
1799/// through the [`Cow<'static, str>`] axis alone and pins the
1800/// zero-alloc discipline on every element).
1801impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
1802    fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
1803        std::borrow::Cow::Borrowed(policy.as_str())
1804    }
1805}
1806
1807/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
1808/// output* forward projection on the M2 OTP-shape per-child-restart
1809/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
1810/// companion to the paired owned-input
1811/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
1812/// immediately above (0612398). Routes byte-for-byte through the same
1813/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
1814/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
1815/// that holds a `&RestartPolicy` and needs a
1816/// [`std::borrow::Cow<'static, str>`] — a
1817/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
1818/// per-arm accept-set materializer (whose iterator over
1819/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
1820/// `RestartPolicy`, so the paired owned-input
1821/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
1822/// alone forces every call site through an explicit `.copied()` /
1823/// dereference / [`Copy`]-bound restatement rather than the direct
1824/// trait-idiomatic projection), a future generic
1825/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
1826/// on a per-child-policy diagnostic column that walks the
1827/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
1828/// webhook rejection body that composes the accepted-policy
1829/// enumeration from an iterated
1830/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1831/// per-arm `match p { … }` cascade — reaches the same three-arm
1832/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1833/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1834/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1835/// paired [`std::fmt::Display`], [`AsRef<str>`],
1836/// [`RestartPolicy::as_str`], the four
1837/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1838/// forward-projection corners, and the paired owned-input
1839/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
1840/// already return.
1841///
1842/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
1843/// [`std::borrow::Cow::Owned`] — the substrate-primitive
1844/// [`RestartPolicy::as_str`] accessor's return carries the
1845/// `&'static str` lifetime by construction (each `match` arm resolves
1846/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
1847/// with static lifetime), so the zero-alloc borrowed arm is the
1848/// type-correct projection with no runtime allocation.
1849///
1850/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
1851/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
1852/// one commit prior (0612398) on the paired owned-input
1853/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
1854/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
1855/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
1856/// which carries both {Self, &Self} × Cow<'static, str> corners since
1857/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
1858/// closed it on the top-level [`crate::CaixaKind`] one commit after
1859/// the owning half (99c1735) landed. This lift closes the whole M2
1860/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
1861/// forward-projection campaign on both input-shape corners
1862/// ({Self, &Self}) of both M2 OTP-shape sibling peers
1863/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
1864/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
1865/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
1866/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
1867/// `FerriteRuntime`) become the future targets of the campaign. Rust's
1868/// standard library does not carry a blanket
1869/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
1870/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
1871/// closed-set fieldless typed enum peer on the substrate that carries
1872/// the paired owned-input [`Cow<'static, str>`] axis but not the
1873/// borrowed-input axis forces every borrowed-input
1874/// [`Cow<'static, str>`]-parameterized call site through a spurious
1875/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
1876/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
1877/// bounds have no compile-time link to the substrate primitive.
1878///
1879/// Pinned load-bearing by
1880/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
1881/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
1882/// against [`RestartPolicy::as_str`] across the three-arm
1883/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
1884/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
1885/// (cross-axis partition pin against the paired owned-input
1886/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
1887/// paired borrowed-input owned-`&'static str`
1888/// [`From<&RestartPolicy> for &'static str`], and the paired
1889/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
1890/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
1891/// over [`RestartPolicy::ALL`] — whose iterator yields
1892/// `&RestartPolicy` by construction, so the borrowed-input
1893/// [`Cow<'static, str>`] axis is what routes the pipe through the
1894/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
1895/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
1896/// spurious [`Copy`] deref).
1897impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
1898    fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
1899        std::borrow::Cow::Borrowed(policy.as_str())
1900    }
1901}
1902
1903// Fleet-wide dispatcher-catalog registrations for caixa's OTP
1904// supervisor surface — two more typed shadows over Erlang/OTP
1905// primitives the substrate now mechanically tracks (see
1906// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
1907// theory/TYPED-ABSORPTION.md for the absorption arc).
1908gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
1909gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
1910
1911/// One child entry in the supervisor's `:children` list.
1912///
1913/// Every child references another caixa by `:caixa <nome>` + version
1914/// constraint. The supervisor materializes one ComputeUnit per entry.
1915#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1916#[serde(rename_all = "camelCase")]
1917pub struct ChildSpec {
1918    /// The child caixa's `:nome`. Must resolve via the same dependency
1919    /// resolution path as `:deps` (caixa-resolver).
1920    pub caixa: String,
1921
1922    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
1923    /// [`crate::dep::Dep::versao`].
1924    pub versao: String,
1925
1926    /// Restart policy — an author-omitted slot degrades onto the
1927    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
1928    /// (`permanent`, the Erlang/OTP worker-child default) through the
1929    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
1930    /// to.
1931    #[serde(default)]
1932    pub restart: RestartPolicy,
1933}
1934
1935impl ChildSpec {
1936    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
1937    /// accessor every consumer that reads the OTP-shape supervised
1938    /// child's identity keys off — returns the author-declared
1939    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
1940    /// from the typed slot's own [`String`] storage.
1941    ///
1942    /// The `:children :caixa` slot carries the DNS-1123 label — the
1943    /// child caixa's `:nome` — that every emitted cluster artifact
1944    /// derives its `metadata.name` from verbatim: the rendered
1945    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
1946    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
1947    /// identity, and the per-child K8s Service `metadata.name` the
1948    /// future wasm-operator (M3) provisions for inter-child supervision-
1949    /// tree wiring. Every downstream consumer that fans on the child's
1950    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
1951    /// per-child DNS-1123 gate at
1952    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
1953    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
1954    /// [`validate_no_self_supervision`] cross-slot equality check
1955    /// against the parent's `:nome`, every `SupervisorError` variant
1956    /// carrying the offending child caixa verbatim for `feira lint`
1957    /// rendering, the future wasm-operator's hierarchical reconciliation
1958    /// scheduler's per-child ComputeUnit-name projection, the future M4
1959    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1960    /// admission webhook).
1961    ///
1962    /// Prior to this lift the `.caixa` byte-string was accessed inline
1963    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
1964    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
1965    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
1966    /// carriers' `child.caixa.clone()`, the dedup key's
1967    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
1968    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
1969    /// field-accesses that expressed no compile-time link back to the
1970    /// typed slot. A future extension of the `:children :caixa` axis to
1971    /// a richer author surface (a per-cluster alias table the operator
1972    /// pins through a future `:placement`-scoped slot on the supervisor
1973    /// tree, a namespace-qualified rewrite the M4 CR materializer
1974    /// applies per-CR, a per-child overlay from the future `:children
1975    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1976    /// acknowledges) would have had to be threaded through every
1977    /// open-coded copy in lockstep or one consumer would silently
1978    /// disagree with the peers on which caixa a given child resolves to
1979    /// — a child-set lookup that treated the name as `"cart-worker"`
1980    /// while the peer duplicate-detector treated it as
1981    /// `"tenant-a/cart-worker"` would silently split the
1982    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
1983    /// self-supervision detector's parent-equality check, a two-consumer
1984    /// split at the validator far from the source `caixa.lisp` with no
1985    /// field naming the identity-drift root cause. Lifting the resolution
1986    /// rule to a typed method on the substrate primitive means every
1987    /// downstream consumer of the Supervisor's per-`:children` identity
1988    /// surface reaches for exactly one typed dispatch — the resolver's
1989    /// accept-set migrates as a unit on any future axis addition.
1990    ///
1991    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
1992    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
1993    /// mesh-slot surface — same "one typed dispatch on the substrate
1994    /// primitive, thin projections at each consumer" discipline extended
1995    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
1996    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
1997    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
1998    /// accessor discipline for the shared substrate concept "another
1999    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
2000    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
2001    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
2002    /// slot family's typed-accessor discipline now spans both the
2003    /// upgrade axis (`:upgrade-from`) and the supervision axis
2004    /// (`:children`), matching the closed M3 mesh-slot accessor family's
2005    /// shape. Named `nome()` to match the tatara-lisp author-surface
2006    /// term the field's docstring already reaches for ("The child
2007    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
2008    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
2009    /// discipline the substrate already carries — the accessor's name
2010    /// maps directly onto the canonical caixa-identity vocabulary rather
2011    /// than shadowing the field's storage-side `caixa` label.
2012    #[must_use]
2013    pub const fn nome(&self) -> &str {
2014        self.caixa.as_str()
2015    }
2016
2017    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
2018    /// requirement scalar accessor every consumer that reads the OTP-shape
2019    /// supervised child's version pin keys off — returns the author-declared
2020    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
2021    /// the typed slot's own [`String`] storage.
2022    ///
2023    /// The `:children :versao` slot carries the Cargo-shaped semver
2024    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
2025    /// which release of the supervised child caixa the OTP-shape supervisor
2026    /// tree materializes against — the same requirement grammar the peer
2027    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
2028    /// shared [`crate::render::require_valid_versao_requirement`] cascade
2029    /// and the shared [`crate::version::parse_requirement`] parser. Every
2030    /// downstream consumer that fans on the child's version pin keys off
2031    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
2032    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
2033    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
2034    /// for `feira lint` rendering, every future per-cluster version-lock
2035    /// overlay the caixa-operator's hierarchical reconciliation scheduler
2036    /// pins through a future `:placement`-scoped supervisor-tree slot, the
2037    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2038    /// per-child version resolver, the future wasm-operator's per-child
2039    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
2040    ///
2041    /// Prior to this lift the `.versao` byte-string was accessed inline at
2042    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
2043    /// [`SupervisorSpec::validate`] requirement-gate call
2044    /// `require_valid_versao_requirement(&child.versao, …)` and the
2045    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
2046    /// `versao: child.versao.clone()` — two open-coded field-accesses that
2047    /// expressed no compile-time link back to the typed slot. A future
2048    /// extension of the `:children :versao` axis to a richer author surface
2049    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2050    /// flow, a lacre-projected concrete-version rewrite the operator
2051    /// materializes at CR-admission time, a future `:children :versao-lock`
2052    /// per-cluster override slot the wasm-operator's hierarchical
2053    /// reconciliation scheduler authors per-CR) would have had to be
2054    /// threaded through both open-coded copies in lockstep or one consumer
2055    /// would silently disagree with the peer on which release constraint a
2056    /// given child resolves to — the requirement-gate call reading
2057    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
2058    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
2059    /// the actual gate rejection input, a two-consumer split at the
2060    /// validator far from the source `caixa.lisp` with no field naming the
2061    /// version-pin drift root cause. Lifting the resolution rule to a typed
2062    /// method on the substrate primitive means every downstream
2063    /// requirement-facing consumer of the Supervisor's per-`:children`
2064    /// version-pin surface reaches for exactly one typed dispatch — the
2065    /// resolver's accept-set migrates as a unit on any future axis addition.
2066    ///
2067    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
2068    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
2069    /// surface — same "one typed dispatch on the substrate primitive, thin
2070    /// projections at each consumer" discipline extended onto the M2
2071    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
2072    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
2073    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
2074    /// one accessor discipline for the shared substrate concept "another
2075    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
2076    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
2077    /// `:nome` scalar accessor — the pair
2078    /// `(nome(), versao_requirement())` jointly projects the
2079    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
2080    /// that fans on per-child identity + version pin keys off, closing the
2081    /// last unlifted per-`:children` `String`-carry axis so every downstream
2082    /// per-`:children` reader now routes through a typed dispatch on the
2083    /// substrate primitive. Named `versao_requirement()` rather than
2084    /// `versao()` because the field's storage-side `.versao` label is
2085    /// already the author-surface term (`:versao`); the accessor's name
2086    /// carries the semantic role — the semver *requirement* string the
2087    /// shared [`crate::version::parse_requirement`] entry-point consumes —
2088    /// so a raw field access and a typed dispatch read differently at every
2089    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
2090    /// naming discipline verbatim.
2091    #[must_use]
2092    pub const fn versao_requirement(&self) -> &str {
2093        self.versao.as_str()
2094    }
2095
2096    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
2097    /// per-child post-exit restart-decision policy scalar accessor every
2098    /// consumer that dispatches on the supervised child's post-exit
2099    /// reconcile posture keys off — returns the author-declared
2100    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
2101    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
2102    /// storage.
2103    ///
2104    /// The `:children :restart` slot carries the closed-set OTP-shaped
2105    /// per-child restart-decision policy discriminator
2106    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
2107    /// worker-child default; [`RestartPolicy::Transient`] — restart only
2108    /// on abnormal exit, the OTP `transient` clean-completion-aware
2109    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
2110    /// `temporary` one-shot default) that every downstream consumer of
2111    /// the Supervisor's per-child post-exit reconcile branch keys off.
2112    /// Every future downstream consumer that fans on the per-child
2113    /// restart-decision keys off this scalar (the future `feira app
2114    /// graph` per-child restart column, the future wasm-operator's
2115    /// per-child post-exit restart-decision branch, the future M4
2116    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2117    /// admission webhook, the `caixa-operator`'s hierarchical
2118    /// reconciliation scheduler's per-child post-exit reconcile branch,
2119    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
2120    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
2121    /// pin threads through).
2122    ///
2123    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
2124    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
2125    /// scalar accessor and the M3 mesh-slot
2126    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
2127    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
2128    /// — same "one typed dispatch on the substrate primitive,
2129    /// `Copy`-projected closed-set enum-arm discriminator that partitions
2130    /// the downstream renderer's per-arm fan-out" discipline extended
2131    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
2132    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
2133    /// [`ChildSpec`] type — companion to the sibling per-`:children`
2134    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
2135    /// and the per-`:children` [`ChildSpec::versao_requirement`]
2136    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
2137    /// on the sibling `String`-carry axes. The triple
2138    /// `(nome(), versao_requirement(), restart())` jointly projects the
2139    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
2140    /// tree consumer that fans on per-child identity + version pin +
2141    /// restart-decision keys off, closing the last unlifted per-`:children`
2142    /// axis so every downstream per-`:children` reader now routes through
2143    /// a typed dispatch on the substrate primitive. Named `restart()` to
2144    /// match the storage field's name and the author-surface
2145    /// `:children :restart` slot term verbatim; the accessor's identity
2146    /// name maps onto the canonical OTP-shape per-child restart-decision-
2147    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
2148    /// carries.
2149    ///
2150    /// Declared `pub const fn` to close the last non-`const`
2151    /// `Copy`-return raw-field-getter posture on the M2
2152    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
2153    /// of the sibling M2 per-`:supervisor`
2154    /// [`SupervisorSpec::estrategia`] (converted in this commit)
2155    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
2156    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2157    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
2158    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
2159    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
2160    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
2161    /// downstream substrate-side `const`-context consumer of the
2162    /// per-`:children` restart-decision-policy scalar (a future
2163    /// module-scope `const _:() = assert!(matches!(child.restart(),
2164    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
2165    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2166    /// admission-webhook `const fn` per-child restart-decision floor
2167    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
2168    /// composer over the substrate primitive that fans on the per-child
2169    /// restart-decision policy at compile time) now reaches through the
2170    /// same typed dispatch on the substrate primitive at const-eval
2171    /// time as at runtime. A future non-`Copy`-return promotion of the
2172    /// scalar (an `Option<RestartPolicy>`-shape migration on the
2173    /// per-child restart-decision axis once heterogeneous per-cluster
2174    /// restart-policy overlays land, a per-tenant restart-policy-alias
2175    /// table the M4 CR materializer resolves per-CR) that would drop
2176    /// the `const` qualifier fails the fail-before-pass-after pin
2177    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
2178    /// build time rather than surfacing as a downstream consumer
2179    /// regression.
2180    #[must_use]
2181    pub const fn restart(&self) -> RestartPolicy {
2182        self.restart
2183    }
2184}
2185
2186/// Supervisor-typed slots that live alongside the standard Caixa
2187/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
2188/// the manifest stays a single typed form; this struct exists for
2189/// validation + conversion.
2190#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2191#[serde(rename_all = "camelCase")]
2192pub struct SupervisorSpec {
2193    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
2194    #[serde(default)]
2195    pub estrategia: RestartStrategy,
2196
2197    /// Max restarts within [`Self::restart_window`] before the
2198    /// supervisor itself terminates (and its parent supervisor decides
2199    /// what to do). Default 5.
2200    #[serde(default = "default_max_restarts")]
2201    pub max_restarts: u32,
2202
2203    /// Sliding window for `max_restarts`. Authored as a duration
2204    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
2205    /// is rejected by [`Self::validate`] — Erlang/OTP's
2206    /// `MaxIntensity / Period` invariant requires a positive window
2207    /// (a zero-period supervisor either trips on the first failure or
2208    /// never trips, depending on operator interpretation, neither of
2209    /// which is the author's intent). Omit the slot to express "no
2210    /// reset"; carry a positive duration to express the sliding window.
2211    #[serde(
2212        default,
2213        skip_serializing_if = "Option::is_none",
2214        with = "duration_codec"
2215    )]
2216    pub restart_window: Option<Duration>,
2217
2218    /// Static children. Empty for `SimpleOneForOne` (children added
2219    /// dynamically); required for the other three strategies.
2220    #[serde(default)]
2221    pub children: Vec<ChildSpec>,
2222}
2223
2224const fn default_max_restarts() -> u32 {
2225    // Route the private serde-`#[serde(default = "…")]` helper through
2226    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
2227    // `pub const` rather than the raw `5` literal — one source of truth
2228    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
2229    // default across the two production consumers that currently
2230    // dispatch on it (this helper via `#[serde(default = "…")]` on
2231    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
2232    // impl at line 962). Pinned by
2233    // `default_max_restarts_helper_routes_through_lifted_default` +
2234    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
2235    // in the tests module; peer of the sibling caixa-core
2236    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
2237    // that now routes its author-omitted `:max-restarts` arm through
2238    // the same lifted constant.
2239    SUPERVISOR_MAX_RESTARTS_DEFAULT
2240}
2241
2242/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
2243/// count default for the `:supervisor :max-restarts` axis — the
2244/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
2245/// Erlang's worker-supervisor default, extracted as a typed `pub const`
2246/// so every substrate-side consumer that resolves "what
2247/// [`SupervisorSpec::max_restarts`] value does an author-omitted
2248/// `:max-restarts` slot degrade onto?" reaches for exactly one
2249/// substrate-primitive `u32`.
2250///
2251/// The `:max-restarts` default axis has two production consumers on the
2252/// substrate side today (both prior to this lift folded onto raw `5`
2253/// literals with no compile-time link back to a shared truth): the
2254/// serde-`#[serde(default = "default_max_restarts")]` helper on
2255/// [`SupervisorSpec::max_restarts`] that every author-omitted
2256/// `:supervisor :max-restarts` slot lands in past the derive-macro's
2257/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
2258/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
2259/// the composed [`SupervisorSpec`] altitude reaches through
2260/// (`feira app graph`, the future wasm-operator's per-supervisor
2261/// restart-intensity counter, the future M4
2262/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2263/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
2264/// A pair of open-coded `5`s across two files that expressed no
2265/// compile-time link back to the shared OTP-canonical default — a
2266/// future rebrand of the default (a tightening to Elixir's
2267/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
2268/// the operator pins through a future
2269/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
2270/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2271/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
2272/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
2273/// per-child-cohort roadmap lands) would have had to be threaded
2274/// through both open-coded copies in lockstep or the wire-format
2275/// author-omitted arm and the view-construction author-omitted arm
2276/// would silently disagree on which restart-budget an omitted
2277/// `:max-restarts` resolves to (an author writing `:supervisor
2278/// (:max-restarts ())` would round-trip through serde with the new
2279/// default while `supervisor_view` silently continued to compose the
2280/// stale `5`, or vice versa), a two-consumer split at the composition
2281/// boundary far from the source `caixa.lisp` with no field naming the
2282/// default-drift root cause. Lifting the resolution rule to a typed
2283/// `pub const` on the substrate primitive means every downstream
2284/// consumer of the per-Supervisor default-restart-budget-count surface
2285/// reaches for exactly one substrate-primitive `u32` — the resolver's
2286/// accepted value migrates as a unit on any future axis change.
2287///
2288/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2289/// worker-supervisor default (the closest canonical OTP-shape
2290/// production reference the substrate carries, matching the sibling
2291/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
2292/// this constant with on the paired sliding-window axis). Two orders of
2293/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
2294/// (the upper bracket on the same axis, sibling of this lower default;
2295/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
2296/// axis and now share one accessor discipline on the substrate) and
2297/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
2298/// restart floor — the "one restart, then escalate" default is
2299/// deliberately loose enough to absorb a short burst of transient
2300/// child failures without escalating past the supervisor's parent
2301/// while remaining tight enough to trip the `MaxIntensity / Period`
2302/// ratio's escalation on a genuinely-stuck child within the sibling
2303/// `60s` sliding window.
2304///
2305/// Lifted as a typed `pub const` so the bound has exactly one source
2306/// of truth — the serde-side wire-format author-omitted arm at
2307/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
2308/// struct-literal default field, and the caixa-core
2309/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
2310/// arm all read from one place. Same shape every other typed default
2311/// in this crate carries (the sibling
2312/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
2313/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
2314/// sibling `:restart-window` axis, and the peer
2315/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2316/// per-renderer defaults on the caixa-flux / caixa-helm rendering
2317/// axes).
2318pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
2319
2320/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
2321/// validated [`SupervisorSpec::max_restarts`] past
2322/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
2323///
2324/// The typed field is `u32` (the zero-floor arm
2325/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
2326/// so a programmatic struct literal
2327/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
2328/// author-surface form (`:max-restarts 4294967295` or any
2329/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
2330/// cleanly through serde — a structurally unbounded `u32` ceiling. The
2331/// runtime substrate consuming the value (Erlang/OTP's
2332/// `MaxIntensity / Period` ratio, the future wasm-operator's
2333/// per-supervisor restart-intensity counter, the M4
2334/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
2335/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
2336/// escalation threshold is structurally so high that no realistic
2337/// restarts-per-`:restart-window` traffic shape can reach it, the
2338/// supervisor never escalates to its parent, and a bad child can loop
2339/// inside the window indefinitely with the parent supervisor structurally
2340/// never receiving the "this subtree has exceeded its restart budget"
2341/// signal the typed slot is meant to express — the canonical
2342/// "supervisor intensity declared, no escalation" footgun, exactly the
2343/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
2344/// on the `:politicas :circuit-breaker :max-failures` axis (both are
2345/// "trip the next-higher protection layer after N events in a rolling
2346/// window" counters with identical degenerate-at-the-high-end shape).
2347///
2348/// The `1000` ceiling matches the sibling
2349/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
2350/// peer — same "events-per-window trip threshold" semantics, same `u32`
2351/// type, same no-op-at-the-high-end failure mode) so the M4
2352/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
2353/// and the future wasm-operator's per-supervisor restart-intensity
2354/// counter reach for either field knowing the value is in `1..=1000`
2355/// without re-validating at the reconciler layer. The cap sits two
2356/// orders of magnitude above every documented Erlang/OTP production
2357/// playbook recommendation (Learn You Some Erlang's
2358/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
2359/// `max_restarts: 3` default, OTP's `supervisor` callback module
2360/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
2361/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
2362/// default) and below the clearly-pathological "effectively no
2363/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
2364/// author can plausibly want at hyperscale (a long-running supervisor
2365/// over a very-flaky pool tolerating thousands of transient restarts
2366/// before escalating), but a hard wall above which the typed policy is
2367/// structurally a no-op carried verbatim on every emitted child-restart
2368/// reconciliation contract.
2369///
2370/// Lifted as a typed `pub const` so the bound has exactly one source of
2371/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2372/// materializer's admission webhook and the wasm-operator-side
2373/// per-supervisor restart-intensity reconciler read from one place. Same
2374/// shape every other typed upper bound in this crate carries
2375/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2376/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2377/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2378/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2379/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2380/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2381pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
2382
2383/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
2384/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
2385/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2386/// (inclusive on both ends, integer-millisecond magnitudes by the
2387/// canonical-form gate immediately preceding).
2388///
2389/// The typed field is `Option<Duration>` (the zero-floor arm
2390/// [`SupervisorError::RestartWindowZero`] already rejects
2391/// `Some(Duration::ZERO)`, and the canonical-form arm
2392/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
2393/// sub-millisecond residue), so a programmatic struct literal
2394/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
2395/// .. }` — 24h) and the equivalent author-surface form
2396/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
2397/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
2398/// cleanly through serde — a structurally unbounded `Duration` ceiling.
2399/// A `:restart-window` value far above the documented Erlang/OTP
2400/// `MaxIntensity / Period` production-playbook band (Learn You Some
2401/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
2402/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
2403/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
2404/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
2405/// degenerates the supervisor's restart-intensity counter into a
2406/// lifetime counter: the rolling failure-counting window is structurally
2407/// so long that transient restarts are never forgotten, so the
2408/// `MaxIntensity / Period` ratio degenerates from "trip the parent
2409/// supervisor when the child has exceeded its restart budget *within
2410/// the recent window*" to "trip the parent when the child has exceeded
2411/// its restart budget *over its lifetime*" — every transient restart
2412/// counts against the budget forever, the supervisor's reset semantic
2413/// never reaches the child, and the typed `:restart-window` slot
2414/// becomes a no-op rolling window carried on every emitted hierarchical
2415/// reconciliation contract. The canonical
2416/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
2417/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
2418/// `:politicas :circuit-breaker :window` axis with identical shape (both
2419/// are "rolling failure-counting window with a per-`Period` reset" Duration
2420/// axes whose lifetime-counter degenerate at the high end is the same
2421/// "the reset semantic never fires" CSE invariant violation).
2422///
2423/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
2424/// the shared duration codec emits (`"<n>h"` for any integer-hour
2425/// magnitude) — every value in the canonical authoring form's
2426/// `<integer><unit>` grammar at or below this cap renders to a clean
2427/// canonical string — and matches the three sibling typed-`Duration`
2428/// caps already lifted to this surface
2429/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2430/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
2431/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
2432/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
2433/// per-supervisor `:supervisor :restart-window` — now share a single
2434/// uniform top edge at the codec's largest emitted unit so the next
2435/// typed-slot wiring (the future wasm-operator's per-supervisor
2436/// `MaxIntensity / Period` reconciler, the M4
2437/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2438/// webhook, the `caixa-operator`'s hierarchical reconciliation
2439/// scheduler) reaches for any of the four knowing the value is in
2440/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
2441/// two orders of magnitude above every documented Erlang/OTP / Elixir /
2442/// Riak Core / RabbitMQ production-playbook recommendation band
2443/// (`5s..=300s`) and below the clearly-pathological "rolling window
2444/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
2445/// a value the author can plausibly want for a very-low-traffic
2446/// long-tail failure-restart window over a hyperscale-flaky child pool,
2447/// but a hard wall above which the rolling-window contract is
2448/// structurally a lifetime-counter contract.
2449///
2450/// Lifted as a typed `pub const` so the bound has exactly one source
2451/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2452/// materializer's admission webhook, the wasm-operator-side
2453/// per-supervisor `MaxIntensity / Period` reconciler, and the
2454/// `caixa-operator`'s hierarchical reconciliation scheduler all read
2455/// from one place. Same shape every other typed upper bound in this
2456/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
2457/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2458/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2459/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2460/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2461/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2462/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
2463/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2464/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2465pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
2466
2467/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
2468/// default for the `:supervisor :restart-window` axis — the canonical
2469/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
2470/// worker-supervisor default, extracted as a typed `pub const` so every
2471/// substrate-side consumer that resolves "what
2472/// [`SupervisorSpec::restart_window`] value does an author-omitted
2473/// `:restart-window` slot degrade onto?" reaches for exactly one
2474/// substrate-primitive [`Duration`].
2475///
2476/// The `:restart-window` default axis has one production consumer on the
2477/// substrate side today: the [`Default for SupervisorSpec`] impl's
2478/// struct-literal `restart_window` field, which prior to this lift folded
2479/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
2480/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
2481/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
2482/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
2483/// *not* fall back to this default on the sibling `:restart-window` axis
2484/// — an author-omitted `:supervisor :restart-window` composes to
2485/// `restart_window: None` (the shared codec's soft-swallow shape),
2486/// keeping author-declared intent ("no reset — never escalate on rolling
2487/// window") distinct from the [`Default for SupervisorSpec`] "canonical
2488/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
2489/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
2490/// default was split across two files with no compile-time link between
2491/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
2492/// `MaxIntensity` half at the substrate primitive while the `Period`
2493/// half rode as an open-coded literal at the composition site, so a
2494/// future coherent rebrand of the paired canonical (a tightening to
2495/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
2496/// per-cluster overlay the operator pins through a future
2497/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
2498/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2499/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
2500/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
2501/// roadmap lands) would have had to migrate the `MaxIntensity` half
2502/// through the lifted constant and the `Period` half through a raw
2503/// literal in lockstep or the two halves of the same OTP-canonical
2504/// default would silently drift out of pairing. Lifting the resolution
2505/// rule to a typed `pub const` on the substrate primitive means the
2506/// paired OTP-canonical default migrates as one unit on any future
2507/// axis change.
2508///
2509/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2510/// worker-supervisor default (the closest canonical OTP-shape
2511/// production reference the substrate carries, matching the paired
2512/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
2513/// constant is the `Period` denominator of on the same
2514/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
2515/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
2516/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
2517/// this lower default; both are typed [`Duration`] const bounds on the
2518/// `:supervisor :restart-window` axis and now share one accessor
2519/// discipline on the substrate) and above the OTP-`supervisor`
2520/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
2521/// rolling window" default is deliberately loose enough to absorb a
2522/// short burst of transient child failures without escalating past the
2523/// supervisor's parent while remaining tight enough for the paired
2524/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
2525/// stuck child within a human-scale observation window.
2526///
2527/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2528/// exactly one source of truth on each half — the sibling
2529/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
2530/// `Period` `60s` half now share the same substrate-primitive lift
2531/// discipline. Same shape every other typed default in this crate
2532/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
2533/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
2534/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
2535/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
2536/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
2537/// caixa-flux / caixa-helm rendering axes).
2538pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
2539
2540/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
2541/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
2542/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
2543/// worker-supervisor default, extracted as a typed `pub const` so every
2544/// substrate-side consumer that resolves "what
2545/// [`SupervisorSpec::estrategia`] variant does an author-omitted
2546/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
2547/// primitive [`RestartStrategy`].
2548///
2549/// The `:estrategia` default axis has three production consumers on the
2550/// substrate side today: the [`Default for RestartStrategy`] impl's
2551/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
2552/// `estrategia` field, and the
2553/// [`crate::manifest::Caixa::supervisor_view`] fold's
2554/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
2555/// collapse arm — three entry points onto the same OTP-canonical
2556/// `one_for_one` value that prior to this lift folded onto a raw
2557/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
2558/// implicit `RestartStrategy::default()` routes at the sibling consumers,
2559/// with no compile-time link back to the paired
2560/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
2561/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
2562/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
2563/// triple was split across three altitudes with no compile-time link
2564/// between the halves: the `MaxIntensity` half rode through the lifted
2565/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
2566/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2567/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
2568/// discriminator at the [`Default for RestartStrategy`] impl, so a future
2569/// coherent rebrand of the triple (Elixir's `{:one_for_one,
2570/// max_restarts: 3, max_seconds: 5}` — same strategy, different
2571/// intensity/period; an OTP `rest_for_one` widening once the substrate
2572/// discovers startup-order-coupled child cohorts as the more common
2573/// worker-supervisor default; a per-cluster overlay the operator pins
2574/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
2575/// §III.2 supervision-canary roadmap acknowledges) would have had to
2576/// migrate the `MaxIntensity` + `Period` halves through the lifted
2577/// constants and the `one_for_one` half through an open-coded arm in
2578/// lockstep or the three halves of the same OTP-canonical default would
2579/// silently drift out of pairing. Lifting the resolution rule to a typed
2580/// `pub const` on the substrate primitive means the paired OTP-canonical
2581/// worker-supervisor default migrates as one unit on any future axis
2582/// change.
2583///
2584/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
2585/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
2586/// closest canonical OTP-shape production reference the substrate
2587/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
2588/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2589/// `60s` `Period` half). The `one_for_one` strategy — restart only the
2590/// failed child, leaving siblings untouched — is the default for tree-of-
2591/// independent-workers use cases the substrate's [`RestartStrategy`]
2592/// discriminator's own docstring already carries as the default arm; it
2593/// composes with the `{5, 60}` restart-intensity ratio to name the same
2594/// substrate-canonical "canonical worker-supervisor" shape the paired
2595/// halves close on their respective axes.
2596///
2597/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2598/// exactly one source of truth on each of its three halves — the sibling
2599/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
2600/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
2601/// this `one_for_one` strategy half now share the same substrate-
2602/// primitive lift discipline. Same shape every other typed default in
2603/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
2604/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
2605/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
2606/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
2607/// upper caps on the paired sibling axes, and the peer
2608/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2609/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
2610pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
2611
2612/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
2613/// default for the `:children :restart` axis — the OTP `permanent`
2614/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
2615/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
2616/// `pub const` so every substrate-side consumer that resolves "what
2617/// [`ChildSpec::restart`] variant does an author-omitted `:children
2618/// :restart` slot degrade onto?" reaches for exactly one substrate-
2619/// primitive [`RestartPolicy`].
2620///
2621/// Completes the OTP-shape supervisor-tree default set at the substrate
2622/// primitive. The per-`:supervisor` axis already carries all three of its
2623/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2624/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
2625/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2626/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
2627/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
2628/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
2629/// the M2 `:supervisor` slot family. The split mattered because the two
2630/// axes resolve *together* on every author-omitted supervisor: a
2631/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
2632/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
2633/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
2634/// `permanent` through an open-coded enum arm, so a future coherent
2635/// rebrand of the OTP-shape default set (an Elixir-shaped
2636/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
2637/// per-cluster overlay the operator pins through the MESH-COMPOSITION
2638/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
2639/// once the substrate discovers clean-completion-aware children as the
2640/// more common child shape) would have had to migrate three halves
2641/// through typed constants and the fourth through a raw enum arm in
2642/// lockstep or the supervisor-level and child-level defaults would
2643/// silently drift apart.
2644///
2645/// The `:children :restart` default axis has two production consumers on
2646/// the substrate side today: the [`Default for RestartPolicy`] impl's
2647/// return arm, and the serde-side `#[serde(default)]` on
2648/// [`ChildSpec::restart`] that resolves an author-omitted `:children
2649/// :restart` slot through that same impl. Both now key off this one
2650/// substrate primitive, so the future wasm-operator's per-child post-exit
2651/// restart-decision branch, the future M4
2652/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2653/// admission webhook, and the `caixa-operator`'s hierarchical
2654/// reconciliation scheduler's per-child fan-out all reach for one typed
2655/// identifier when they resolve an omitted per-child restart posture.
2656///
2657/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
2658/// worker-child restart type — always restart the child regardless of how
2659/// it died, the canonical posture for long-running services that must
2660/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2661/// `one_for_one` tree-of-independent-workers strategy this constant pairs
2662/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
2663/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
2664/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
2665/// [`RestartPolicy::Temporary`] — never restart) express deliberate
2666/// one-shot / clean-completion-aware postures an author declares
2667/// explicitly, never a posture an omitted slot should silently assume.
2668pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
2669
2670/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
2671/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
2672/// `pub const fn` constructor rather than a struct-literal cascade over
2673/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
2674/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2675/// lifted consts — one source of truth for the Erlang/OTP-canonical
2676/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
2677/// paths every downstream consumer already reaches through (the
2678/// hand-authored-until-now [`Default::default`] the
2679/// `..SupervisorSpec::default()` struct-update-syntax on every
2680/// one-axis-under-test fixture in this crate's test module rests on,
2681/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
2682/// every `const`-context consumer reaches through).
2683///
2684/// Extends the [`Default`]-through-const-ctor fold discipline the
2685/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
2686/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
2687/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
2688/// and [`crate::BehaviorSpec`]
2689/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
2690/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
2691/// typed-slot spec family — extended here onto the M2 supervisor-slot
2692/// [`SupervisorSpec`] whose canonical baseline is not "everything
2693/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
2694/// supervisor triple. The `empty()` peer's naming did not fit
2695/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
2696/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
2697/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
2698/// the sibling `Option`-only slots fold to), so this peer is named
2699/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
2700/// existing per-arm pin tests
2701/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
2702/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
2703/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2704/// already reach for. Pinned load-bearing by
2705/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
2706/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
2707/// [`PartialEq`], sharpening the sibling
2708/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
2709/// pins from a per-field lift into a whole-struct one-source-of-truth
2710/// pin — the derived-until-now [`Default::default`] and the
2711/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
2712/// construction, not by coincidence).
2713impl Default for SupervisorSpec {
2714    #[inline]
2715    fn default() -> Self {
2716        Self::otp_canonical()
2717    }
2718}
2719
2720impl SupervisorSpec {
2721    /// `const`-context peer of the [`Default for SupervisorSpec`]
2722    /// impl (which routes through this constructor) — returns the
2723    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
2724    /// baseline this crate reaches for in every fixture-builder
2725    /// `..SupervisorSpec::default()` struct-update expression and
2726    /// every downstream `SupervisorSpec::default()` seed.
2727    ///
2728    /// Each field routes through the same substrate-canonical
2729    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
2730    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
2731    /// per-arm pin tests
2732    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
2733    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
2734    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2735    /// already assert, so a future coherent rebrand of the OTP-canonical
2736    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
2737    /// cluster overlay via a future `:restart-window-overrides` slot, a
2738    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
2739    /// absorption roadmap acknowledges) migrates through three typed
2740    /// constants in lockstep, and the paired [`Default`] impl inherits
2741    /// every future extension by construction.
2742    ///
2743    /// `pub const fn` rather than the derived-style `Default::default`
2744    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
2745    /// [`Default::default`] is not `const` on stable Rust, and
2746    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
2747    /// every consumer through a [`Clone::clone`]. The `pub const fn`
2748    /// discipline lets `const`-context callers construct the OTP-
2749    /// canonical baseline at compile time without runtime dispatch on
2750    /// the derived [`Default::default`], the same posture the sibling
2751    /// [`crate::LimitsSpec::empty`] (9739971) /
2752    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
2753    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
2754    /// spec `pub const fn` constructors carry on the sibling
2755    /// "everything `None`" baseline axis.
2756    ///
2757    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
2758    /// of the derived-style [`Default`]" family — sibling of the
2759    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
2760    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
2761    /// baseline" trio, extended here onto the M2 supervisor-slot
2762    /// [`SupervisorSpec`] whose canonical baseline is not "everything
2763    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
2764    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
2765    /// than `empty()` to name the actual invariant the return value
2766    /// pins — the same phrasing already used in the per-arm pin tests
2767    /// on this file. Pinned load-bearing by
2768    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
2769    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
2770    #[must_use]
2771    pub const fn otp_canonical() -> Self {
2772        Self {
2773            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
2774            max_restarts: default_max_restarts(),
2775            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2776            children: Vec::new(),
2777        }
2778    }
2779
2780    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
2781    /// sibling-restart-strategy scalar accessor every consumer that
2782    /// dispatches on the supervisor's per-sibling restart-decision shape
2783    /// keys off — returns the author-declared `:supervisor :estrategia`
2784    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
2785    /// the typed slot's own [`RestartStrategy`] storage.
2786    ///
2787    /// The `:supervisor :estrategia` slot carries the closed-set
2788    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
2789    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
2790    /// [`RestartStrategy::OneForAll`] — restart every child on any child
2791    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
2792    /// [`RestartStrategy::RestForOne`] — restart the failed child and
2793    /// every child started after it, the Erlang/OTP `rest_for_one`
2794    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
2795    /// dynamic children of the same shape, the Erlang/OTP
2796    /// `simple_one_for_one` per-session default) that every downstream
2797    /// consumer of the Supervisor's per-sibling restart-decision fan-out
2798    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
2799    /// paired coherently with the sibling `:children` axis
2800    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
2801    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
2802    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
2803    /// downstream consumer that reads the strategy keys off this scalar
2804    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2805    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
2806    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
2807    /// `estrategia:` field, the future `feira app graph` per-Supervisor
2808    /// strategy print line, the future wasm-operator's per-supervisor
2809    /// sibling-restart-strategy branch, the future M4
2810    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
2811    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
2812    /// reconciliation scheduler's per-strategy fan-out).
2813    ///
2814    /// Prior to this lift the `.estrategia` field was accessed inline at
2815    /// two production sites in `caixa-core/src/supervisor.rs` — the
2816    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2817    /// `match self.estrategia { … }` partition dispatch, and the
2818    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
2819    /// carrier at `estrategia: self.estrategia` — two open-coded
2820    /// field-accesses that expressed no compile-time link back to the
2821    /// typed slot. A future extension of the `:supervisor :estrategia`
2822    /// axis to a richer author surface (a per-cluster strategy override
2823    /// the operator pins through a future `:supervisor :estrategia-overrides`
2824    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2825    /// acknowledges, a per-tenant strategy-alias table the M4 CR
2826    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
2827    /// derivation the future adaptive-supervision engine computes from
2828    /// child-failure-history topology, a per-child-cohort strategy split
2829    /// the future `RestForCohort` extension acknowledged by the
2830    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
2831    /// would have had to be threaded through every open-coded copy in
2832    /// lockstep — one consumer reading the raw variant while a peer read
2833    /// the operator-resolved variant would silently split the
2834    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
2835    /// the actual partition-dispatch input the empty-children refusal
2836    /// arm reached under, a two-consumer split at the validator far from
2837    /// the source `caixa.lisp` with no field naming the strategy-drift
2838    /// root cause. Lifting the resolution rule to a typed method on the
2839    /// substrate primitive means every downstream consumer of the
2840    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
2841    /// reaches for exactly one typed dispatch — the resolver's accept-set
2842    /// migrates as a unit on any future axis addition.
2843    ///
2844    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
2845    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
2846    /// per-`:placement` distribution-strategy axis — same "one typed
2847    /// dispatch on the substrate primitive, thin projections at each
2848    /// consumer" discipline extended onto the M2 supervisor-slot
2849    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
2850    /// scalar axis. The two typed axes (`Placement::estrategia` on the
2851    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
2852    /// Supervisor side) now share one accessor discipline for the shared
2853    /// substrate concept "a `Copy`-projected closed-set enum-arm
2854    /// discriminator that partitions the downstream renderer's per-arm
2855    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
2856    /// `SupervisorSpec` type — companion to the sibling per-`:children`
2857    /// [`crate::ChildSpec::nome`] (57c61d0) /
2858    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2859    /// scalar accessors on the sibling per-`:children` `String`-carry
2860    /// axes. Named `estrategia()` to match the storage field's name and
2861    /// the peer [`crate::Placement::estrategia`] method-name discipline
2862    /// verbatim; the accessor's identity name maps onto the canonical
2863    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
2864    /// docstring already carries.
2865    ///
2866    /// Declared `pub const fn` to close the M2 supervisor-slot
2867    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
2868    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
2869    /// (converted in this commit) `Copy`-composite-enum accessor, peer
2870    /// of the sibling M2 per-`:supervisor`
2871    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2872    /// already lifted, and mirror of the peer M3 mesh-slot
2873    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
2874    /// `Copy`-return `pub const fn` scalar accessor whose method-name
2875    /// discipline this accessor was authored to match. Every downstream
2876    /// substrate-side `const`-context consumer of the per-`:supervisor`
2877    /// sibling-restart-strategy scalar (a future module-scope `const
2878    /// _:() = assert!(matches!(sup.estrategia(),
2879    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
2880    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2881    /// admission-webhook `const fn` per-supervisor strategy-arm floor
2882    /// over a typed [`SupervisorSpec`], any future `const fn`
2883    /// supervisor-tree composer over the substrate primitive that fans
2884    /// on the sibling-restart-strategy at compile time) now reaches
2885    /// through the same typed dispatch on the substrate primitive at
2886    /// const-eval time as at runtime. A future non-`Copy`-return
2887    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
2888    /// migration once the substrate grows per-cluster strategy overlays
2889    /// the [`SupervisorSpec`] docstring already anticipates, a
2890    /// per-tenant strategy-alias table the M4 CR materializer resolves
2891    /// per-CR) that would drop the `const` qualifier fails the
2892    /// fail-before-pass-after pin
2893    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
2894    /// caixa-core build time rather than surfacing as a downstream
2895    /// consumer regression.
2896    #[must_use]
2897    pub const fn estrategia(&self) -> RestartStrategy {
2898        self.estrategia
2899    }
2900
2901    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
2902    /// `MaxIntensity` restart-budget scalar accessor every consumer that
2903    /// reads the supervisor's per-`:restart-window` restart-budget count
2904    /// keys off — returns the author-declared `:supervisor :max-restarts`
2905    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
2906    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
2907    /// borrow of `&self` past the call). Non-optional (the `u32` field
2908    /// carries the restart-budget count as a required axis with a
2909    /// [`default_max_restarts`]-supplied default; the zero-floor arm
2910    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
2911    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
2912    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
2913    ///
2914    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
2915    /// `MaxIntensity` restart-budget count that pairs with the sibling
2916    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
2917    /// restart-intensity ratio the supervisor trips its own escalation on
2918    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
2919    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
2920    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
2921    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
2922    /// upper-cap bracket at
2923    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
2924    /// wasm-operator's per-supervisor restart-intensity counter's
2925    /// budget-vs-count comparator, the future M4
2926    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2927    /// webhook, the `caixa-operator`'s hierarchical reconciliation
2928    /// scheduler's per-supervisor escalation-decision branch, every
2929    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
2930    /// offending count verbatim for `feira lint` rendering).
2931    ///
2932    /// Prior to this lift the `.max_restarts` field was accessed inline at
2933    /// one production site in `caixa-core/src/supervisor.rs` — the
2934    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
2935    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
2936    /// that expressed no compile-time link back to the typed slot. A
2937    /// future extension of the `:max-restarts` axis to a richer author
2938    /// surface (a per-cluster restart-budget override the operator pins
2939    /// through a future `:supervisor :max-restarts-overrides` slot the
2940    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
2941    /// a per-tenant restart-budget-alias table the M4 CR materializer
2942    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
2943    /// the future adaptive-supervision engine computes from child-failure-
2944    /// history topology, a promotion of the plain `u32` count to a richer
2945    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
2946    /// budget-partition slot comes into scope) would have had to be
2947    /// threaded through every open-coded copy in lockstep or the validate
2948    /// gate and the future M4 emit path would silently disagree on which
2949    /// restart-budget count a given supervisor resolves to — an author's
2950    /// `:max-restarts 5` would satisfy validate while the emit path
2951    /// silently read a drifted other value (a `:max-restarts 10000`
2952    /// no-op supervisor at the emit boundary would carry the author's
2953    /// declared `5` verbatim in `feira lint` output while the future
2954    /// wasm-operator's restart-intensity counter operated under the
2955    /// drifted count), a two-consumer split at the validator far from the
2956    /// source `caixa.lisp` with no field naming the restart-budget-drift
2957    /// root cause. Lifting the resolution rule to a typed method on the
2958    /// substrate primitive means every downstream consumer of the
2959    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
2960    /// for exactly one typed dispatch — the resolver's accept-set migrates
2961    /// as a unit on any future axis addition.
2962    ///
2963    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
2964    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
2965    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
2966    /// outlier-detection trip-threshold axis — same "one typed dispatch on
2967    /// the substrate primitive, thin projections at each consumer"
2968    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
2969    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
2970    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
2971    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
2972    /// one accessor discipline for the shared substrate concept "a
2973    /// `Copy`-projected required `u32` count that trips the next-higher
2974    /// protection layer after N events in a rolling window" — both are
2975    /// counters with identical degenerate-at-the-high-end shape and share
2976    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
2977    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
2978    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
2979    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
2980    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
2981    /// the storage field's name verbatim and the peer
2982    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
2983    /// accessor's identity maps onto the canonical OTP-shape supervision
2984    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
2985    /// already carries.
2986    #[must_use]
2987    pub const fn max_restarts(&self) -> u32 {
2988        self.max_restarts
2989    }
2990
2991    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
2992    /// `Period` sliding-window scalar accessor every consumer of the
2993    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
2994    /// keys off — returns the author-declared `:supervisor :restart-window`
2995    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
2996    /// the typed slot's own `Option<Duration>` storage (`Duration` is
2997    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
2998    /// value; no borrow of `&self` past the call). `None` when the slot is
2999    /// absent (the canonical "never reset — every restart across the
3000    /// supervisor's lifetime counts against the sibling `:max-restarts`
3001    /// budget" sentinel the field's own docstring names and the peer
3002    /// `validate_accepts_none_restart_window` pin locks in on the
3003    /// [`SupervisorSpec::validate`] entry-side).
3004    ///
3005    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
3006    /// `Period` sliding-observation-interval that pairs with the sibling
3007    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
3008    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
3009    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
3010    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
3011    /// default). The typed slot's `Option<Duration>` accept-set —
3012    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
3013    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
3014    /// `Period > 0`; a zero period either trips on the first failure or
3015    /// never trips depending on operator interpretation, neither of which
3016    /// is the author's intent — omit the slot to express "no reset";
3017    /// carry a positive duration to express the sliding window),
3018    /// integer-millisecond canonical form enforced through
3019    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
3020    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
3021    /// future wasm-operator's per-supervisor restart-intensity counter
3022    /// quantizes at milliseconds), upper-bounded by
3023    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
3024    /// supervisor rolling window any operationally-reachable supervisor
3025    /// can honor without spanning multiple scheduler epochs the
3026    /// hierarchical-reconciliation scheduler treats as independent) —
3027    /// maps onto the future wasm-operator (M3) per-supervisor
3028    /// restart-intensity counter's rolling-observation-interval, the
3029    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3030    /// per-`spec.restartWindow` admission webhook, and the sibling
3031    /// `duration_codec`-serialized wire scalar every downstream consumer
3032    /// of the supervisor's per-`:supervisor` restart-intensity denominator
3033    /// keys off.
3034    ///
3035    /// Prior to this lift the `.restart_window` field was accessed inline
3036    /// at one production site in `caixa-core/src/supervisor.rs` — the
3037    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
3038    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
3039    /// open-coded field-access that expressed no compile-time link back to
3040    /// the typed slot. A future extension of the `:restart-window` axis to
3041    /// a richer author surface (a per-cluster restart-window override the
3042    /// operator pins through a future `:supervisor :restart-window-overrides`
3043    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3044    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
3045    /// materializer resolves per-CR, a per-supervisor dynamic
3046    /// restart-window derivation the future adaptive-supervision engine
3047    /// computes from child-failure-history topology, a promotion of the
3048    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
3049    /// pair once Erlang/OTP's per-child-cohort observation-interval-
3050    /// partition slot comes into scope) would have had to be threaded
3051    /// through every open-coded copy in lockstep or the validate gate and
3052    /// the future M4 emit path would silently disagree on which
3053    /// restart-window a given supervisor resolves to — an author's
3054    /// `:restart-window "60s"` would satisfy validate while the emit path
3055    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
3056    /// authored slot at the emit boundary would carry the author's
3057    /// declared window verbatim in `feira lint` output while the future
3058    /// wasm-operator's restart-intensity counter operated under a
3059    /// drifted window, or vice versa: an author's `:restart-window ()`
3060    /// would carry the "never reset" sentinel through validate while the
3061    /// emit path silently substituted a default sliding window), a
3062    /// two-consumer split at the validator far from the source
3063    /// `caixa.lisp` with no field naming the restart-window-drift root
3064    /// cause. Lifting the resolution rule to a typed method on the
3065    /// substrate primitive means every downstream consumer of the
3066    /// Supervisor's per-`:supervisor` restart-intensity-denominator
3067    /// surface reaches for exactly one typed dispatch — the resolver's
3068    /// accept-set migrates as a unit on any future axis addition.
3069    ///
3070    /// Third `Copy`-return accessor on the M2 supervisor-slot
3071    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
3072    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
3073    /// payload rather than a `Copy`-scalar, and the per-`:children`
3074    /// [`crate::ChildSpec::nome`] (57c61d0) /
3075    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3076    /// scalar accessors already close the per-element `String`-carry
3077    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
3078    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
3079    /// per-outermost-call wall-clock-deadline axis and the peer M3
3080    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
3081    /// accessor on the `:politicas` slot's per-call-deadline axis — all
3082    /// three share the shared substrate concept "a `Copy`-projected
3083    /// optional `Duration` that carries a positive integer-millisecond
3084    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
3085    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
3086    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
3087    /// bracket-helper the three axes each route through. Named
3088    /// `restart_window()` to match the storage field's name verbatim and
3089    /// the peer [`crate::LimitsSpec::wall_clock`] /
3090    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
3091    /// accessor's identity maps onto the canonical OTP-shape supervision
3092    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
3093    /// already carries.
3094    #[must_use]
3095    pub const fn restart_window(&self) -> Option<Duration> {
3096        self.restart_window
3097    }
3098
3099    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
3100    /// static-child-list slice accessor every consumer that walks the
3101    /// supervisor's declared child set keys off — returns the author-
3102    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
3103    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
3104    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
3105    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
3106    /// through). Non-optional: an empty slice is the load-bearing
3107    /// "author declared `:children ()`" sentinel every consumer of the
3108    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
3109    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
3110    /// three strategies require a non-empty slice — the paired
3111    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
3112    /// [`SupervisorError::NoChildren`] refusal cascade pins the
3113    /// partition on both arms).
3114    ///
3115    /// The `:supervisor :children` slot carries the OTP-shaped static
3116    /// child list the supervisor materializes one ComputeUnit per
3117    /// entry from — the Erlang/OTP `supervisor:init/1`'s
3118    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
3119    /// through the tatara-lisp `:children` author surface onto a typed
3120    /// `Vec<ChildSpec>` whose per-element `(nome(),
3121    /// versao_requirement(), restart)` triple the per-child
3122    /// [`SupervisorSpec::validate`] loop already gates through the
3123    /// lifted [`ChildSpec::nome`] (57c61d0) /
3124    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
3125    /// Every downstream consumer that fans on the static child list
3126    /// keys off this slice (the [`SupervisorSpec::validate`]
3127    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
3128    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
3129    /// per-child DNS-1123 / semver-requirement / duplicate-detection
3130    /// fan-out loop, every future wasm-operator (M3) per-supervisor
3131    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
3132    /// materialization loop, the future M4
3133    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3134    /// admission-webhook fan-out, the future `feira app graph`
3135    /// per-supervisor tree-print traversal).
3136    ///
3137    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
3138    /// inline at three production sites in `caixa-core/src/supervisor.rs`
3139    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
3140    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
3141    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
3142    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
3143    /// validate loop's `for child in &self.children` traversal head —
3144    /// three open-coded field-accesses that expressed no compile-time
3145    /// link back to the typed slot. A future extension of the
3146    /// `:supervisor :children` axis to a richer author surface (a
3147    /// per-cluster child-set overlay the operator pins through a future
3148    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
3149    /// supervision-canary roadmap acknowledges, a per-tenant
3150    /// child-set-alias table the M4 CR materializer resolves per-CR,
3151    /// a per-supervisor dynamic-child derivation the future adaptive-
3152    /// supervision engine computes from child-failure-history topology,
3153    /// a promotion of the plain `Vec<ChildSpec>` to a richer
3154    /// `{static, dynamic}` partition once Erlang/OTP's
3155    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
3156    /// would have had to be threaded through all three open-coded copies
3157    /// in lockstep or one consumer would silently disagree with the
3158    /// peers on which child-set a given supervisor resolves to — the
3159    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
3160    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
3161    /// would silently split the partition-dispatch's two-arm coherence
3162    /// (a supervisor that satisfies neither arm's precondition, or that
3163    /// satisfies both, at the cost of the paired
3164    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
3165    /// silently drifting from the per-child validate loop's actual
3166    /// traversal input), a three-consumer split at the validator far
3167    /// from the source `caixa.lisp` with no field naming the
3168    /// child-set-drift root cause. Lifting the resolution rule to a
3169    /// typed method on the substrate primitive means every downstream
3170    /// consumer of the Supervisor's per-`:supervisor` static-child-list
3171    /// surface reaches for exactly one typed dispatch — the resolver's
3172    /// accept-set migrates as a unit on any future axis addition.
3173    ///
3174    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
3175    /// — the seed for the same "one typed dispatch on the substrate
3176    /// primitive, thin projections at each consumer" discipline the
3177    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
3178    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
3179    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
3180    /// onto the first `Vec`-carry axis on the substrate. The four peer
3181    /// `Vec`-carry axes still unlifted at the time of this seed —
3182    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
3183    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
3184    /// (`Vec<Membro>` per-Aplicacao member list),
3185    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
3186    /// per-Aplicacao WIT-typed edge list),
3187    /// [`crate::UpgradeFromEntry::instructions`]
3188    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
3189    /// — inherit this accessor's discipline as future compounding runs
3190    /// migrate their consumers onto the shared slice-return shape.
3191    /// Fourth (and final) accessor on the M2 supervisor-slot
3192    /// `SupervisorSpec` type, sibling to the three `Copy`-return
3193    /// [`SupervisorSpec::estrategia`] (eafb619) /
3194    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
3195    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
3196    /// the last unlifted per-`:supervisor` field axis (the
3197    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
3198    /// per-`:supervisor` reader now routes through a typed dispatch on
3199    /// the substrate primitive. Named `children()` to match the storage
3200    /// field's name verbatim and the tatara-lisp author-surface term
3201    /// (`:children`) the field's own docstring already carries; the
3202    /// accessor's identity maps onto the canonical OTP-shape
3203    /// supervision vocabulary the [`SupervisorSpec::children`] field's
3204    /// docstring already reaches for ("Static children ..."). Returns
3205    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
3206    /// consumer of the child list treats it as a read-only sequence —
3207    /// the slice-view is the narrowest borrow that supports every
3208    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
3209    /// index, `.len()`) without leaking the backing `Vec`'s
3210    /// grow/push/reserve surface that no consumer of the typed view
3211    /// reaches for (the storage-side `Vec` remains reachable through
3212    /// the `pub children` field for the mutation-carrying
3213    /// `Caixa::supervisor_view` fold-in path in
3214    /// `manifest.rs:supervisor_view`).
3215    #[must_use]
3216    pub const fn children(&self) -> &[ChildSpec] {
3217        self.children.as_slice()
3218    }
3219
3220    /// Validate the supervisor's typed shape — strategy ↔ children
3221    /// invariants, max_restarts > 0, restart_window > 0 when set,
3222    /// per-child non-empty + duplicate-free names.
3223    ///
3224    /// Mirrors the value-shape discipline applied to every other
3225    /// typed slot:
3226    ///
3227    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
3228    ///     same "0 means the opposite of what you think" footgun
3229    ///     closed for `:politicas :timeout` (Envoy interprets a zero
3230    ///     timeout as `infinite`), `:politicas :circuit-breaker
3231    ///     :window`, and `:limits :wall-clock`. The
3232    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
3233    ///     `supervisor` requires `Period > 0`; a zero period either
3234    ///     trips on the first failure or never trips depending on
3235    ///     operator interpretation, neither of which is the
3236    ///     author's intent. Omit `:restart-window` to express "no
3237    ///     reset"; carry a positive duration to express the window.
3238    ///   - duplicate `:children` `:caixa` names are the same
3239    ///     graph-node-set / multiset distinction closed for
3240    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
3241    ///     and `:entrada :paths` (eb3456d). Two children with the
3242    ///     same `:caixa` materialize as two ComputeUnits with the
3243    ///     same name in the cluster's HelmRelease values, one
3244    ///     silently overwriting the other. Erlang/OTP's
3245    ///     `child_spec.id` is required-unique per supervisor;
3246    ///     pleme-io enforces the same set-not-multiset shape on
3247    ///     `:caixa` (the load-bearing identity in our renderer).
3248    pub fn validate(&self) -> Result<(), SupervisorError> {
3249        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
3250        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3251        // error carrier's `estrategia:` field through the lifted
3252        // [`SupervisorSpec::estrategia`] accessor rather than the raw
3253        // `self.estrategia` field access — the two production consumers
3254        // of the per-`:supervisor` sibling-restart-strategy scalar now
3255        // key off exactly one typed dispatch on the substrate primitive,
3256        // so any future rebrand on the axis (a per-cluster strategy
3257        // override the operator pins through a future `:supervisor
3258        // :estrategia-overrides` slot, a per-tenant strategy-alias table
3259        // the M4 CR materializer resolves per-CR) migrates as a single
3260        // caixa-core edit rather than a coordinated rewrite of the two
3261        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
3262        // (921fe1b) four-consumer migration on the per-`:placement`
3263        // distribution-strategy axis.
3264        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
3265        // dispatch's paired `.is_empty()` cross-slot refusal probes
3266        // (the `SimpleOneForOne`-arm
3267        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
3268        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3269        // refusal) through the lifted [`SupervisorSpec::children`]
3270        // slice-return accessor rather than the raw `self.children`
3271        // field access — the two paired production consumers of the
3272        // per-`:supervisor` static-child-list scalar-shape now key off
3273        // exactly one typed dispatch on the substrate primitive, so any
3274        // future rebrand on the axis (a per-cluster child-set overlay
3275        // the operator pins through a future `:supervisor
3276        // :children-overrides` slot, a per-tenant child-set-alias table
3277        // the M4 CR materializer resolves per-CR) migrates as a single
3278        // caixa-core edit rather than a coordinated rewrite of the
3279        // paired arms — first slice-return migration on any typed slot,
3280        // seed for the peer per-`:placement :clusters`,
3281        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
3282        // :instructions` `Vec`-carry axes.
3283        match self.estrategia() {
3284            RestartStrategy::SimpleOneForOne => {
3285                // SimpleOneForOne: children added at runtime. Static
3286                // list must be empty (one shape declared elsewhere).
3287                if !self.children().is_empty() {
3288                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
3289                }
3290            }
3291            _ => {
3292                if self.children().is_empty() {
3293                    return Err(SupervisorError::no_children(self.estrategia()));
3294                }
3295            }
3296        }
3297        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
3298        // axis. See [`crate::render::require_positive_bounded_u32`] for
3299        // the ordering discipline (zero-floor arm strictly precedes cap
3300        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
3301        // diagnostic with its counter-axis remediation directly named,
3302        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
3303        // cap-arm miss). Until this bracket landed the top edge ran all
3304        // the way to `u32::MAX` and a struct-literal
3305        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
3306        // equivalent author-surface `:max-restarts 100000` /
3307        // `:max-restarts 4294967295` typo landing in the slot) silently
3308        // passed validate. The runtime substrate consuming the value
3309        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
3310        // wasm-operator's per-supervisor restart-intensity counter, the
3311        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3312        // admission webhook) then turned a typed `:max-restarts`
3313        // policy into a no-op supervisor: the escalation threshold is
3314        // structurally so high that no realistic
3315        // restarts-per-`:restart-window` traffic shape can reach it,
3316        // the supervisor never escalates to its parent, and a bad
3317        // child can loop inside the window indefinitely with the
3318        // parent supervisor structurally never receiving the "this
3319        // subtree has exceeded its restart budget" signal the typed
3320        // slot is meant to express. The bracket set is
3321        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
3322        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
3323        // the sibling `:politicas :circuit-breaker :max-failures` axis:
3324        // both are "trip the next-higher protection layer after N
3325        // events in a rolling window" counters with identical
3326        // degenerate-at-the-high-end shape and now share one canonical
3327        // bracket helper. The bracket precedes the sibling
3328        // `:restart-window` zero-floor / canonical-millisecond arms so
3329        // an over-cap `max_restarts` paired with a structurally invalid
3330        // window surfaces the bracket diagnostic first, mirroring the
3331        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
3332        // ordering on the peer `:politicas :circuit-breaker` slot.
3333        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
3334        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
3335        // accessor rather than the raw `self.max_restarts` field access —
3336        // the one production consumer of the per-`:supervisor`
3337        // restart-budget-count scalar now keys off exactly one typed
3338        // dispatch on the substrate primitive, so any future rebrand on
3339        // the axis (a per-cluster restart-budget override the operator
3340        // pins through a future `:supervisor :max-restarts-overrides`
3341        // slot, a per-tenant restart-budget-alias table the M4 CR
3342        // materializer resolves per-CR) migrates as a single caixa-core
3343        // edit rather than a coordinated rewrite — sibling of the peer M3
3344        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
3345        // the per-`:politicas :circuit-breaker :max-failures` axis.
3346        crate::render::require_positive_bounded_u32(
3347            self.max_restarts(),
3348            SUPERVISOR_MAX_RESTARTS_MAX,
3349            || SupervisorError::ZeroMaxRestarts,
3350            SupervisorError::max_restarts_exceeds_cap,
3351        )?;
3352        // Route the [`SupervisorSpec::validate`] `:restart-window`
3353        // zero-floor + integer-millisecond canonical-form + upper-cap
3354        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
3355        // accessor rather than the raw `self.restart_window` field access —
3356        // the one production consumer of the per-`:supervisor`
3357        // restart-intensity-denominator scalar now keys off exactly one
3358        // typed dispatch on the substrate primitive, so any future rebrand
3359        // on the axis (a per-cluster restart-window override the operator
3360        // pins through a future `:supervisor :restart-window-overrides`
3361        // slot, a per-tenant restart-window-alias table the M4 CR
3362        // materializer resolves per-CR) migrates as a single caixa-core
3363        // edit rather than a coordinated rewrite — sibling of the peer M2
3364        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
3365        // on the per-`:limits :wall-clock` axis and the peer M3
3366        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
3367        // per-`:politicas :timeout` axis.
3368        if let Some(w) = self.restart_window() {
3369            // Zero-floor + integer-millisecond canonical-form +
3370            // upper-cap bracket on the typed `:restart-window` axis.
3371            // See
3372            // [`crate::render::require_positive_canonical_bounded_duration`]
3373            // for the full three-arm ordering discipline (zero-floor
3374            // strictly precedes canonical-form so `Duration::ZERO`
3375            // surfaces the self-locating `RestartWindowZero`
3376            // diagnostic; canonical-form strictly precedes the cap arm
3377            // so a sub-millisecond above-cap value surfaces the more
3378            // fundamental round-trip-shape diagnostic first) and the
3379            // three peer typed-`Duration` sites that share this
3380            // canonical bracket ([`crate::MeshPolicy::timeout`],
3381            // [`crate::CircuitBreaker::window`],
3382            // [`crate::LimitsSpec::wall_clock`]). Every validated
3383            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3384            // (1ms..=1h), integer-millisecond granularity.
3385            crate::render::require_positive_canonical_bounded_duration(
3386                w,
3387                SUPERVISOR_RESTART_WINDOW_MAX,
3388                || SupervisorError::RestartWindowZero,
3389                SupervisorError::restart_window_not_canonical,
3390                SupervisorError::restart_window_exceeds_cap,
3391            )?;
3392        }
3393        // Route the per-child DNS-1123 / semver-requirement / duplicate-
3394        // detection fan-out loop through the lifted named per-slot gate
3395        // [`SupervisorSpec::validate_children`] rather than an inline
3396        // three-per-child cascade — every future consumer that wants to
3397        // re-check only the `:children` slot's per-entry axes (the M4
3398        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3399        // admission webhook re-validating one added/renamed child, the
3400        // future wasm-operator's per-child dynamic-add re-validator on
3401        // the `SimpleOneForOne` runtime-add path once dynamic-children
3402        // graduate to a typed slot, a future partial re-validator on a
3403        // per-`:children`-entry patch) reaches every per-entry axis
3404        // through one dispatch rather than re-inlining the three-arm
3405        // cascade in lockstep with `validate` or paying the peer
3406        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
3407        // reach one entry check. Sibling of the peer M3 mesh-slot
3408        // per-slot gate family (`validate_membros` — the exact peer on
3409        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
3410        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
3411        // `validate_placement`; `validate_politicas` routing through
3412        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
3413        // per-slot gate discipline now spans both the M3 mesh-slot
3414        // family and the M2 `:children` per-child-cascade axis on one
3415        // shape: one named per-slot gate per typed per-entry loop.
3416        self.validate_children()?;
3417        Ok(())
3418    }
3419
3420    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
3421    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
3422    /// gate, and duplicate-`:caixa` dedup arm into one call every
3423    /// consumer that wants to re-validate one `:children` entry (or the
3424    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
3425    /// admits reaches through.
3426    ///
3427    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
3428    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
3429    /// three-per-entry shape (DNS-1123 name + semver-requirement +
3430    /// duplicate-`:caixa` dedup), lifted to one named substrate
3431    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3432    /// materializer's admission webhook re-checking one added or renamed
3433    /// child, the future wasm-operator's per-child dynamic-add
3434    /// re-validator on the `SimpleOneForOne` runtime-add path once
3435    /// dynamic-children graduate to a typed slot, a future partial
3436    /// re-validator on a per-`:children`-entry patch — each reaches the
3437    /// three per-entry axes through this one dispatch rather than
3438    /// re-inlining the three-arm cascade in lockstep with `validate`
3439    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
3440    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
3441    /// reach one entry check.
3442    ///
3443    /// Self-contained on `&self` — resolves its own dedup `HashSet`
3444    /// through [`SupervisorSpec::children`] rather than borrowing one
3445    /// threaded down from `validate`, the same posture the peer M3
3446    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
3447    /// [`crate::AplicacaoSpec::validate_contratos`],
3448    /// [`crate::AplicacaoSpec::validate_entrada`],
3449    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
3450    /// consumer that reaches this gate directly (without first calling
3451    /// `validate`) still runs the full per-child cascade — pinned by
3452    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3453    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3454    /// + `validate_children_is_self_contained_on_children_slot`.
3455    ///
3456    /// The three per-entry arms run in the same canonical order the
3457    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
3458    /// the diagnostic every author-declared per-`:children` entry surfaces
3459    /// through `validate` is byte-equal to the diagnostic this gate
3460    /// surfaces when called directly — the equivalence-pin pair
3461    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3462    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3463    /// asserts the two altitudes discriminate the same set on every
3464    /// per-entry-covered input.
3465    pub fn validate_children(&self) -> Result<(), SupervisorError> {
3466        let mut seen = std::collections::HashSet::new();
3467        for child in self.children() {
3468            // Every emitted cluster artifact's `metadata.name` for a
3469            // supervised child derives from this `:children :caixa` value
3470            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
3471            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
3472            // label value on every child's pod identity, and the per-
3473            // child K8s [`Service`][svc] `metadata.name` the future
3474            // wasm-operator (M3) provisions for inter-child supervision
3475            // tree wiring. Each apiserver-side schema on each landing
3476            // site enforces the DNS-1123 label rule on admission; a
3477            // structurally invalid child name (`"Worker"`, `"my_worker"`,
3478            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
3479            // UUID-shaped mistaken-identity slug) silently passes the
3480            // prior empty-/duplicate-only gate and the failure surfaces
3481            // at `kubectl apply` time as a `metadata.name: Invalid value`
3482            // rejection, far from the source caixa.lisp, with no field
3483            // naming the offending `:children` entry. Lifting the gate
3484            // to caixa-build time mirrors the `:membros :caixa` value-
3485            // shape trajectory (3f9d7a0) and the `:placement :clusters`
3486            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
3487            // identifier axis — the supervisor tree's child names —
3488            // through the lifted
3489            // [`crate::render::require_valid_dns_1123_label`] gate the
3490            // seven peer name axes (`:membros :caixa`, `:placement
3491            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
3492            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
3493            // route through, so drift between the eight axes' accepted
3494            // DNS-1123-label sets is structurally impossible.
3495            //
3496            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
3497            crate::render::require_valid_dns_1123_label(
3498                child.nome(),
3499                || SupervisorError::EmptyChildName,
3500                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
3501            )?;
3502            // The author surface for `:children :versao` is the same
3503            // Cargo-shaped semver requirement string `:deps :versao` and
3504            // `:membros :versao` carry — and the lacre pipeline resolves
3505            // all three axes through the same
3506            // [`crate::version::parse_requirement`] entry-point. The
3507            // shared [`crate::render::require_valid_versao_requirement`]
3508            // helper brackets the empty-first + parse cascade both peer
3509            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
3510            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
3511            // :versao`) route through, so drift between the three axes'
3512            // accepted requirement sets is structurally impossible and
3513            // the parse-side no-op the empty-first arm closes (semver's
3514            // empty parse yields an implicit `*`) lives in exactly one
3515            // predicate. Every `ChildSpec::versao` past validate is
3516            // round-trippable through [`crate::parse_requirement`]
3517            // without re-checking at the resolver layer, and the three
3518            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
3519            // are now structurally equivalent by construction.
3520            crate::render::require_valid_versao_requirement(
3521                child.versao_requirement(),
3522                || SupervisorError::empty_child_version(child.nome()),
3523                |reason| {
3524                    SupervisorError::child_versao_invalid(
3525                        child.nome(),
3526                        child.versao_requirement(),
3527                        reason,
3528                    )
3529                },
3530            )?;
3531            crate::render::insert_first_seen(&mut seen, child.nome(), || {
3532                SupervisorError::duplicate_child_caixa(child.nome())
3533            })?;
3534        }
3535        Ok(())
3536    }
3537}
3538
3539/// Cross-slot coherence gate on the supervision tree: no
3540/// `:children :caixa` entry may name the supervisor's own `:nome`.
3541///
3542/// A supervisor that lists itself as a child is a degenerate self-parent
3543/// — the supervision tree is a DAG rooted at the supervisor (OTP child
3544/// specs reference *distinct* child processes; a supervisor is never its
3545/// own child), and the wasm-operator's hierarchical reconciliation would
3546/// otherwise be handed a node that is its own parent: a one-node cycle it
3547/// either rejects far from the source `caixa.lisp` or recurses on. Because
3548/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
3549/// lacre closure root), a child whose `:caixa` equals the supervisor's
3550/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
3551///
3552/// Lives outside [`SupervisorSpec::validate`] because the typed view
3553/// carries the children but not the parent `:nome`; mirrors the
3554/// cross-slot precedence gate `validate_upgrade_from_against_versao`
3555/// (which likewise reads one slot against another at the
3556/// [`crate::layout`] wire-up site) and the mesh self-edge gate
3557/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
3558/// node to itself is structurally not a tree/mesh edge" discipline, here
3559/// on the supervision-tree axis.
3560pub fn validate_no_self_supervision(
3561    children: &[ChildSpec],
3562    parent_nome: &str,
3563) -> Result<(), SupervisorError> {
3564    for child in children {
3565        if child.nome() == parent_nome {
3566            return Err(SupervisorError::child_supervises_self(parent_nome));
3567        }
3568    }
3569    Ok(())
3570}
3571
3572#[derive(Debug, Error, PartialEq, Eq)]
3573pub enum SupervisorError {
3574    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
3575    NoChildren { estrategia: RestartStrategy },
3576    #[error(
3577        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
3578    )]
3579    SimpleOneForOneWithStaticChildren,
3580    #[error(":max-restarts must be > 0")]
3581    ZeroMaxRestarts,
3582    #[error(
3583        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
3584         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
3585         restart-intensity policy into a no-op supervisor: the escalation threshold is \
3586         structurally so high that no realistic restarts-per-:restart-window traffic shape \
3587         can reach it, so the supervisor never escalates to its parent and a bad child can \
3588         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
3589         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
3590         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3591         materializer's admission webhook) emits a `:max-restarts` declaration that is \
3592         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
3593         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
3594         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
3595         band) or restructure the supervision tree (split the flaky child into its own \
3596         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
3597    )]
3598    MaxRestartsExceedsCap { max_restarts: u32 },
3599    #[error(
3600        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
3601         requires Period > 0; a zero window either trips on the first failure or \
3602         never trips depending on operator interpretation. Omit :restart-window to \
3603         express `never reset`; carry a positive duration to express the window."
3604    )]
3605    RestartWindowZero,
3606    #[error(
3607        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
3608         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
3609         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
3610         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
3611         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
3612    )]
3613    RestartWindowNotCanonical { window: Duration },
3614    #[error(
3615        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
3616         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
3617         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
3618         failure-counting window is structurally so long that transient restarts are never \
3619         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
3620         when the child has exceeded its restart budget within the recent window` to `trip the \
3621         parent when the child has exceeded its restart budget over its lifetime`, and the \
3622         supervisor's reset semantic never reaches the child — every typed-slot consumer \
3623         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
3624         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3625         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
3626         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
3627         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
3628         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
3629         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
3630         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
3631         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
3632         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
3633         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
3634         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
3635         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
3636         hiding it behind a rolling-window declaration the cap arm rejects)"
3637    )]
3638    RestartWindowExceedsCap { window: Duration },
3639    #[error("child entry has empty :caixa name")]
3640    EmptyChildName,
3641    #[error(
3642        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
3643         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
3644         name / label value the child name lands in — the per-child \
3645         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
3646         label value, and the future wasm-operator per-child Service `metadata.name` \
3647         — each apiserver-side schema rejects names that don't match; use a \
3648         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
3649    )]
3650    ChildCaixaInvalid { caixa: String, reason: String },
3651    #[error("child {caixa:?} has empty :versao constraint")]
3652    EmptyChildVersion { caixa: String },
3653    #[error(
3654        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
3655         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
3656         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
3657         `:membros :versao` carry; the lacre pipeline resolves all three \
3658         through the same parser)"
3659    )]
3660    ChildVersaoInvalid {
3661        caixa: String,
3662        versao: String,
3663        reason: String,
3664    },
3665    #[error(
3666        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
3667         child_spec.id per supervisor; duplicate children materialize as duplicate \
3668         ComputeUnits in the rendered chart, one silently overwriting the other)"
3669    )]
3670    DuplicateChildCaixa { caixa: String },
3671    #[error(
3672        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
3673         never its own child (the supervision tree is a DAG rooted at the supervisor; \
3674         OTP child specs reference distinct child processes). Since every :nome is a \
3675         globally-unique substrate identity, a child naming the supervisor's own :nome \
3676         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
3677         self-referential :children entry or rename it to the actual child caixa."
3678    )]
3679    ChildSupervisesSelf { caixa: String },
3680}
3681
3682// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
3683// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
3684// and [`validate_no_self_supervision`] onto one substrate primitive per
3685// typed variant — the sibling on `SupervisorError` of the four uniform-shape
3686// `LayoutError`-envelope constructor families the peer
3687// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
3688// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
3689// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
3690// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
3691// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
3692// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
3693// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
3694// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
3695// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
3696// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
3697// variants on `{ de, para }`) already at that discipline on the peer
3698// `AplicacaoError` envelopes.
3699//
3700// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
3701// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
3702// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
3703// self-supervision arm) opened the identical
3704// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
3705// the exact "same block re-inlined at every consumer" shape the PRIME
3706// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
3707// `AplicacaoError` families each closed on their sibling envelopes. The
3708// three variants share one `{ caixa: String }` shape, so the fold routes
3709// each wire-up site through one dispatch per typed variant.
3710//
3711// The macro below generates one static constructor per variant of shape
3712// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
3713// collapses onto one dispatch:
3714// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
3715// struct-literal on the same `&str` fixture. The uniform one-field
3716// construction (`caixa: caixa.to_string()`) is spelled once — inside the
3717// macro — rather than at every wire-up site. Every constructor is
3718// `#[must_use]` so a caller who mistakenly discards the constructed error
3719// trips a compile warning at the wire-up site.
3720//
3721// Every future consumer that wants to construct one of these three
3722// variants outside `SupervisorSpec::validate_children` /
3723// `validate_no_self_supervision` — a deferred
3724// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3725// webhook re-checking one added/renamed child, a future
3726// `feira validate --supervisor` per-caixa admission verb, a per-child
3727// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
3728// once dynamic-children graduate to a typed slot, a per-Supervisor
3729// overlay resolver rejecting a duplicate/self-supervising child against
3730// a cluster-local snapshot — now reaches each variant through one call
3731// rather than re-inlining the three-line struct-literal in lockstep
3732// with the three in-crate wire-up sites.
3733macro_rules! supervisor_caixa_only_ctors {
3734    ($($ctor:ident => $variant:ident),* $(,)?) => {
3735        impl SupervisorError {
3736            $(
3737                #[doc = concat!(
3738                    "Construct a [`SupervisorError::",
3739                    stringify!($variant),
3740                    "`] naming the offending `:children :caixa` (or ",
3741                    "supervisor `:nome`, on the self-supervision arm). ",
3742                    "Folds the uniform `Self::",
3743                    stringify!($variant),
3744                    " { caixa: caixa.to_string() }` one-field ",
3745                    "struct-literal onto one substrate primitive so ",
3746                    "every [`SupervisorSpec::validate_children`] / ",
3747                    "[`validate_no_self_supervision`] wire-up on this ",
3748                    "variant reads through one dispatch rather than the ",
3749                    "pre-lift open-coded struct-literal block."
3750                )]
3751                #[must_use]
3752                pub fn $ctor(caixa: &str) -> Self {
3753                    Self::$variant { caixa: caixa.to_string() }
3754                }
3755            )*
3756        }
3757    };
3758}
3759
3760supervisor_caixa_only_ctors! {
3761    empty_child_version => EmptyChildVersion,
3762    duplicate_child_caixa => DuplicateChildCaixa,
3763    child_supervises_self => ChildSupervisesSelf,
3764}
3765
3766// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
3767// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
3768// one substrate primitive per typed variant — the M2 supervisor-side siblings
3769// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
3770// already lifted through the sibling
3771// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
3772// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
3773// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
3774// String }` two-slot shape the peer seven-variant
3775// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
3776// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
3777// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
3778// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
3779// variant carries the `{ caixa: String, versao: String, reason: String }`
3780// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
3781// carries on the same `:versao` value-shape.
3782//
3783// Each of the two wire-up sites opened the same closure-shaped
3784// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
3785// [versao: child.versao_requirement().to_string(),] reason }` block inside
3786// the paired [`crate::render::require_valid_dns_1123_label`] and
3787// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
3788// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
3789// as a bug, on the same altitude the peer `AplicacaoError` /
3790// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
3791// families already closed on their sibling envelopes.
3792//
3793// The two `#[must_use]` inherent constructors below fold each wire-up onto
3794// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
3795// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
3796// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
3797// The uniform per-field `.to_string()` / `.into()` construction is spelled
3798// once — inside each ctor body — rather than at every wire-up site. The
3799// `reason: impl Into<String>` bound accepts both `&str` literals and
3800// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
3801// diagnostic shape at the lift, matching the peer
3802// [`aplicacao_field_reason_ctors!`] and
3803// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
3804// sibling envelopes.
3805//
3806// Every future consumer that wants to construct one of these two variants
3807// outside `SupervisorSpec::validate_children` — a deferred
3808// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
3809// re-checking one added/renamed child's `:caixa` or `:versao`, a future
3810// `feira validate --supervisor` per-caixa admission verb, a per-child
3811// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
3812// dynamic-children graduate to a typed slot, a per-Supervisor overlay
3813// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
3814// cluster-local snapshot — now reaches each variant through one call rather
3815// than re-inlining the per-shape struct-literal block in lockstep with the
3816// two in-crate wire-up sites.
3817impl SupervisorError {
3818    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
3819    /// offending `:children :caixa` value under the given `reason`. Folds
3820    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
3821    /// reason: reason.into() }` two-slot struct-literal onto one substrate
3822    /// primitive so every wire-up on this variant reads through one
3823    /// dispatch, matching the peer
3824    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
3825    /// sibling `AplicacaoError { caixa: String, reason: String }`
3826    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
3827    /// outputs through the `impl Into<String>` bound.
3828    #[must_use]
3829    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
3830        Self::ChildCaixaInvalid {
3831            caixa: caixa.to_string(),
3832            reason: reason.into(),
3833        }
3834    }
3835
3836    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
3837    /// offending `:children :caixa` and its `:versao` requirement under
3838    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
3839    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
3840    /// reason.into() }` three-slot struct-literal onto one substrate
3841    /// primitive so every wire-up on this variant reads through one
3842    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
3843    /// { caixa, versao, reason }` three-slot axis on the peer
3844    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
3845    /// and `format!(…)` outputs through the `impl Into<String>` bound.
3846    #[must_use]
3847    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
3848        Self::ChildVersaoInvalid {
3849            caixa: caixa.to_string(),
3850            versao: versao.to_string(),
3851            reason: reason.into(),
3852        }
3853    }
3854}
3855
3856// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
3857// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
3858// three bracket-arms — one struct-literal at the `:children`-empty
3859// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
3860// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
3861// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
3862// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
3863// [`crate::render::require_positive_canonical_bounded_duration`]
3864// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
3865// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
3866// primitive per typed variant, matching the sibling
3867// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
3868// variants on the same `{ <field>: Duration | u32 }` shape) at that
3869// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
3870// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
3871// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
3872// wire-up site through one dispatch per typed variant without a runtime-
3873// work delta.
3874//
3875// Each of the four wire-up sites opened the identical
3876// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
3877// exact "same block re-inlined at every consumer" shape the PRIME
3878// DIRECTIVE names as a bug, on the same altitude the peer
3879// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
3880// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
3881// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
3882// the fold routes each wire-up site through one dispatch per typed
3883// variant.
3884//
3885// The macro below generates one static constructor per variant of shape
3886// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
3887// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
3888// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
3889// fixture — as a direct call at the [`SupervisorSpec::validate`]
3890// `:children`-empty refusal, or as a bare function pointer in the
3891// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
3892// [`crate::render::require_positive_bounded_u32`] /
3893// [`crate::render::require_positive_canonical_bounded_duration`] gate
3894// carries — rather than the pre-lift open-coded one-line closure over
3895// the same one-field struct-literal. `const fn` preserves the `Copy`-
3896// pass-through's zero-runtime-work property verbatim. Every constructor
3897// is `#[must_use]` so a caller who mistakenly discards the constructed
3898// error trips a compile warning at the wire-up site.
3899//
3900// Every future consumer that wants to construct one of these four
3901// variants outside `SupervisorSpec::validate` — a deferred
3902// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3903// webhook re-checking one edited `:estrategia` / `:max-restarts` /
3904// `:restart-window` slot against the cap + canonical-form cascade, a
3905// future `feira validate --supervisor` per-caixa admission verb re-
3906// running the shape gates on demand, a per-Supervisor overlay resolver
3907// rejecting an author-supplied slot against a cluster-local snapshot —
3908// now reaches each variant through one call rather than re-inlining the
3909// per-shape struct-literal block in lockstep with the four in-crate
3910// wire-up sites.
3911macro_rules! supervisor_scalar_ctors {
3912    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
3913        impl SupervisorError {
3914            $(
3915                #[doc = concat!(
3916                    "Construct a [`SupervisorError::",
3917                    stringify!($variant),
3918                    "`] naming the offending per-`:supervisor` `",
3919                    stringify!($field),
3920                    "` scalar. Folds the uniform `Self::",
3921                    stringify!($variant),
3922                    " { ",
3923                    stringify!($field),
3924                    " }` one-field `Copy`-pass-through struct-literal onto ",
3925                    "one substrate primitive so every per-axis wire-up on ",
3926                    "this variant reads through one dispatch — as a direct ",
3927                    "call (`SupervisorError::",
3928                    stringify!($ctor),
3929                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
3930                    "the same `Copy`-`",
3931                    stringify!($ty),
3932                    "` fixture) or as a bare function pointer in the ",
3933                    "`impl FnOnce(",
3934                    stringify!($ty),
3935                    ") -> SupervisorError` bracket-closure slot every ",
3936                    "`crate::render::require_positive_bounded_*` / ",
3937                    "`crate::render::require_positive_canonical_bounded_*` ",
3938                    "gate carries — rather than the pre-lift open-coded ",
3939                    "one-line closure over the same one-field struct-",
3940                    "literal. `const fn` preserves the `Copy`-pass-through's ",
3941                    "zero-runtime-work property verbatim."
3942                )]
3943                #[must_use]
3944                pub const fn $ctor($field: $ty) -> Self {
3945                    Self::$variant { $field }
3946                }
3947            )*
3948        }
3949    };
3950}
3951
3952supervisor_scalar_ctors! {
3953    no_children => NoChildren { estrategia: RestartStrategy },
3954    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
3955    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
3956    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
3957}
3958
3959/// Shared duration string codec for the typed slots that take a
3960/// duration (`restart_window`, `MeshPolicy::timeout`,
3961/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
3962/// reuse it without duplicating the parser.
3963pub mod duration_codec {
3964    use super::Duration;
3965    use serde::{Deserializer, Serializer};
3966
3967    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
3968        // Route through the canonical [`crate::render::serialize_option_via_str`]
3969        // — the substrate-side single-owner primitive for the forward
3970        // arm of the typed-magnitude codec family. See its docstring
3971        // for the full sibling roster.
3972        crate::render::serialize_option_via_str(v, s, render)
3973    }
3974
3975    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
3976        // Route through the canonical [`crate::render::deserialize_option_via_str`]
3977        // — the substrate-side single-owner primitive for the reverse
3978        // arm of the typed-magnitude codec family. See its docstring
3979        // for the full sibling roster.
3980        crate::render::deserialize_option_via_str(d, parse)
3981    }
3982
3983    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
3984        // Paired whitespace-rejection arm — same canonical-form
3985        // render-determinism discipline as the peer
3986        // `limits::parse_byte_size` / `limits::parse_duration` /
3987        // `limits::parse_millicores` /
3988        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
3989        // byte-scan closes the WhatWG-conformant whitespace bytes
3990        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
3991        // `char::is_whitespace` scan closes the strictly-complementary
3992        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
3993        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
3994        // codepoints) that `str::trim` at parse entry silently strips.
3995        // Either drift class would round-trip through `render` to a
3996        // *different* canonical form on next emit — breaking the
3997        // THEORY.md Part V render-determinism contract on three typed-
3998        // duration slots at once (`:supervisor :restart-window`,
3999        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
4000        // via the shared codec.
4001        //
4002        // Routed through the lifted [`crate::render::reject_whitespace`]
4003        // primitive — the substrate-side single-owner paired-arm gate
4004        // every typed-magnitude codec in caixa-core shares.
4005        crate::render::reject_whitespace::<String, _, _>(
4006            s,
4007            |b| {
4008                format!(
4009                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4010                 authoring form for the typed duration slots routed through this shared codec \
4011                 (`:supervisor :restart-window`, `:politicas :timeout`, \
4012                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4013                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
4014                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
4015                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
4016                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
4017                 Part V render-determinism contract every typed slot carries. Strip every \
4018                 whitespace byte (write `\"30s\"` verbatim)"
4019                )
4020            },
4021            |ch| {
4022                format!(
4023                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
4024                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
4025                 duration slots routed through this shared codec (`:supervisor \
4026                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
4027                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
4028                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
4029                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
4030                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
4031                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
4032                 `White_Space` property, strictly wider than the ASCII byte set) silently \
4033                 strips it at parse entry, and the value round-trips through `render` to \
4034                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
4035                 the THEORY.md Part V render-determinism contract every typed slot \
4036                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
4037                 verbatim with only ASCII bytes)",
4038                    cp = ch as u32
4039                )
4040            },
4041        )?;
4042        let s = s.trim();
4043        // Routed through the lifted
4044        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
4045        // the single-owner split every ASCII-alphabetic-unit typed-
4046        // magnitude codec in caixa-core (`limits::parse_byte_size` /
4047        // `limits::parse_duration` / this shared duration codec) shares.
4048        // See its docstring for the full sibling roster on the same
4049        // primitive altitude.
4050        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
4051        let num_trim = num_part.trim();
4052        // The canonical authoring form for every typed slot routed
4053        // through this shared codec — `:supervisor :restart-window`,
4054        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
4055        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
4056        // non-negative integer with no decimal point and no leading
4057        // sign, so the parser's accepted set must match for
4058        // serialize/deserialize to round-trip without canonical-form
4059        // drift. Until this gate landed the parser accepted any
4060        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
4061        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
4062        // tripped the value to a *different* canonical string on the
4063        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
4064        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
4065        // — breaking the THEORY.md Part V render-determinism contract
4066        // on three typed slots at once. Same canonical-form discipline
4067        // `crate::limits::parse_duration` (818dd38, the immediate
4068        // predecessor on the peer `:limits :wall-clock` codec) applies;
4069        // this gate lifts the discipline onto the shared codec that
4070        // backs the remaining three typed-duration slots in caixa-core.
4071        //
4072        // Strict canonical form: every byte of the magnitude is an
4073        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4074        // inputs the gate distinguishes "non-canonical-but-numeric"
4075        // (parses as f64 or i64 — surfaced with a self-locating
4076        // diagnostic naming the canonical authoring form, the
4077        // round-trip drift each rejected shape would produce on first
4078        // serialize, and the canonical-form remediation) from
4079        // "garbage" (parses as neither — surfaced with the existing
4080        // narrower "bad duration magnitude" wording so its diagnostic
4081        // shape remains stable for the parser-shape footgun case).
4082        // The pre-existing `num < 0.0` arm is now unreachable — the
4083        // digit-only gate strictly precedes magnitude parsing, and a
4084        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
4085        // non-canonical-but-numeric branch with the `-30` named
4086        // verbatim in the diagnostic rather than the prior
4087        // value-laundered "negative duration in \"-30s\"" wording.
4088        //
4089        // Routed through the lifted
4090        // [`crate::render::is_digit_only_magnitude`] predicate — the
4091        // same source of truth the four peer typed-magnitude codec
4092        // sites share.
4093        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
4094        if !digit_only {
4095            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
4096            if numeric {
4097                return Err(format!(
4098                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
4099                     canonical authoring form for the typed duration slots routed through \
4100                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4101                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4102                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
4103                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
4104                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
4105                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
4106                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
4107                     THEORY.md Part V render-determinism contract every typed slot carries. \
4108                     Pick an integer magnitude in the unit that divides cleanly (write \
4109                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
4110                ));
4111            }
4112            return Err(format!("bad duration magnitude in {s:?}"));
4113        }
4114        // Leading-zero arm — peer with the `rate_limit_codec` leading-
4115        // zero arm (4f46830) on the same canonical-form render-
4116        // determinism axis. The digit-only gate accepts `"030s"`,
4117        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
4118        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
4119        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
4120        // *different* canonical string on the next emit, breaking the
4121        // THEORY.md Part V render-determinism contract the same way
4122        // `"+30s"` did before the leading-`+` arm landed. The single-
4123        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
4124        // losslessly through `render` (`render(Duration::ZERO)` emits
4125        // `"0s"`) — the downstream semantic-zero gates (e.g.
4126        // `SupervisorError::ZeroRestartWindow` on
4127        // `:supervisor :restart-window`,
4128        // `AplicacaoError::PolicyTimeoutZero` /
4129        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
4130        // duration slots) refuse zero-magnitude authoring at the typed-
4131        // validate layer above, so the single-byte `"0"` stays in the
4132        // accepted set at this codec layer and the diagnostic
4133        // partitioning between canonical-form drift (this arm) and
4134        // semantic-zero (the downstream gates) remains stable.
4135        // Peer with the future leading-zero arms on the two remaining
4136        // typed-magnitude codecs the trajectory acknowledges:
4137        // `limits::parse_duration` backing `:limits :wall-clock`,
4138        // `limits::parse_byte_size` backing `:limits :memory` — each
4139        // carries the same canonical-form-drift class today; this
4140        // gate lands the discipline on the shared duration codec
4141        // first because the `rate_limit_codec` predecessor on the
4142        // same canonical-form-drift axis is the closest peer on the
4143        // trajectory.
4144        //
4145        // Routed through the lifted
4146        // [`crate::render::is_leading_zero_padded_magnitude`]
4147        // predicate — the same source of truth the four peer
4148        // typed-magnitude codec sites share.
4149        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
4150            return Err(format!(
4151                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
4152                 canonical authoring form for the typed duration slots routed through \
4153                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4154                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4155                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
4156                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
4157                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
4158                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
4159                 serialize — breaking the THEORY.md Part V render-determinism contract \
4160                 every typed slot carries. Strip the leading zeros (write \
4161                 `\"30s\"` instead of `\"030s\"`)"
4162            ));
4163        }
4164        // The digit-only gate guarantees every byte is `[0-9]`, and
4165        // the leading-zero arm above guarantees the magnitude is
4166        // either the single byte `"0"` or starts with `[1-9]`, so
4167        // the only way `u64::from_str` can fail here is overflow (the
4168        // magnitude exceeds `u64::MAX`). Surface that with an
4169        // overflow-shaped wording so the diagnostic names the offending
4170        // magnitude verbatim rather than collapsing onto the
4171        // non-canonical arm. The codec now operates on `u64` end-to-end
4172        // — every accepted magnitude is integer-exact; no f64 mantissa
4173        // drift between author-supplied magnitude and the consumer's
4174        // `Duration` value. Same shape `crate::limits::parse_duration`
4175        // (818dd38) carries on the peer `:limits :wall-clock` axis.
4176        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
4177            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
4178        })?;
4179        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
4180        // unit-arm dispatch through the canonical
4181        // [`crate::render::duration_from_integer_magnitude_and_unit`]
4182        // primitive — the substrate-side single-owner unit-dispatch
4183        // table every typed-duration codec in caixa-core routes
4184        // through (peer: `crate::limits::parse_duration` backing
4185        // `:limits :wall-clock`). Every unit conversion is integer-
4186        // exact for an integer magnitude; overflow surfaces via the
4187        // typed `DurationUnitError::Overflow { multiplier }`
4188        // discriminant so this arm reconstructs the pre-lift
4189        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
4190        // wording verbatim from `num` / `unit_trim` / the returned
4191        // `multiplier`, and the unknown-unit arm reconstructs the
4192        // pre-lift `"unknown duration unit \"<other>\""` wording from
4193        // the caller-scoped `unit_trim`. Load-bearing pinned by
4194        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
4195        let unit_trim = unit.trim();
4196        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
4197            |e| match e {
4198                crate::render::DurationUnitError::Overflow { multiplier } => format!(
4199                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
4200                ),
4201                crate::render::DurationUnitError::UnknownUnit => {
4202                    format!("unknown duration unit {unit_trim:?}")
4203                }
4204            },
4205        )?;
4206        Ok(dur)
4207    }
4208
4209    /// Render a [`Duration`] in the canonical pleme-io duration string
4210    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
4211    /// caixa typed-duration slot serializes to and the same form K8s
4212    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
4213    /// EnvoyConfig per-route timeouts both expect (an integer
4214    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
4215    /// `+`). Lifted to `pub` so caixa-side renderers
4216    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
4217    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
4218    /// emitter, the future caixa-otel collector pipeline emitter) can
4219    /// consume the same canonical formatter without re-inlining the
4220    /// magnitude/unit decision tree (and inheriting the same drift
4221    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
4222    /// downstream apply-time parsing in non-obvious ways).
4223    pub fn render(d: Duration) -> String {
4224        let total_ms = d.as_millis();
4225        if total_ms == 0 {
4226            return "0s".into();
4227        }
4228        if total_ms.is_multiple_of(3600 * 1000) {
4229            return format!("{}h", total_ms / (3600 * 1000));
4230        }
4231        if total_ms.is_multiple_of(60 * 1000) {
4232            return format!("{}m", total_ms / (60 * 1000));
4233        }
4234        if total_ms.is_multiple_of(1000) {
4235            return format!("{}s", total_ms / 1000);
4236        }
4237        format!("{total_ms}ms")
4238    }
4239
4240    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
4241    ///
4242    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
4243    /// largest divisor unit, so any sub-millisecond residue
4244    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
4245    /// §V.2.7 render-determinism contract:
4246    ///
4247    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
4248    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
4249    ///     `1_000_000` ns ≠ original `1_500_000` ns;
4250    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
4251    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
4252    ///     on every typed-`Duration` slot then rejects on re-validate.
4253    ///
4254    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
4255    /// the codec's round-trippable accepted set lives in exactly one place —
4256    /// every typed-`Duration` slot that routes through this shared codec
4257    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
4258    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
4259    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
4260    /// every typed-`Duration` slot whose own codec shares the same
4261    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
4262    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
4263    /// pair) calls this predicate from its `validate()` to bracket the
4264    /// accepted set against the codec's accepted set, structurally. Drift
4265    /// between the codec's granularity and any typed slot's accepted set is
4266    /// then a single-source-of-truth edit at this predicate rather than a
4267    /// silent round-trip break the next consumer discovers at apply time.
4268    ///
4269    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
4270    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
4271    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
4272    /// family — same "typed-slot's valid set matches its codec's accepted
4273    /// set, structurally" discipline carried at the codec layer.
4274    #[must_use]
4275    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
4276        d.subsec_nanos().is_multiple_of(1_000_000)
4277    }
4278}
4279
4280/// Required-Duration variant for fields that aren't Option<Duration>.
4281pub mod duration_codec_required {
4282    use super::Duration;
4283    use serde::{Deserialize, Deserializer, Serializer};
4284
4285    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
4286        s.serialize_str(&super::duration_codec::render(*v))
4287    }
4288
4289    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
4290        let s = String::deserialize(d)?;
4291        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
4292    }
4293}
4294
4295#[cfg(test)]
4296mod tests {
4297    use super::*;
4298
4299    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
4300        ChildSpec {
4301            caixa: name.into(),
4302            versao: ver.into(),
4303            restart,
4304        }
4305    }
4306
4307    #[test]
4308    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
4309        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
4310        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
4311        // posture. Each accessor projects the per-`:children :caixa`
4312        // / per-`:children :versao` [`String`] storage through the
4313        // `pub const fn` [`String::as_str`] (const-stable since Rust
4314        // 1.87, well within the workspace MSRV) — any future
4315        // accidental downgrade to non-`const` fails the corresponding
4316        // `<name>_via_const_fn` wrapper at caixa-core build time with
4317        // E0015 (`cannot call non-const method`), strictly stronger
4318        // than a runtime `assert!`. Sibling of the peer
4319        // per-M2/M3/universal-axis `String → &str` scalar-accessor
4320        // family pins on the sibling `const`-eval-surface passes
4321        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
4322        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
4323        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
4324        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
4325        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
4326        // [`crate::aplicacao::Entrada::destination`] at the M3
4327        // ingress axis,
4328        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
4329        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
4330        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
4331        // axis, and the per-`:contratos`
4332        // [`crate::aplicacao::WitContract::source`] /
4333        // [`crate::aplicacao::WitContract::destination`] /
4334        // [`crate::aplicacao::WitContract::world_ref`] trio the
4335        // sibling pin at 279823b already anchors).
4336        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
4337            c.nome()
4338        }
4339        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
4340            c.versao_requirement()
4341        }
4342        for (caixa, versao) in [
4343            ("worker-a", "^0.1"),
4344            ("worker-b", "~0.2.3"),
4345            ("collector", "*"),
4346        ] {
4347            let c = child(caixa, versao, RestartPolicy::Permanent);
4348            assert_eq!(nome_via_const_fn(&c), c.nome());
4349            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
4350            assert_eq!(c.nome(), caixa);
4351            assert_eq!(c.versao_requirement(), versao);
4352        }
4353    }
4354
4355    #[test]
4356    fn supervisor_children_slice_return_accessor_is_const_fn() {
4357        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
4358        // `const`-eval-surface posture. The accessor destructures the
4359        // per-`:children` `Vec<ChildSpec>` storage through the
4360        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
4361        // 1.66, well within the workspace MSRV) — any future
4362        // accidental downgrade to non-`const` fails
4363        // `children_via_const_fn` at caixa-core build time with E0015
4364        // (`cannot call non-const method`), strictly stronger than a
4365        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
4366        // `Vec → &[T]` slice-return accessor family pin
4367        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
4368        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
4369        // per-`:membros` / per-`:contratos` slice-return axes, and of
4370        // the peer M2 upgrade-appup axis pin
4371        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
4372        // on the per-`:upgrade-from :instructions` slice-return axis.
4373        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
4374            s.children()
4375        }
4376        // Sweep both the empty-children (leaf-supervisor with no
4377        // static children — the `SimpleOneForOne` dynamic-child
4378        // arm's canonical shape) and the populated-children
4379        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
4380        // arm's canonical shape) axes so the accessor carries a
4381        // const-dispatch pin on both arms.
4382        let s_empty = SupervisorSpec {
4383            estrategia: RestartStrategy::SimpleOneForOne,
4384            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4385            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4386            children: vec![],
4387        };
4388        assert!(children_via_const_fn(&s_empty).is_empty());
4389        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
4390        let s_full = SupervisorSpec {
4391            estrategia: RestartStrategy::OneForOne,
4392            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4393            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4394            children: vec![
4395                child("worker-a", "^0.1", RestartPolicy::Permanent),
4396                child("worker-b", "~0.2.3", RestartPolicy::Transient),
4397                child("collector", "*", RestartPolicy::Temporary),
4398            ],
4399        };
4400        assert_eq!(children_via_const_fn(&s_full).len(), 3);
4401        assert_eq!(children_via_const_fn(&s_full), s_full.children());
4402    }
4403
4404    #[test]
4405    fn default_has_one_for_one_and_5_restarts_in_60s() {
4406        let s = SupervisorSpec::default();
4407        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
4408        assert_eq!(s.max_restarts, 5);
4409        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
4410        assert!(s.children.is_empty());
4411    }
4412
4413    #[test]
4414    fn validate_one_for_one_requires_children() {
4415        let mut s = SupervisorSpec::default();
4416        s.children = vec![];
4417        assert!(matches!(
4418            s.validate().unwrap_err(),
4419            SupervisorError::NoChildren { .. }
4420        ));
4421        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
4422        s.validate().unwrap();
4423    }
4424
4425    #[test]
4426    fn validate_simple_one_for_one_forbids_static_children() {
4427        let mut s = SupervisorSpec {
4428            estrategia: RestartStrategy::SimpleOneForOne,
4429            ..SupervisorSpec::default()
4430        };
4431        s.children
4432            .push(child("w", "^0.1", RestartPolicy::Permanent));
4433        assert_eq!(
4434            s.validate().unwrap_err(),
4435            SupervisorError::SimpleOneForOneWithStaticChildren
4436        );
4437        s.children.clear();
4438        s.validate().unwrap();
4439    }
4440
4441    #[test]
4442    fn validate_rejects_zero_max_restarts() {
4443        let s = SupervisorSpec {
4444            max_restarts: 0,
4445            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4446            ..SupervisorSpec::default()
4447        };
4448        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
4449    }
4450
4451    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
4452    //
4453    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
4454    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
4455    // `:supervisor :max-restarts` axis — both fields are "trip the
4456    // next-higher protection layer after N events in a rolling window"
4457    // counters with identical degenerate-at-the-high-end shape, so the
4458    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
4459    // exactly as it lies in `1..=1000` on the breaker side.
4460
4461    #[test]
4462    fn validate_rejects_max_restarts_above_cap() {
4463        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
4464        // 1` is structurally one past the cap and silently passed
4465        // validate on every pre-gate codebase because the typed slot's
4466        // only check was the zero-floor arm. The no-op-supervisor vector
4467        // only surfaced at the runtime substrate (Erlang/OTP
4468        // MaxIntensity/Period ratio, the future wasm-operator's
4469        // per-supervisor restart-intensity counter) far from the source
4470        // caixa.lisp with no field naming the offending supervisor.
4471        let s = SupervisorSpec {
4472            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4473            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4474            ..SupervisorSpec::default()
4475        };
4476        assert_eq!(
4477            s.validate().unwrap_err(),
4478            SupervisorError::MaxRestartsExceedsCap {
4479                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4480            }
4481        );
4482    }
4483
4484    #[test]
4485    fn validate_rejects_max_restarts_far_above_cap() {
4486        // The `u32::MAX` worst case — the four-billion-restart
4487        // threshold a typo (`:max-restarts 4294967295`) or a
4488        // struct-literal copy-paste lands in the slot. Pin the cap
4489        // arm's coverage explicitly across the full `u32` overflow so
4490        // a future relaxation that drops the upper bound surfaces
4491        // here. Same shape every other typed-cap arm on this surface
4492        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
4493        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
4494        let s = SupervisorSpec {
4495            max_restarts: u32::MAX,
4496            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4497            ..SupervisorSpec::default()
4498        };
4499        assert_eq!(
4500            s.validate().unwrap_err(),
4501            SupervisorError::MaxRestartsExceedsCap {
4502                max_restarts: u32::MAX,
4503            }
4504        );
4505    }
4506
4507    #[test]
4508    fn validate_accepts_max_restarts_at_cap() {
4509        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
4510        // must validate. The cap is inclusive on the top edge,
4511        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
4512        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
4513        // discipline on the sibling capped axes. Pin the boundary
4514        // explicitly so a future off-by-one tightening
4515        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
4516        // here as a test failure rather than a silent contract
4517        // narrowing.
4518        let s = SupervisorSpec {
4519            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
4520            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4521            ..SupervisorSpec::default()
4522        };
4523        s.validate()
4524            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
4525    }
4526
4527    #[test]
4528    fn validate_accepts_max_restarts_typical_values() {
4529        // The documented production-playbook band positive-control
4530        // sweep — every value Erlang/OTP / Elixir / Riak Core /
4531        // RabbitMQ recommend (1..=100) must pass, plus a sweep
4532        // through the hyperscale band (200, 500, 1000) the cap
4533        // accepts. Pin the inclusive validated set explicitly so a
4534        // future tightening of the ceiling surfaces here.
4535        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
4536            let s = SupervisorSpec {
4537                max_restarts: n,
4538                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4539                ..SupervisorSpec::default()
4540            };
4541            s.validate()
4542                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
4543        }
4544    }
4545
4546    #[test]
4547    fn zero_max_restarts_takes_precedence_over_cap() {
4548        // The cross-arm ordering pin: `0` is structurally outside
4549        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
4550        // (cap), but the zero-floor diagnostic is the more
4551        // self-locating one (it directly names the counter-axis
4552        // remediation), so the validate gate must fire on zero first.
4553        // Same shape every other zero-then-shape ordering on this
4554        // surface uses (PolicyRetriesZero then
4555        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
4556        // PolicyBreakerMaxFailuresExceedsCap).
4557        let s = SupervisorSpec {
4558            max_restarts: 0,
4559            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4560            ..SupervisorSpec::default()
4561        };
4562        assert_eq!(
4563            s.validate().unwrap_err(),
4564            SupervisorError::ZeroMaxRestarts,
4565            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
4566        );
4567    }
4568
4569    #[test]
4570    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
4571        // The cross-arm ordering pin between the cap and the sibling
4572        // `:restart-window` gates (zero-window, canonical-window). A
4573        // supervisor carrying both an over-cap `max_restarts` AND a
4574        // structurally invalid window (zero, sub-ms) must surface the
4575        // cap diagnostic first — the cap arm is wired immediately
4576        // after the zero-restart arm and strictly before the window
4577        // arms, so the offending value the diagnostic names matches
4578        // the order the author would discover the gates by reading
4579        // top-to-bottom through `SupervisorSpec::validate`. Pin the
4580        // order so a future refactor that reorders the arms surfaces
4581        // here as a test failure rather than a silent diagnostic
4582        // regression. Peer of
4583        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
4584        // on the sibling `:politicas :circuit-breaker` slot.
4585        let s = SupervisorSpec {
4586            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4587            restart_window: Some(Duration::ZERO),
4588            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4589            ..SupervisorSpec::default()
4590        };
4591        assert_eq!(
4592            s.validate().unwrap_err(),
4593            SupervisorError::MaxRestartsExceedsCap {
4594                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4595            },
4596            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4597        );
4598    }
4599
4600    #[test]
4601    fn max_restarts_cap_diagnostic_carries_offending_value() {
4602        // The diagnostic-shape pin: the offending `u32` is carried
4603        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
4604        // variant so the surfaced error message names the value the
4605        // author wrote (`":supervisor :max-restarts (50000) exceeds the
4606        // supervisor-policy ceiling …"`), not just the cap. Same
4607        // self-locating diagnostic shape every other typed-cap arm on
4608        // this surface carries
4609        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
4610        // the offending failure count verbatim,
4611        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
4612        // retries count verbatim).
4613        let s = SupervisorSpec {
4614            max_restarts: 50_000,
4615            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4616            ..SupervisorSpec::default()
4617        };
4618        let err = s.validate().unwrap_err();
4619        assert!(
4620            matches!(
4621                err,
4622                SupervisorError::MaxRestartsExceedsCap {
4623                    max_restarts: 50_000
4624                }
4625            ),
4626            "got {err:?}"
4627        );
4628        let msg = err.to_string();
4629        assert!(
4630            msg.contains("50000"),
4631            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
4632        );
4633    }
4634
4635    #[test]
4636    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
4637        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
4638        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
4639        // half of Learn You Some Erlang's worker-supervisor default,
4640        // sibling of the `60s` `Period` half that the paired
4641        // [`Default for SupervisorSpec`] impl already pins on the
4642        // sibling `restart_window` axis. Pinning the literal here
4643        // surfaces a future rebrand (a tightening to Elixir's `3`,
4644        // a widening to a per-cluster overlay the operator pins
4645        // through a future `:max-restarts-overrides` slot) as a
4646        // deliberate test edit, not a silent contract migration.
4647        // Peer of the sibling
4648        // [`supervisor_max_restarts_cap_pins_canonical_value`]
4649        // upper-bracket pin on the same axis.
4650        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
4651    }
4652
4653    #[test]
4654    fn default_max_restarts_helper_routes_through_lifted_default() {
4655        // Composition pin: the private `default_max_restarts()`
4656        // serde-`#[serde(default = "…")]` helper on
4657        // [`SupervisorSpec::max_restarts`] must route through the
4658        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4659        // typed `pub const` rather than a raw `5` literal. Prior to
4660        // the lift the helper carried an inline `5` with no compile-
4661        // time link back to the shared default, so the wire-format
4662        // author-omitted arm and the caixa-core
4663        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
4664        // arm could silently split on any future default rebrand.
4665        // Byte-parity against the lifted constant closes the split.
4666        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
4667    }
4668
4669    #[test]
4670    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
4671        // Composition pin: the [`Default for SupervisorSpec`] impl's
4672        // struct-literal `max_restarts` field must route through the
4673        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4674        // typed `pub const` (via the private helper this test's
4675        // sibling `default_max_restarts_helper_routes_through_lifted_default`
4676        // already pins onto the constant). Structurally: every
4677        // `SupervisorSpec::default()` call must yield a
4678        // `max_restarts` field byte-equal to the lifted constant
4679        // (the two paired defaults — the serde-side wire-format arm
4680        // and the struct-literal default arm — cannot silently split
4681        // on any future default rebrand). Peer of the sibling
4682        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
4683        // — this pin closes the byte-parity arm on the two paired
4684        // altitude entry points onto the shared substrate constant.
4685        assert_eq!(
4686            SupervisorSpec::default().max_restarts(),
4687            SUPERVISOR_MAX_RESTARTS_DEFAULT,
4688        );
4689    }
4690
4691    #[test]
4692    fn supervisor_restart_window_default_pins_otp_canonical_value() {
4693        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
4694        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
4695        // Learn You Some Erlang's worker-supervisor default, paired
4696        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
4697        // `MaxIntensity` half this constant is the sliding-window
4698        // denominator of on the same `MaxIntensity / Period`
4699        // restart-intensity ratio. Pinning the literal here surfaces a
4700        // future coherent rebrand of the paired default (Elixir's
4701        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
4702        // the operator pins through a future
4703        // `:restart-window-overrides` slot) as a deliberate test edit,
4704        // not a silent contract migration. Peer of the sibling
4705        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
4706        // paired-half pin on the same OTP-canonical default and the
4707        // [`supervisor_restart_window_cap_pins_canonical_value`]
4708        // upper-bracket pin on the same axis.
4709        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
4710    }
4711
4712    #[test]
4713    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
4714        // Composition pin: the [`Default for SupervisorSpec`] impl's
4715        // struct-literal `restart_window` field must route through the
4716        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4717        // typed `pub const` rather than a raw
4718        // `Duration::from_secs(60)` literal. Prior to this lift the
4719        // paired `{intensity, 5, 60}` OTP-canonical default was split
4720        // across two altitudes with no compile-time link between the
4721        // halves — the `MaxIntensity` half rode through the lifted
4722        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
4723        // `Period` half rode as an open-coded literal at the
4724        // composition site, so a future coherent rebrand of the paired
4725        // canonical would have had to migrate one half through the
4726        // constant and the other through a raw literal in lockstep.
4727        // Byte-parity against the lifted constant on the `Period` half
4728        // closes the split — the paired OTP-canonical default now
4729        // migrates as one unit on any future axis change. Peer of the
4730        // sibling
4731        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4732        // byte-parity pin on the paired `MaxIntensity` half.
4733        assert_eq!(
4734            SupervisorSpec::default().restart_window(),
4735            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4736        );
4737    }
4738
4739    #[test]
4740    fn supervisor_estrategia_default_pins_otp_canonical_value() {
4741        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
4742        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
4743        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
4744        // canonical default, paired with the sibling
4745        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
4746        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
4747        // this constant is the strategy discriminator of on the same
4748        // OTP-canonical worker-supervisor default. Pinning the arm here
4749        // surfaces a future coherent rebrand of the paired triple (Elixir's
4750        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
4751        // intensity/period axes leaving this strategy arm untouched, an OTP
4752        // `rest_for_one` widening once the substrate discovers startup-
4753        // order-coupled child cohorts as the more common worker-supervisor
4754        // shape, a per-cluster overlay the operator pins through a future
4755        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
4756        // supervision-canary roadmap acknowledges) as a deliberate test
4757        // edit, not a silent contract migration. Peer of the sibling
4758        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
4759        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4760        // paired-half pins on the same OTP-canonical default.
4761        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
4762    }
4763
4764    #[test]
4765    fn restart_strategy_default_routes_through_lifted_default() {
4766        // Composition pin: the [`Default for RestartStrategy`] impl's
4767        // return arm must route through the substrate-canonical
4768        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
4769        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
4770        // an inline `Self::OneForOne` with no compile-time link back to
4771        // the shared OTP-canonical `one_for_one` strategy the paired
4772        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
4773        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
4774        // `.unwrap_or_default()` (now
4775        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
4776        // so a future rebrand of the OTP-canonical strategy default (an
4777        // OTP `rest_for_one` widening once the substrate discovers
4778        // startup-order-coupled child cohorts as the more common worker-
4779        // supervisor shape, a per-cluster overlay the operator pins
4780        // through a future `:estrategia-overrides` slot) would have had to
4781        // be threaded through the `Default` impl and the two peer routes
4782        // in lockstep or the three consumers would silently split. Byte-
4783        // parity against the lifted constant closes the split. Peer of
4784        // the sibling
4785        // [`default_max_restarts_helper_routes_through_lifted_default`] +
4786        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4787        // composition pins on the paired `MaxIntensity` + `Period` halves.
4788        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
4789    }
4790
4791    #[test]
4792    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
4793        // Composition pin: the [`Default for SupervisorSpec`] impl's
4794        // struct-literal `estrategia` field must route through the
4795        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
4796        // `pub const` (either directly, or via the
4797        // [`RestartStrategy::default`] impl that the sibling
4798        // `restart_strategy_default_routes_through_lifted_default` pin
4799        // already routes onto the constant). Structurally: every
4800        // `SupervisorSpec::default()` call must yield an `estrategia`
4801        // field byte-equal to the lifted constant (the three paired
4802        // defaults — the [`Default for RestartStrategy`] impl arm, the
4803        // struct-literal default arm here, and the
4804        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
4805        // silently split on any future default rebrand). Peer of the
4806        // sibling
4807        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4808        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4809        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
4810        // of the same `SupervisorSpec::default()` composed altitude.
4811        assert_eq!(
4812            SupervisorSpec::default().estrategia(),
4813            SUPERVISOR_ESTRATEGIA_DEFAULT,
4814        );
4815    }
4816
4817    #[test]
4818    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
4819        // Composition pin: the [`Default for SupervisorSpec`] impl must
4820        // route through the substrate-canonical
4821        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
4822        // rather than a re-hand-authored struct-literal cascade. Sharpens
4823        // the sibling per-arm
4824        // `supervisor_spec_default_*_routes_through_lifted_default` pins
4825        // from a per-field lift into a whole-struct one-source-of-truth
4826        // pin — the derived-until-now [`Default::default`] and the
4827        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
4828        // construction, not by coincidence.
4829        //
4830        // A future extension of the OTP-canonical baseline (a fifth
4831        // `restart_intensity` field the Erlang/OTP `#supervisor` record
4832        // grows, a per-child-cohort split of the `restart_window` /
4833        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
4834        // CR materializer's admission-time overlay pass) reaches both
4835        // paths through exactly one edit on
4836        // [`SupervisorSpec::otp_canonical`] — the derived path could
4837        // silently disagree with the constructor's shape on any new
4838        // field whose [`Default::default`] resolves to a different arm
4839        // than the OTP-canonical baseline the constructor names, while
4840        // this delegated impl reaches the constructor directly and
4841        // picks up every future extension by construction.
4842        //
4843        // Fourth peer on the M2 / M3 typed-slot-spec
4844        // [`Default`]-through-const-ctor fold family — sibling of the
4845        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
4846        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
4847        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
4848        // (91641a4), and [`crate::BehaviorSpec`]
4849        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
4850        // per-`Option`-only-typed-slot folds — extended here onto the
4851        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
4852        // is not "everything `None`" but the Erlang/OTP-canonical
4853        // `{one_for_one, 5, 60}` worker-supervisor triple.
4854        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
4855    }
4856
4857    #[test]
4858    fn supervisor_spec_otp_canonical_byte_equals_default() {
4859        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
4860        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
4861        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
4862        // pin already asserts against the [`Default::default`] path.
4863        // Sharpens the pair-invariant into a per-constructor pin so a
4864        // future extension of [`SupervisorSpec`] with a fifth field
4865        // whose OTP-canonical shape is non-`Default::default`-equivalent
4866        // trips at caixa-core test time rather than at a downstream
4867        // consumer that composed [`SupervisorSpec::otp_canonical`] with
4868        // [`SupervisorSpec::validate`] as its "canonical baseline
4869        // seed".
4870        let canonical = SupervisorSpec::otp_canonical();
4871        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
4872        assert_eq!(canonical.max_restarts, 5);
4873        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
4874        assert!(canonical.children.is_empty());
4875    }
4876
4877    #[test]
4878    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
4879        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
4880        // remain callable from a `const`-bound position so downstream
4881        // `const`-context callers wanting a canonical OTP-baseline seed
4882        // can construct one at compile time without runtime dispatch on
4883        // the derived [`Default::default`]. Peer of the sibling
4884        // `pub const fn` [`crate::LimitsSpec::empty`] /
4885        // [`crate::aplicacao::MeshPolicy::empty`] /
4886        // [`crate::BehaviorSpec::empty`] constructors on the sibling
4887        // typed-slot-spec `pub const fn` axis. If a future edit breaks
4888        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
4889        // (a non-`const` field-default helper, a non-`const`-stable
4890        // container type promotion), this evaluation fails at
4891        // build time on this file rather than at a downstream
4892        // `const`-context call site.
4893        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
4894        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
4895        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
4896        assert_eq!(
4897            CANONICAL.restart_window,
4898            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4899        );
4900        assert!(CANONICAL.children.is_empty());
4901    }
4902
4903    #[test]
4904    fn supervisor_child_restart_default_pins_otp_canonical_value() {
4905        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
4906        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
4907        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
4908        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
4909        // half of the same OTP-shape supervisor-tree default set whose
4910        // per-`:supervisor` halves the sibling
4911        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
4912        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
4913        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
4914        // arm here surfaces a future rebrand of the per-child default (an
4915        // OTP-`transient` widening once the substrate discovers clean-
4916        // completion-aware children as the more common child shape, a
4917        // per-cluster overlay the operator pins through a future
4918        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
4919        // supervision-canary roadmap acknowledges) as a deliberate test
4920        // edit, not a silent contract migration. Peer of the sibling
4921        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
4922        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
4923        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4924        // value pins on the per-`:supervisor` halves.
4925        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
4926    }
4927
4928    #[test]
4929    fn restart_policy_default_routes_through_lifted_default() {
4930        // Composition pin: the [`Default for RestartPolicy`] impl's return
4931        // arm must route through the substrate-canonical
4932        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
4933        // than a raw `Self::Permanent` arm. Prior to the lift the impl
4934        // carried an inline `Self::Permanent` with no compile-time link
4935        // back to the OTP-shape supervisor-tree default set whose three
4936        // per-`:supervisor` halves already rode through lifted constants
4937        // — so a future coherent rebrand of the set would have had to
4938        // migrate three halves through typed constants and this fourth
4939        // through a raw enum arm in lockstep or the supervisor-level and
4940        // child-level defaults would silently drift apart. Byte-parity
4941        // against the lifted constant closes the split. Peer of the
4942        // sibling
4943        // [`restart_strategy_default_routes_through_lifted_default`]
4944        // composition pin on the per-`:supervisor` `:estrategia` axis.
4945        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
4946    }
4947
4948    #[test]
4949    fn child_spec_serde_default_restart_routes_through_lifted_default() {
4950        // Composition pin: the serde-side `#[serde(default)]` on
4951        // [`ChildSpec::restart`] — the wire-format author-omitted
4952        // `:children :restart` arm — must resolve onto the substrate-
4953        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
4954        // (via the [`Default for RestartPolicy`] impl the sibling
4955        // `restart_policy_default_routes_through_lifted_default` pin
4956        // already routes onto the constant). Structurally: a `ChildSpec`
4957        // deserialized from a payload that omits the `restart` key must
4958        // yield a `restart` field byte-equal to the lifted constant, so
4959        // the wire-format author-omitted arm and the
4960        // [`RestartPolicy::default`] impl arm cannot silently split on any
4961        // future default rebrand. Peer of the sibling
4962        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
4963        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4964        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4965        // byte-parity pins on the per-`:supervisor` halves of the same
4966        // author-omitted-slot resolution surface.
4967        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
4968            .expect("ChildSpec must deserialize with the restart key omitted");
4969        assert_eq!(
4970            omitted.restart(),
4971            SUPERVISOR_CHILD_RESTART_DEFAULT,
4972            "an author-omitted :children :restart slot must degrade onto \
4973             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
4974             {:?}, expected {:?})",
4975            omitted.restart(),
4976            SUPERVISOR_CHILD_RESTART_DEFAULT,
4977        );
4978    }
4979
4980    #[test]
4981    fn supervisor_max_restarts_cap_pins_canonical_value() {
4982        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
4983        // 1000 — the same ceiling the peer
4984        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
4985        // `:politicas :circuit-breaker :max-failures` axis (both are
4986        // "trip the next-higher protection layer after N events in a
4987        // rolling window" counters with identical
4988        // degenerate-at-the-high-end shape; uniform top edge so the
4989        // M4 CR materializers and the wasm-operator reconciler reach
4990        // for either field knowing the value is in `1..=1000`). Two
4991        // orders of magnitude above every documented Erlang/OTP /
4992        // Elixir / Riak Core / RabbitMQ production-playbook
4993        // recommendation band and below the clearly-pathological
4994        // "effectively no escalation" floor (10_000, 100_000,
4995        // u32::MAX). Pinning the literal value here surfaces a future
4996        // drift (a relaxation to 10_000, a tightening to 100) as a
4997        // deliberate test edit, not a silent contract narrowing.
4998        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
4999    }
5000
5001    #[test]
5002    fn validate_rejects_empty_child_name() {
5003        let s = SupervisorSpec {
5004            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5005            ..SupervisorSpec::default()
5006        };
5007        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
5008    }
5009
5010    #[test]
5011    fn validate_rejects_empty_child_version() {
5012        let s = SupervisorSpec {
5013            children: vec![child("w", "", RestartPolicy::Permanent)],
5014            ..SupervisorSpec::default()
5015        };
5016        assert!(matches!(
5017            s.validate().unwrap_err(),
5018            SupervisorError::EmptyChildVersion { .. }
5019        ));
5020    }
5021
5022    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
5023
5024    #[test]
5025    fn validate_rejects_invalid_child_versao_requirement() {
5026        // The fail-before-pass-after pin: a non-empty but malformed
5027        // semver requirement (`"^bad-version"`) silently passed
5028        // `validate()` on every pre-gate codebase because the prior
5029        // shape only refused the empty string. The parse failure
5030        // surfaced far downstream at lacre-resolve time with a
5031        // `semver::Error` that didn't name which `:children` entry
5032        // carried the typo. The new gate moves the check to caixa-build
5033        // time at the source caixa.lisp — the third `:versao` typed
5034        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
5035        // structural parity.
5036        let s = SupervisorSpec {
5037            children: vec![
5038                child("worker", "^0.1", RestartPolicy::Permanent),
5039                child("cache", "^bad-version", RestartPolicy::Transient),
5040            ],
5041            ..SupervisorSpec::default()
5042        };
5043        let err = s.validate().unwrap_err();
5044        assert!(
5045            matches!(
5046                err,
5047                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5048                    if caixa == "cache" && versao == "^bad-version"
5049            ),
5050            "got {err:?}"
5051        );
5052    }
5053
5054    #[test]
5055    fn validate_rejects_child_versao_with_double_caret_typo() {
5056        // `"^^0.1"` is the canonical doubled-caret typo — looks
5057        // Cargo-shaped on first glance but fails the parser because
5058        // semver doesn't accept stacked operators. Pin this
5059        // adjacent-shape footgun explicitly so a future relaxation that
5060        // accepts "looks-canonical-but-isn't" forms surfaces here.
5061        let s = SupervisorSpec {
5062            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
5063            ..SupervisorSpec::default()
5064        };
5065        let err = s.validate().unwrap_err();
5066        assert!(
5067            matches!(
5068                err,
5069                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5070                    if caixa == "worker" && versao == "^^0.1"
5071            ),
5072            "got {err:?}"
5073        );
5074    }
5075
5076    #[test]
5077    fn validate_rejects_child_versao_with_v_prefixed_tag() {
5078        // `"v0.1"` is the canonical "git-tag-shape leaking into the
5079        // semver requirement slot" typo — an author copies the
5080        // publish-side git-tag string verbatim into `:versao`, but
5081        // Cargo's semver parser rejects the leading `v`. Same
5082        // adjacent-shape footgun pinned for `:membros :versao`
5083        // (9888b13).
5084        let s = SupervisorSpec {
5085            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
5086            ..SupervisorSpec::default()
5087        };
5088        let err = s.validate().unwrap_err();
5089        assert!(
5090            matches!(
5091                err,
5092                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5093                    if caixa == "worker" && versao == "v0.1"
5094            ),
5095            "got {err:?}"
5096        );
5097    }
5098
5099    #[test]
5100    fn validate_accepts_canonical_child_versao_forms() {
5101        // The Cargo-shaped requirement forms `:deps :versao` and
5102        // `:membros :versao` already accept via
5103        // `crate::parse_requirement` must pass the children gate
5104        // without re-validating at the resolver layer. Pin every leg so
5105        // a future tightening of the canonical set surfaces here as a
5106        // test failure.
5107        for form in [
5108            "^0.1",      // caret — minor-range pin (the most common shape)
5109            "~0.1.2",    // tilde — patch-range pin
5110            "0.1.0",     // exact — single-version pin
5111            "*",         // wildcard — any version (semver::VersionReq::STAR)
5112            ">=0.1, <2", // multi-range — comma-separated comparators
5113        ] {
5114            let s = SupervisorSpec {
5115                children: vec![child("worker", form, RestartPolicy::Permanent)],
5116                ..SupervisorSpec::default()
5117            };
5118            s.validate()
5119                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5120        }
5121    }
5122
5123    #[test]
5124    fn child_versao_empty_takes_precedence_over_invalid() {
5125        // Order pin: the existing `EmptyChildVersion` diagnostic (which
5126        // doesn't try to parse) fires before the new
5127        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
5128        // `:versao` keeps its narrower error message —
5129        // `parse_requirement` would also reject `""`, but the
5130        // empty-string arm is the more self-locating diagnostic for the
5131        // author. Same ordering discipline as
5132        // `membro_versao_empty_takes_precedence_over_invalid` in
5133        // aplicacao.rs.
5134        let s = SupervisorSpec {
5135            children: vec![child("worker", "", RestartPolicy::Permanent)],
5136            ..SupervisorSpec::default()
5137        };
5138        let err = s.validate().unwrap_err();
5139        assert!(
5140            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
5141            "got {err:?}"
5142        );
5143    }
5144
5145    #[test]
5146    fn child_versao_invalid_fires_before_duplicate_check() {
5147        // Order pin: a malformed requirement on a non-duplicate entry
5148        // surfaces *its own* diagnostic (which names the offending
5149        // `:versao` string), even when a later entry would otherwise
5150        // collapse onto an earlier name. The per-entry shape gate runs
5151        // inline before the duplicate-key insert — parallel to
5152        // `membro_versao_invalid_fires_before_duplicate_check` in
5153        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
5154        let s = SupervisorSpec {
5155            children: vec![
5156                child("worker", "^bad", RestartPolicy::Permanent),
5157                child("cache", "^0.1", RestartPolicy::Transient),
5158                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5159            ],
5160            ..SupervisorSpec::default()
5161        };
5162        let err = s.validate().unwrap_err();
5163        assert!(
5164            matches!(
5165                err,
5166                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
5167            ),
5168            "got {err:?}"
5169        );
5170    }
5171
5172    #[test]
5173    fn child_versao_invalid_diagnostic_carries_offending_versao() {
5174        // The diagnostic-shape pin: the error names the offending
5175        // `:versao` value verbatim so the author can grep their
5176        // caixa.lisp without re-running the build, and carries a
5177        // non-empty `reason` from `semver::VersionReq::parse` so the
5178        // parser's own wording flows through to the diagnostic.
5179        let s = SupervisorSpec {
5180            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
5181            ..SupervisorSpec::default()
5182        };
5183        let err = s.validate().unwrap_err();
5184        let SupervisorError::ChildVersaoInvalid {
5185            caixa,
5186            versao,
5187            reason,
5188        } = err
5189        else {
5190            panic!("expected ChildVersaoInvalid, got other variant");
5191        };
5192        assert_eq!(caixa, "worker");
5193        assert_eq!(versao, "not-a-req");
5194        assert!(
5195            !reason.is_empty(),
5196            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
5197        );
5198    }
5199
5200    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
5201
5202    #[test]
5203    fn validate_rejects_child_caixa_with_uppercase() {
5204        // The canonical "I copied the Servico's display name verbatim"
5205        // typo — child caixa names are lowercase per K8s DNS-1123 label
5206        // rule. The diagnostic names the offending name and suggests the
5207        // lower-cased fix in one edit, mirroring the
5208        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
5209        let s = SupervisorSpec {
5210            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
5211            ..SupervisorSpec::default()
5212        };
5213        let err = s.validate().unwrap_err();
5214        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5215            panic!("expected ChildCaixaInvalid, got other variant");
5216        };
5217        assert_eq!(caixa, "Worker");
5218        assert!(
5219            reason.contains("uppercase"),
5220            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
5221        );
5222        assert!(
5223            reason.contains("\"worker\""),
5224            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
5225        );
5226    }
5227
5228    #[test]
5229    fn validate_rejects_child_caixa_with_underscore() {
5230        // The canonical "I'm thinking of a Python module / Postgres
5231        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
5232        // label schema. K8s rejects `metadata.name: my_worker` at
5233        // admission time with an opaque `field is invalid` (no source-
5234        // citing diagnostic). The gate moves it to caixa-build time.
5235        let s = SupervisorSpec {
5236            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
5237            ..SupervisorSpec::default()
5238        };
5239        let err = s.validate().unwrap_err();
5240        assert!(
5241            matches!(
5242                err,
5243                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5244                    if caixa == "my_worker" && reason.contains('_')
5245            ),
5246            "got {err:?}"
5247        );
5248    }
5249
5250    #[test]
5251    fn validate_rejects_child_caixa_with_dot() {
5252        // A `:children :caixa` entry is a single DNS-1123 label, not a
5253        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
5254        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
5255        // (3f9d7a0) on the peer name axis.
5256        let s = SupervisorSpec {
5257            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
5258            ..SupervisorSpec::default()
5259        };
5260        let err = s.validate().unwrap_err();
5261        assert!(
5262            matches!(
5263                err,
5264                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5265                    if caixa == "team.worker" && reason.contains('.')
5266            ),
5267            "got {err:?}"
5268        );
5269    }
5270
5271    #[test]
5272    fn validate_rejects_child_caixa_with_leading_hyphen() {
5273        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
5274        // with an alphanumeric. The K8s apiserver rejects `-worker`
5275        // outright; the renderer would emit a `metadata.name: "-worker"`
5276        // that fails admission far from the source caixa.lisp.
5277        let s = SupervisorSpec {
5278            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
5279            ..SupervisorSpec::default()
5280        };
5281        let err = s.validate().unwrap_err();
5282        assert!(
5283            matches!(
5284                err,
5285                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5286                    if caixa == "-worker" && reason.contains("start and end")
5287            ),
5288            "got {err:?}"
5289        );
5290    }
5291
5292    #[test]
5293    fn validate_rejects_child_caixa_with_trailing_hyphen() {
5294        // The symmetric arm of the boundary rule. Pin separately so
5295        // both ends of the label are covered against a future relaxation
5296        // that only checks one boundary.
5297        let s = SupervisorSpec {
5298            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
5299            ..SupervisorSpec::default()
5300        };
5301        let err = s.validate().unwrap_err();
5302        assert!(
5303            matches!(
5304                err,
5305                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5306                    if caixa == "worker-"
5307            ),
5308            "got {err:?}"
5309        );
5310    }
5311
5312    #[test]
5313    fn validate_rejects_child_caixa_with_unicode() {
5314        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
5315        // (`xn--…`) by the author before it reaches K8s. The byte-by-
5316        // byte ASCII validity check rejects multi-byte UTF-8 sequences
5317        // by the first byte that fails the `[a-z0-9-]` predicate.
5318        let s = SupervisorSpec {
5319            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
5320            ..SupervisorSpec::default()
5321        };
5322        let err = s.validate().unwrap_err();
5323        assert!(
5324            matches!(
5325                err,
5326                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5327                    if caixa == "café"
5328            ),
5329            "got {err:?}"
5330        );
5331    }
5332
5333    #[test]
5334    fn validate_rejects_child_caixa_with_whitespace() {
5335        // Whitespace is the canonical "I pasted from a sketch / doc"
5336        // footgun. The apiserver rejects every `metadata.name` value
5337        // carrying whitespace; pin the gate fires at the right boundary.
5338        let s = SupervisorSpec {
5339            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
5340            ..SupervisorSpec::default()
5341        };
5342        let err = s.validate().unwrap_err();
5343        assert!(
5344            matches!(
5345                err,
5346                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5347                    if caixa == "my worker"
5348            ),
5349            "got {err:?}"
5350        );
5351    }
5352
5353    #[test]
5354    fn validate_rejects_child_caixa_too_long() {
5355        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
5356        // 63 bytes; the K8s apiserver rejects every `metadata.name`
5357        // axis over the limit at admission time. The diagnostic names
5358        // both the cap and the actual length so the author can shorten
5359        // in one edit, mirroring `rejects_membro_caixa_too_long`
5360        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
5361        let too_long = "a".repeat(64);
5362        let s = SupervisorSpec {
5363            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
5364            ..SupervisorSpec::default()
5365        };
5366        let err = s.validate().unwrap_err();
5367        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5368            panic!("expected ChildCaixaInvalid, got other variant");
5369        };
5370        assert_eq!(caixa, too_long);
5371        assert!(
5372            reason.contains("63"),
5373            "diagnostic must name the 63-byte cap (got: {reason:?})"
5374        );
5375        assert!(
5376            reason.contains("64"),
5377            "diagnostic must name the actual length (got: {reason:?})"
5378        );
5379    }
5380
5381    #[test]
5382    fn child_caixa_max_length_validates() {
5383        // The 63-byte boundary control pin — exactly-at-the-cap is
5384        // accepted, mirroring `membro_caixa_max_length_validates`
5385        // (3f9d7a0) and `placement_cluster_max_length_validates`
5386        // (6cbb900). Pinned separately so a future off-by-one tightening
5387        // surfaces here.
5388        let max_label = "a".repeat(63);
5389        let s = SupervisorSpec {
5390            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
5391            ..SupervisorSpec::default()
5392        };
5393        s.validate().unwrap();
5394    }
5395
5396    #[test]
5397    fn validate_accepts_canonical_child_caixa_forms() {
5398        // The realistic shapes a supervised child's `:caixa` carries —
5399        // single-word `worker`, version-suffixed `cache-v2`, single-char
5400        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
5401        // `payment-retry`, all-digit `0`. Pin every leg so a future
5402        // tightening (e.g. requiring a leading lowercase letter) surfaces
5403        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
5404        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
5405        // (6cbb900).
5406        for form in [
5407            "worker",
5408            "cache-v2",
5409            "a",
5410            "db",
5411            "2-pool",
5412            "payment-retry",
5413            "0",
5414        ] {
5415            let s = SupervisorSpec {
5416                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
5417                ..SupervisorSpec::default()
5418            };
5419            s.validate()
5420                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5421        }
5422    }
5423
5424    #[test]
5425    fn child_caixa_empty_takes_precedence_over_invalid() {
5426        // Order pin: the existing `EmptyChildName` diagnostic (which
5427        // doesn't try to parse the DNS-1123 shape) fires before the new
5428        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
5429        // its narrower error message — `is_dns_1123_label` would reject
5430        // the empty string too (boundary check on the first byte), but
5431        // the empty-string arm is the more self-locating diagnostic for
5432        // the author. Same ordering discipline as
5433        // `membro_caixa_empty_takes_precedence_over_invalid` in
5434        // aplicacao.rs.
5435        let s = SupervisorSpec {
5436            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5437            ..SupervisorSpec::default()
5438        };
5439        let err = s.validate().unwrap_err();
5440        assert_eq!(err, SupervisorError::EmptyChildName);
5441    }
5442
5443    #[test]
5444    fn child_caixa_invalid_fires_before_versao_check() {
5445        // Order pin: the per-axis shape gate runs inline before the
5446        // per-entry versao check, so a malformed `:caixa` on an entry
5447        // whose `:versao` would also fail surfaces the more self-
5448        // locating name-axis diagnostic first. Parallel to
5449        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
5450        // and `placement_cluster_invalid_fires_before_duplicate_check`
5451        // (6cbb900).
5452        let s = SupervisorSpec {
5453            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
5454            ..SupervisorSpec::default()
5455        };
5456        let err = s.validate().unwrap_err();
5457        assert!(
5458            matches!(
5459                err,
5460                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
5461            ),
5462            "got {err:?}"
5463        );
5464    }
5465
5466    #[test]
5467    fn child_caixa_invalid_fires_before_duplicate_check() {
5468        // Order pin: a malformed name on a non-duplicate entry surfaces
5469        // its own diagnostic, even when a later entry would otherwise
5470        // collapse onto an earlier name. The per-entry shape gate runs
5471        // inline before the duplicate-key HashSet insert, mirroring
5472        // `placement_cluster_invalid_fires_before_duplicate_check`
5473        // (6cbb900).
5474        let s = SupervisorSpec {
5475            children: vec![
5476                child("Worker", "^0.1", RestartPolicy::Permanent),
5477                child("cache", "^0.1", RestartPolicy::Transient),
5478                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5479            ],
5480            ..SupervisorSpec::default()
5481        };
5482        let err = s.validate().unwrap_err();
5483        assert!(
5484            matches!(
5485                err,
5486                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
5487            ),
5488            "got {err:?}"
5489        );
5490    }
5491
5492    #[test]
5493    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
5494        // The diagnostic-shape pin: the error names the offending
5495        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
5496        // the author can grep their caixa.lisp without re-running the
5497        // build. Mirrors the diagnostic-shape sweep on every prior
5498        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
5499        let s = SupervisorSpec {
5500            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
5501            ..SupervisorSpec::default()
5502        };
5503        let err = s.validate().unwrap_err();
5504        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5505            panic!("expected ChildCaixaInvalid, got other variant");
5506        };
5507        assert_eq!(caixa, "My_Worker");
5508        assert!(
5509            !reason.is_empty(),
5510            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
5511        );
5512    }
5513
5514    // ── value-shape: zero restart_window + duplicate child names ──────────
5515
5516    #[test]
5517    fn validate_accepts_none_restart_window() {
5518        // Omitted `:restart-window` is the "never reset" sentinel —
5519        // valid by design. Mirrors :limits axes where None = unbounded.
5520        let s = SupervisorSpec {
5521            restart_window: None,
5522            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5523            ..SupervisorSpec::default()
5524        };
5525        s.validate().unwrap();
5526    }
5527
5528    #[test]
5529    fn validate_rejects_zero_restart_window() {
5530        // Same "0 means the opposite of what you think" footgun closed
5531        // for :politicas :timeout (Envoy treats 0s as infinite) and
5532        // :limits :wall-clock (wasmtime traps before the call starts).
5533        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
5534        let s = SupervisorSpec {
5535            restart_window: Some(Duration::ZERO),
5536            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5537            ..SupervisorSpec::default()
5538        };
5539        assert_eq!(
5540            s.validate().unwrap_err(),
5541            SupervisorError::RestartWindowZero
5542        );
5543    }
5544
5545    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
5546    //
5547    // The fourth (and last) typed-`Duration` axis in caixa-core to get
5548    // the integer-millisecond canonical-form gate — peer with
5549    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
5550    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
5551    // path is already gated at the shared codec layer (see
5552    // `restart_window_serde_rejects_fractional_seconds`); this arm
5553    // closes the programmatic-struct-literal path the codec gate can't
5554    // see.
5555
5556    #[test]
5557    fn validate_rejects_sub_millisecond_restart_window() {
5558        // The fail-before-pass-after pin: a programmatic
5559        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
5560        // `validate` on every pre-gate codebase, then truncated to
5561        // `as_millis() == 1` on first serialize — the shared codec
5562        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
5563        // 1_000_000 ns, the typed `restart_window` no longer matches
5564        // its rendered form.
5565        let s = SupervisorSpec {
5566            restart_window: Some(Duration::from_micros(1500)),
5567            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5568            ..SupervisorSpec::default()
5569        };
5570        match s.validate().unwrap_err() {
5571            SupervisorError::RestartWindowNotCanonical { window } => {
5572                assert_eq!(window, Duration::from_micros(1500));
5573            }
5574            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5575        }
5576    }
5577
5578    #[test]
5579    fn validate_rejects_one_nanosecond_restart_window() {
5580        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
5581        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
5582        // so the shared codec emits the literal `"0s"` — the next
5583        // serde round-trip would parse back to `Duration::ZERO`, which
5584        // the `RestartWindowZero` arm then rejects on re-validate. The
5585        // canonical-form gate at this layer surfaces a self-locating
5586        // diagnostic naming the offending Duration verbatim rather
5587        // than a downstream `RestartWindowZero` whose remediation
5588        // points at omitting the slot.
5589        let s = SupervisorSpec {
5590            restart_window: Some(Duration::from_nanos(1)),
5591            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5592            ..SupervisorSpec::default()
5593        };
5594        match s.validate().unwrap_err() {
5595            SupervisorError::RestartWindowNotCanonical { window } => {
5596                assert_eq!(window, Duration::from_nanos(1));
5597            }
5598            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5599        }
5600    }
5601
5602    #[test]
5603    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
5604        // The 1-ns-past-1ms boundary case: a `Duration` carrying
5605        // 1_000_001 ns is structurally past the integer-ms granularity
5606        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
5607        // trip would truncate to `1ms` and the consumer would observe
5608        // a 1-ns drift on every emit. Same boundary the peer
5609        // `validate_rejects_nanosecond_past_canonical_boundary` test
5610        // in limits.rs pins for the `:limits :wall-clock` axis.
5611        let w = Duration::from_nanos(1_000_001);
5612        let s = SupervisorSpec {
5613            restart_window: Some(w),
5614            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5615            ..SupervisorSpec::default()
5616        };
5617        assert_eq!(
5618            s.validate().unwrap_err(),
5619            SupervisorError::RestartWindowNotCanonical { window: w }
5620        );
5621    }
5622
5623    #[test]
5624    fn validate_accepts_integer_millisecond_restart_window_values() {
5625        // The positive-control sweep: every `Duration` the shared
5626        // codec can round-trip losslessly — the canonical
5627        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
5628        // pair emits and accepts — passes `validate` without
5629        // surfacing the new canonical-form arm. Mirrors
5630        // `validate_accepts_integer_millisecond_wall_clock_values` on
5631        // the sibling `:limits :wall-clock` axis.
5632        for w in [
5633            Duration::from_millis(1),
5634            Duration::from_millis(500),
5635            Duration::from_millis(1500),
5636            Duration::from_secs(1),
5637            Duration::from_secs(30),
5638            Duration::from_secs(60),
5639            Duration::from_secs(120),
5640            Duration::from_secs(3600),
5641        ] {
5642            let s = SupervisorSpec {
5643                restart_window: Some(w),
5644                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5645                ..SupervisorSpec::default()
5646            };
5647            s.validate()
5648                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
5649        }
5650    }
5651
5652    #[test]
5653    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
5654        // Cross-arm ordering pin: `Duration::ZERO` has
5655        // `subsec_nanos() == 0` and would otherwise pass the
5656        // canonical-form arm — the zero-floor arm must fire first so
5657        // the more self-locating `RestartWindowZero` diagnostic (with
5658        // its omit-axis remediation directly named) leads. Same
5659        // posture every peer zero-then-shape gate uses
5660        // (`WallClockZero` → `WallClockNotCanonical`,
5661        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
5662        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
5663        let s = SupervisorSpec {
5664            restart_window: Some(Duration::ZERO),
5665            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5666            ..SupervisorSpec::default()
5667        };
5668        assert_eq!(
5669            s.validate().unwrap_err(),
5670            SupervisorError::RestartWindowZero
5671        );
5672    }
5673
5674    #[test]
5675    fn restart_window_canonical_diagnostic_carries_offending_duration() {
5676        // Diagnostic-shape pin: the canonical-form arm names the
5677        // offending `Duration` verbatim so the author's grep lands on
5678        // the field's value, not a generic "duration not canonical"
5679        // message. Same shape every other typed-canonical-form arm
5680        // on this surface carries (`WallClockNotCanonical` carries
5681        // the offending `Duration` verbatim,
5682        // `PolicyTimeoutNotCanonical` carries the offending
5683        // `Duration` verbatim).
5684        let w = Duration::from_micros(500);
5685        let s = SupervisorSpec {
5686            restart_window: Some(w),
5687            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5688            ..SupervisorSpec::default()
5689        };
5690        let err = s.validate().unwrap_err();
5691        let msg = err.to_string();
5692        assert!(
5693            msg.contains("500"),
5694            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
5695        );
5696        assert!(
5697            msg.contains("sub-millisecond"),
5698            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
5699        );
5700    }
5701
5702    #[test]
5703    fn restart_window_validated_value_round_trips_through_codec() {
5704        // The structural property the canonical-ms gate enforces:
5705        // every `SupervisorSpec::restart_window` past
5706        // `SupervisorSpec::validate` round-trips losslessly through
5707        // the shared duration codec (serialize → string →
5708        // deserialize → equal value). Pin this end-to-end so a future
5709        // change to either side (the validate gate's accepted
5710        // granularity, the codec's parse/render unit set) that breaks
5711        // the alignment surfaces here. Peer of
5712        // `wall_clock_validated_value_round_trips_through_codec` on
5713        // the sibling `:limits :wall-clock` axis.
5714        for w in [
5715            Duration::from_millis(1),
5716            Duration::from_millis(1500),
5717            Duration::from_secs(30),
5718            Duration::from_secs(3600),
5719        ] {
5720            let s = SupervisorSpec {
5721                restart_window: Some(w),
5722                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5723                ..SupervisorSpec::default()
5724            };
5725            s.validate().unwrap();
5726            let json = serde_json::to_string(&s).unwrap();
5727            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5728            assert_eq!(back.restart_window, Some(w));
5729        }
5730    }
5731
5732    // ── value-shape: upper cap on :restart-window ─────────────────────────
5733    //
5734    // The fourth (and last) typed-`Duration` axis in caixa-core to get
5735    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
5736    // `:politicas :timeout` (2e8ee7e), and `:politicas
5737    // :circuit-breaker :window` (379a814). Brackets the typed
5738    // `:restart-window` axis structurally: every validated value lies
5739    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
5740    // granularity, closing the
5741    // rolling-window-degenerates-to-lifetime-counter footgun the prior
5742    // zero-floor-and-canonical-form-only checks left open.
5743
5744    #[test]
5745    fn validate_rejects_restart_window_above_cap() {
5746        // The fail-before-pass-after pin: 3601s = 1h + 1s is
5747        // structurally one canonical-tick past the
5748        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
5749        // integer-millisecond magnitude the canonical-form arm above
5750        // accepts cleanly, that the shared duration codec round-trips
5751        // losslessly as `"3601s"`, and that silently passed validate on
5752        // every pre-gate codebase because the typed slot's only checks
5753        // were the zero-floor and canonical-form arms. The runtime
5754        // substrate consuming the value (Erlang/OTP's MaxIntensity/
5755        // Period reconciler, the future wasm-operator's per-supervisor
5756        // restart-intensity counter) reaches for a `Duration` so long
5757        // no realistic restart-recovery pattern resets the counter,
5758        // far from the source caixa.lisp.
5759        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5760        let s = SupervisorSpec {
5761            restart_window: Some(w),
5762            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5763            ..SupervisorSpec::default()
5764        };
5765        assert_eq!(
5766            s.validate().unwrap_err(),
5767            SupervisorError::RestartWindowExceedsCap { window: w }
5768        );
5769    }
5770
5771    #[test]
5772    fn validate_rejects_restart_window_one_millisecond_above_cap() {
5773        // Boundary case: exactly 1ms past the cap (the granularity the
5774        // canonical-form gate enforces). Catches a future "strictly
5775        // less than" half-measure and pins the diagnostic to name the
5776        // offending `Duration` verbatim. Peer of
5777        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
5778        // `rejects_policy_timeout_one_millisecond_above_cap` /
5779        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
5780        // on the sibling typed-`Duration` axes' top edges.
5781        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
5782        let s = SupervisorSpec {
5783            restart_window: Some(w),
5784            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5785            ..SupervisorSpec::default()
5786        };
5787        assert_eq!(
5788            s.validate().unwrap_err(),
5789            SupervisorError::RestartWindowExceedsCap { window: w }
5790        );
5791    }
5792
5793    #[test]
5794    fn validate_rejects_restart_window_far_above_cap() {
5795        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
5796        // `(:restart-window "7d")`, or any "I want a lifetime counter
5797        // but wrote a `<integer>h` magnitude anyway" typo — values the
5798        // canonical-form arm accepts as integer-millisecond magnitudes,
5799        // the codec round-trips losslessly through serde, but the
5800        // operator's `MaxIntensity / Period` reconciler cannot honor
5801        // as a meaningful rolling window. Until this gate landed
5802        // validate accepted them. Pin the common above-cap values (24h,
5803        // 7d, ~11.5d) so a future relaxation that drops the upper bound
5804        // surfaces here.
5805        for w in [
5806            Duration::from_secs(86_400),    // 24h
5807            Duration::from_secs(604_800),   // 7d
5808            Duration::from_secs(1_000_000), // ~11.5 days
5809        ] {
5810            let s = SupervisorSpec {
5811                restart_window: Some(w),
5812                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5813                ..SupervisorSpec::default()
5814            };
5815            assert_eq!(
5816                s.validate().unwrap_err(),
5817                SupervisorError::RestartWindowExceedsCap { window: w }
5818            );
5819        }
5820    }
5821
5822    #[test]
5823    fn validate_accepts_restart_window_at_cap() {
5824        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
5825        // (1h) — must validate. The cap is inclusive on the top edge,
5826        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
5827        // [`crate::POLICY_TIMEOUT_MAX`] /
5828        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
5829        // capped axes. Pin the boundary explicitly so a future
5830        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
5831        // instead of `>`) surfaces here as a test failure rather than a
5832        // silent contract narrowing.
5833        let s = SupervisorSpec {
5834            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5835            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5836            ..SupervisorSpec::default()
5837        };
5838        s.validate()
5839            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
5840    }
5841
5842    #[test]
5843    fn validate_accepts_restart_window_typical_values() {
5844        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
5845        // per-supervisor production-playbook band positive-control
5846        // sweep — every value Learn You Some Erlang's `{intensity, 5,
5847        // 60}` worker-supervisor `Period = 60s` default, Elixir's
5848        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
5849        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
5850        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
5851        // default recommend (5s..=300s) must pass, plus a sweep
5852        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
5853        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
5854        // on the sibling `:limits :wall-clock` axis.
5855        for w in [
5856            Duration::from_millis(1),
5857            Duration::from_millis(500),
5858            Duration::from_secs(1),
5859            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
5860            Duration::from_secs(10), // Riak Core lower
5861            Duration::from_secs(30),
5862            Duration::from_secs(60),  // Learn You Some Erlang default
5863            Duration::from_secs(120), // OTP supervisor MaxT typical
5864            Duration::from_secs(300), // Riak Core upper
5865            Duration::from_secs(900), // 15m
5866            Duration::from_secs(1800),
5867            Duration::from_secs(3600), // exactly 1h, the cap
5868        ] {
5869            let s = SupervisorSpec {
5870                restart_window: Some(w),
5871                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5872                ..SupervisorSpec::default()
5873            };
5874            s.validate()
5875                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
5876        }
5877    }
5878
5879    #[test]
5880    fn restart_window_zero_takes_precedence_over_cap() {
5881        // The cross-arm ordering pin: `Duration::ZERO` is structurally
5882        // outside both `>= 1ms` (zero-floor) and `<=
5883        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
5884        // diagnostic is the more self-locating one (it directly names
5885        // the omit-axis remediation), so the validate gate must fire
5886        // on zero first. Same shape every other zero-then-cap ordering
5887        // on this surface uses (`WallClockZero` then
5888        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
5889        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
5890        // `PolicyBreakerWindowExceedsCap`).
5891        let s = SupervisorSpec {
5892            restart_window: Some(Duration::ZERO),
5893            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5894            ..SupervisorSpec::default()
5895        };
5896        assert_eq!(
5897            s.validate().unwrap_err(),
5898            SupervisorError::RestartWindowZero,
5899            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
5900        );
5901    }
5902
5903    #[test]
5904    fn restart_window_canonical_takes_precedence_over_cap() {
5905        // The cross-arm ordering pin: a `Duration` that is *both*
5906        // sub-millisecond (non-canonical-form) and structurally above
5907        // the cap surfaces the canonical-form diagnostic first,
5908        // because the round-trip-shape break is the more fundamental
5909        // issue (the value can't even round-trip through the codec,
5910        // so the cap diagnostic naming `1ms..=1h` would be misleading
5911        // — there's no integer-ms form of the offending value). Pin
5912        // the order so a future refactor that reorders the arms
5913        // surfaces here as a test failure rather than a silent
5914        // diagnostic regression. Peer of
5915        // `wall_clock_canonical_takes_precedence_over_cap` /
5916        // `policy_timeout_canonical_takes_precedence_over_cap`.
5917        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
5918        let s = SupervisorSpec {
5919            restart_window: Some(w),
5920            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5921            ..SupervisorSpec::default()
5922        };
5923        assert_eq!(
5924            s.validate().unwrap_err(),
5925            SupervisorError::RestartWindowNotCanonical { window: w },
5926            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
5927        );
5928    }
5929
5930    #[test]
5931    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
5932        // The cross-arm ordering pin between the `:max-restarts` cap
5933        // and the sibling `:restart-window` cap. A supervisor carrying
5934        // both an over-cap `max_restarts` AND an over-cap window must
5935        // surface the `MaxRestartsExceedsCap` diagnostic first — the
5936        // cap arm is wired immediately after the zero-restart arm and
5937        // strictly before every window-axis arm (zero / canonical /
5938        // cap), so the offending value the diagnostic names matches
5939        // the order the author would discover the gates by reading
5940        // top-to-bottom through `SupervisorSpec::validate`. Pin the
5941        // order so a future refactor that reorders the arms surfaces
5942        // here as a test failure rather than a silent diagnostic
5943        // regression. Peer of
5944        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
5945        // on the sibling zero / canonical window arms.
5946        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5947        let s = SupervisorSpec {
5948            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5949            restart_window: Some(w),
5950            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5951            ..SupervisorSpec::default()
5952        };
5953        assert_eq!(
5954            s.validate().unwrap_err(),
5955            SupervisorError::MaxRestartsExceedsCap {
5956                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5957            },
5958            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5959        );
5960    }
5961
5962    #[test]
5963    fn restart_window_cap_diagnostic_carries_offending_value() {
5964        // The diagnostic-shape pin: the offending `Duration` is
5965        // carried verbatim into the
5966        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
5967        // surfaced error message names the value the author wrote,
5968        // not just the cap. Same self-locating diagnostic shape every
5969        // other typed-cap arm on this surface carries
5970        // (`WallClockExceedsCap` carries the offending `Duration`
5971        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
5972        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
5973        // the offending `Duration` verbatim).
5974        let w = Duration::from_secs(7200); // 2h
5975        let s = SupervisorSpec {
5976            restart_window: Some(w),
5977            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5978            ..SupervisorSpec::default()
5979        };
5980        let err = s.validate().unwrap_err();
5981        assert!(
5982            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
5983            "got {err:?}"
5984        );
5985        let msg = err.to_string();
5986        assert!(
5987            msg.contains("7200"),
5988            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
5989        );
5990    }
5991
5992    #[test]
5993    fn supervisor_restart_window_cap_pins_canonical_value() {
5994        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
5995        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
5996        // shared duration codec emits as a clean canonical string
5997        // (`"<n>h"`). Pinning the literal value here surfaces a future
5998        // drift (a relaxation to 24h, a tightening to 5m) as a
5999        // deliberate test edit, not a silent contract narrowing.
6000        //
6001        // The four typed-`Duration` caps on the validation surface
6002        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
6003        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
6004        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
6005        // single uniform top edge at the codec's largest emitted unit
6006        // — a structural-property invariant the equality assertions
6007        // here enshrine, so a future drift on any of the four
6008        // surfaces as a deliberate test edit. Same shape every other
6009        // typed-cap value pin uses
6010        // (`wall_clock_cap_pins_canonical_value`,
6011        // `policy_timeout_cap_pins_canonical_value`,
6012        // `circuit_breaker_window_cap_pins_canonical_value`).
6013        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
6014        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
6015        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
6016        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
6017        assert_eq!(
6018            SUPERVISOR_RESTART_WINDOW_MAX,
6019            crate::POLICY_BREAKER_WINDOW_MAX
6020        );
6021    }
6022
6023    #[test]
6024    fn restart_window_cap_value_round_trips_through_codec() {
6025        // The codec round-trip property the cap arm preserves: the
6026        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
6027        // through the shared duration codec — every value at the cap
6028        // serializes to the canonical `"1h"` form and parses back
6029        // identically. Pin the round-trip so a future change to the
6030        // codec's unit set or to the cap's magnitude that breaks the
6031        // round-trip property surfaces here. Peer of
6032        // `wall_clock_cap_value_round_trips_through_codec` on the
6033        // sibling `:limits :wall-clock` axis.
6034        let s = SupervisorSpec {
6035            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6036            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6037            ..SupervisorSpec::default()
6038        };
6039        s.validate().unwrap();
6040        let json = serde_json::to_string(&s).unwrap();
6041        assert!(
6042            json.contains("\"1h\""),
6043            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
6044        );
6045        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6046        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
6047    }
6048
6049    #[test]
6050    fn validate_rejects_duplicate_child_caixa() {
6051        // Two children with the same :caixa render to two ComputeUnits
6052        // with the same name in the cluster's HelmRelease values —
6053        // one silently overwrites the other. Erlang/OTP's child_spec.id
6054        // is required-unique per supervisor; same set-not-multiset
6055        // discipline applied here as for :membros / :placement
6056        // :clusters / :entrada :paths.
6057        let s = SupervisorSpec {
6058            children: vec![
6059                child("worker", "^0.1", RestartPolicy::Permanent),
6060                child("cache", "^0.1", RestartPolicy::Transient),
6061                child("worker", "^0.2", RestartPolicy::Permanent),
6062            ],
6063            ..SupervisorSpec::default()
6064        };
6065        let err = s.validate().unwrap_err();
6066        assert!(
6067            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
6068            "got {err:?}"
6069        );
6070    }
6071
6072    #[test]
6073    fn validate_duplicate_child_diagnostic_names_first_collision() {
6074        // Iteration walks the :children list in declaration order —
6075        // the diagnostic names the first repeat, deterministically,
6076        // even when multiple names duplicate.
6077        let s = SupervisorSpec {
6078            children: vec![
6079                child("a", "^0.1", RestartPolicy::Permanent),
6080                child("b", "^0.1", RestartPolicy::Permanent),
6081                child("a", "^0.1", RestartPolicy::Permanent),
6082                child("b", "^0.1", RestartPolicy::Permanent),
6083            ],
6084            ..SupervisorSpec::default()
6085        };
6086        let err = s.validate().unwrap_err();
6087        assert!(
6088            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
6089            "got {err:?}"
6090        );
6091    }
6092
6093    // ── self-supervision cross-slot gate ──────────────────────────
6094
6095    #[test]
6096    fn validate_no_self_supervision_rejects_self_referential_child() {
6097        // A supervisor whose `:children` lists its own `:nome` is a
6098        // one-node reconciliation cycle — rejected, naming the parent.
6099        let children = vec![
6100            child("worker", "^0.1", RestartPolicy::Permanent),
6101            child("orquestra", "^0.1", RestartPolicy::Permanent),
6102        ];
6103        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
6104        assert!(
6105            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
6106            "got {err:?}"
6107        );
6108    }
6109
6110    #[test]
6111    fn validate_no_self_supervision_accepts_distinct_children() {
6112        // Positive control: distinct child names (including a child that
6113        // is itself a supervisor — nested trees are valid OTP) pass.
6114        let children = vec![
6115            child("worker", "^0.1", RestartPolicy::Permanent),
6116            child("sub-tree", "^0.1", RestartPolicy::Permanent),
6117        ];
6118        validate_no_self_supervision(&children, "orquestra").unwrap();
6119    }
6120
6121    #[test]
6122    fn validate_no_self_supervision_empty_children_is_ok() {
6123        // SimpleOneForOne / no-static-children supervisors have nothing
6124        // to self-reference — the gate is vacuously satisfied.
6125        validate_no_self_supervision(&[], "orquestra").unwrap();
6126    }
6127
6128    #[test]
6129    fn validate_simple_one_for_one_skips_uniqueness_check() {
6130        // SimpleOneForOne supervisors carry no static children — the
6131        // duplicate-child loop never runs. A zero-window declaration
6132        // on a SimpleOneForOne supervisor still trips the window check
6133        // (window applies to dynamic children too).
6134        let s = SupervisorSpec {
6135            estrategia: RestartStrategy::SimpleOneForOne,
6136            restart_window: None,
6137            children: vec![],
6138            ..SupervisorSpec::default()
6139        };
6140        s.validate().unwrap();
6141        let s_zero = SupervisorSpec {
6142            estrategia: RestartStrategy::SimpleOneForOne,
6143            restart_window: Some(Duration::ZERO),
6144            children: vec![],
6145            ..SupervisorSpec::default()
6146        };
6147        assert_eq!(
6148            s_zero.validate().unwrap_err(),
6149            SupervisorError::RestartWindowZero
6150        );
6151    }
6152
6153    #[test]
6154    fn validate_zero_window_runs_after_max_restarts_check() {
6155        // Pin the order: max_restarts == 0 fires before
6156        // restart_window == 0s, so an author with both wrong sees the
6157        // counter-axis diagnostic first (matches the order in the
6158        // struct and in the doc comment).
6159        let s = SupervisorSpec {
6160            max_restarts: 0,
6161            restart_window: Some(Duration::ZERO),
6162            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6163            ..SupervisorSpec::default()
6164        };
6165        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
6166    }
6167
6168    #[test]
6169    fn round_trip_all_strategies() {
6170        for &strat in RestartStrategy::ALL {
6171            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
6172            // shape partition through the [`gen_platform::IsVariant`]
6173            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
6174            // predicate rather than the raw
6175            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
6176            // open-coded pattern-match — same closed-set-typed-enum
6177            // arm-discriminator dispatch discipline the sibling
6178            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
6179            // (915a934) extended onto its two paired positive / negated
6180            // `matches!` filter sites, and the sibling
6181            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
6182            // predicate convergence (766ec63) extended onto the M3 mesh-
6183            // slot per-`:placement` distribution-strategy `matches!`
6184            // discriminator axis. See the sibling
6185            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
6186            // fixture and the peer `manifest::tests::
6187            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
6188            // fixture — all three sites (the last unlifted
6189            // `matches!`-based arm-discriminator axis on the OTP-shape
6190            // supervisor sibling-restart-strategy closed-set typed enum,
6191            // acknowledged in 915a934's Prior-commits footnote as the
6192            // outstanding follow-up) now consult one typed dispatch on
6193            // the substrate primitive.
6194            let s = SupervisorSpec {
6195                estrategia: strat,
6196                children: if strat.is_simple_one_for_one() {
6197                    vec![]
6198                } else {
6199                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
6200                },
6201                ..SupervisorSpec::default()
6202            };
6203            let json = serde_json::to_string(&s).unwrap();
6204            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6205            assert_eq!(s, back);
6206        }
6207    }
6208
6209    #[test]
6210    fn round_trip_all_restart_policies() {
6211        for policy in [
6212            RestartPolicy::Permanent,
6213            RestartPolicy::Temporary,
6214            RestartPolicy::Transient,
6215        ] {
6216            let c = child("w", "^0.1", policy);
6217            let json = serde_json::to_string(&c).unwrap();
6218            let back: ChildSpec = serde_json::from_str(&json).unwrap();
6219            assert_eq!(c, back);
6220        }
6221    }
6222
6223    #[test]
6224    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
6225        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
6226        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
6227        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
6228        // is the only variant that satisfies `.is_simple_one_for_one()`;
6229        // every static-children-bearing arm (`OneForOne` / `OneForAll`
6230        // / `RestForOne`) returns `false`. This pin makes the partition
6231        // invariant load-bearing at caixa-core test time so a future
6232        // derive regression (a hole that returns `false` for
6233        // `SimpleOneForOne` too, or a byte-collision that flips a second
6234        // variant to `true`) trips here rather than laundering the arm
6235        // at the three test-fixture builder sites (a hole flips the
6236        // `SimpleOneForOne` fixture to carry a non-empty children list
6237        // and the subsequent `SupervisorSpec::validate` would refuse the
6238        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
6239        // a collision flips a peer strategy's fixture to carry an empty
6240        // children list and the subsequent `validate` would refuse with
6241        // [`SupervisorError::NoChildren`] — either way, the pin fires
6242        // here, at the derive site, rather than at the fixture-refusal
6243        // site far away). Peer of the sibling
6244        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
6245        // (915a934) pin on the M2 OTP-appup axis and the sibling
6246        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
6247        // pin on the M0 `:kind` axis.
6248        let cases: &[(RestartStrategy, bool)] = &[
6249            (RestartStrategy::OneForOne, false),
6250            (RestartStrategy::OneForAll, false),
6251            (RestartStrategy::RestForOne, false),
6252            (RestartStrategy::SimpleOneForOne, true),
6253        ];
6254        for (variant, expected) in cases {
6255            assert_eq!(
6256                variant.is_simple_one_for_one(),
6257                *expected,
6258                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
6259                 return {expected} (partition invariant on the \
6260                 IsVariant-derived arm-discriminator predicate — every \
6261                 test-fixture site that partitions the `:children` slot \
6262                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
6263                 off this typed dispatch, so a derive regression must \
6264                 surface here rather than at the fixture-refusal site)"
6265            );
6266        }
6267    }
6268
6269    #[test]
6270    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
6271        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
6272        // fixture-shape partition against the pre-lift
6273        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
6274        // pattern-match every test-fixture builder site previously
6275        // coupled to inline. Asserts the two projections agree byte-for-
6276        // byte on every arm of the enum, so a future derive regression
6277        // that flipped either predicate's arm-set would surface here at
6278        // caixa-core test time rather than at the three fixture-builder
6279        // sites (`supervisor::tests::round_trip_all_strategies`,
6280        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
6281        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
6282        // far from the derive site. Same peer-shape byte-identity pin
6283        // every sibling `IsVariant`-derive-routed convergence carries on
6284        // the substrate's closed-set typed-enum surface (peer of
6285        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
6286        // on the M2 OTP-appup axis).
6287        for &strat in RestartStrategy::ALL {
6288            let via_predicate = strat.is_simple_one_for_one();
6289            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
6290            assert_eq!(
6291                via_predicate, via_matches,
6292                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
6293                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
6294                 the pre-lift open-coded pattern and the \
6295                 IsVariant-derived predicate are the same axis, \
6296                 one typed dispatch"
6297            );
6298        }
6299    }
6300
6301    #[test]
6302    fn duration_codec_round_trip_canonical_units() {
6303        // Note the canonical-form rule: durations serialize to the
6304        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
6305        // "60s" — but the round-trip preserves the underlying Duration.
6306        let cases = [
6307            ("30s", Duration::from_secs(30)),
6308            ("5m", Duration::from_secs(300)),
6309            ("1h", Duration::from_secs(3600)),
6310            ("500ms", Duration::from_millis(500)),
6311        ];
6312        for (lit, dur) in cases {
6313            let s = SupervisorSpec {
6314                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6315                restart_window: Some(dur),
6316                ..SupervisorSpec::default()
6317            };
6318            let json = serde_json::to_string(&s).unwrap();
6319            assert!(
6320                json.contains(&format!("\"{lit}\"")),
6321                "expected \"{lit}\" in {json}"
6322            );
6323            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6324            assert_eq!(back.restart_window, Some(dur));
6325        }
6326    }
6327
6328    #[test]
6329    fn duration_canonicalizes_to_largest_unit() {
6330        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
6331        // typed Duration still equals 60s on the way back.
6332        let s = SupervisorSpec {
6333            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6334            restart_window: Some(Duration::from_secs(60)),
6335            ..SupervisorSpec::default()
6336        };
6337        let json = serde_json::to_string(&s).unwrap();
6338        assert!(json.contains("\"1m\""), "{json}");
6339        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6340        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
6341    }
6342
6343    #[test]
6344    fn three_child_one_for_one_validates() {
6345        let s = SupervisorSpec {
6346            estrategia: RestartStrategy::OneForOne,
6347            max_restarts: 5,
6348            restart_window: Some(Duration::from_secs(60)),
6349            children: vec![
6350                child("worker", "^0.1", RestartPolicy::Permanent),
6351                child("cache", "^0.1", RestartPolicy::Transient),
6352                child("scratch", "^0.1", RestartPolicy::Temporary),
6353            ],
6354        };
6355        s.validate().unwrap();
6356    }
6357
6358    #[test]
6359    fn json_uses_pascal_case_for_strategy_and_policy() {
6360        // Variant names are PascalCase by default in serde, matching
6361        // tatara-lisp's enum convention (`:estrategia OneForOne`).
6362        let c = child("w", "^0.1", RestartPolicy::Permanent);
6363        let json = serde_json::to_string(&c).unwrap();
6364        assert!(json.contains("\"Permanent\""));
6365        assert!(!json.contains("\"permanent\""));
6366
6367        let s = SupervisorSpec {
6368            estrategia: RestartStrategy::OneForOne,
6369            children: vec![c],
6370            ..SupervisorSpec::default()
6371        };
6372        let json = serde_json::to_string(&s).unwrap();
6373        assert!(json.contains("\"estrategia\":\"OneForOne\""));
6374    }
6375
6376    // ── shared duration codec: integer-magnitude canonical-form gate ──
6377    //
6378    // The gate lifts the discipline `crate::limits::parse_duration`
6379    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
6380    // the shared codec backing the remaining three typed-duration
6381    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
6382    // `:politicas :circuit-breaker :window`. Every magnitude `render`
6383    // emits is a non-negative integer with no decimal point and no
6384    // leading sign, so the codec's accepted set must match for
6385    // serialize/deserialize to round-trip without canonical-form
6386    // drift.
6387
6388    #[test]
6389    fn parse_accepts_integer_canonical_units() {
6390        // Pin the happy-path: every canonical author shape `render`
6391        // ever emits parses to the same `Duration` value, so the
6392        // codec's accepted set is at least a superset of its emitted
6393        // set on the canonical-unit axis.
6394        for (lit, dur) in [
6395            ("30s", Duration::from_secs(30)),
6396            ("500ms", Duration::from_millis(500)),
6397            ("2m", Duration::from_secs(120)),
6398            ("1h", Duration::from_secs(3600)),
6399            ("0s", Duration::ZERO),
6400        ] {
6401            assert_eq!(
6402                duration_codec::parse(lit).unwrap(),
6403                dur,
6404                "parse({lit:?}) should be {dur:?}"
6405            );
6406        }
6407    }
6408
6409    #[test]
6410    fn parse_accepts_bare_integer_as_seconds() {
6411        // The `"s" | ""` arm: a bare integer with no unit is read as
6412        // seconds. Pin this so the unit-empty form keeps parsing (it
6413        // renders to `"<n>s"` on serialize — that's a unit-choice
6414        // drift the integer-magnitude gate does NOT close, matching
6415        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
6416        // the peer `:limits :memory` codec).
6417        assert_eq!(
6418            duration_codec::parse("30").unwrap(),
6419            Duration::from_secs(30)
6420        );
6421    }
6422
6423    #[test]
6424    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
6425        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
6426        // on first serialize — DRIFT. The integer-magnitude gate names
6427        // the offending `"1.5"` verbatim and points at the canonical
6428        // remediation `"1500ms"`.
6429        let err = duration_codec::parse("1.5s").unwrap_err();
6430        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
6431        assert!(
6432            err.contains("not a non-negative integer"),
6433            "missing canonical-form reason in {err:?}"
6434        );
6435        assert!(
6436            err.contains("\"1500ms\""),
6437            "missing canonical-form remediation in {err:?}"
6438        );
6439    }
6440
6441    #[test]
6442    fn parse_rejects_decimal_shaped_integer_seconds() {
6443        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
6444        // `1s` exactly, so the round-trip looks correct — but the
6445        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
6446        // decimal-shape-with-integer-value form so author intent is
6447        // never silently rewritten.
6448        let err = duration_codec::parse("1.0s").unwrap_err();
6449        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
6450        assert!(
6451            err.contains("not a non-negative integer"),
6452            "missing canonical-form reason in {err:?}"
6453        );
6454    }
6455
6456    #[test]
6457    fn parse_rejects_half_unit_minute() {
6458        // `"0.5m"` is the unit-fraction footgun — author writes a
6459        // human-readable half-minute, serde silently rewrites to
6460        // `"30s"` on next emit. The gate names the offending
6461        // magnitude `"0.5"` and points at the integer-in-smaller-unit
6462        // form.
6463        let err = duration_codec::parse("0.5m").unwrap_err();
6464        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
6465        assert!(
6466            err.contains("\"30s\""),
6467            "missing canonical-form remediation in {err:?}"
6468        );
6469    }
6470
6471    #[test]
6472    fn parse_rejects_leading_plus_sign() {
6473        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
6474        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
6475        // cleanly to 30s and round-tripped to `"30s"` on next emit
6476        // (DRIFT). The digit-only gate closes the leading-sign class
6477        // first; the diagnostic names `"+30"` verbatim.
6478        let err = duration_codec::parse("+30s").unwrap_err();
6479        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
6480        assert!(
6481            err.contains("not a non-negative integer"),
6482            "missing canonical-form reason in {err:?}"
6483        );
6484    }
6485
6486    #[test]
6487    fn parse_rejects_leading_minus_sign() {
6488        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
6489        // rejected with `"negative duration in \"-30s\""`. Under the
6490        // integer-magnitude gate the diagnostic is unified — `-30` is
6491        // non-digit-only, f64-numeric, and surfaces with the canonical-
6492        // form reason (no leading `+` / `-` sign) naming the offending
6493        // `"-30"` verbatim. Same diagnostic shape as every other
6494        // rejected non-integer magnitude.
6495        let err = duration_codec::parse("-30s").unwrap_err();
6496        assert!(err.contains("\"-30\""), "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_garbage_still_falls_through_to_bad_magnitude() {
6505        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
6506        // through to the narrower "bad duration magnitude" arm — the
6507        // canonical-form diagnostic is reserved for the parser-shape
6508        // footgun case, not the "not a number at all" case. Same
6509        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
6510        // the peer `:limits :memory` codec.
6511        let err = duration_codec::parse("--1s").unwrap_err();
6512        assert!(
6513            err.contains("bad duration magnitude"),
6514            "expected bad-magnitude wording in {err:?}"
6515        );
6516    }
6517
6518    #[test]
6519    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
6520        // The accepted set is now closed under `u64`-exact integer
6521        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
6522        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
6523        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
6524        // possible. Pin the integer-exact arms across the four unit
6525        // suffixes so a future refactor that reaches back for f64
6526        // (`from_secs_f64`, `mul_f64`) surfaces here.
6527        assert_eq!(
6528            duration_codec::parse("3600s").unwrap(),
6529            Duration::from_secs(3600)
6530        );
6531        assert_eq!(
6532            duration_codec::parse("60m").unwrap(),
6533            Duration::from_secs(3600)
6534        );
6535        assert_eq!(
6536            duration_codec::parse("1h").unwrap(),
6537            Duration::from_secs(3600)
6538        );
6539        assert_eq!(
6540            duration_codec::parse("999ms").unwrap(),
6541            Duration::from_millis(999)
6542        );
6543    }
6544
6545    #[test]
6546    fn restart_window_serde_rejects_fractional_seconds() {
6547        // The shared codec backs `SupervisorSpec::restart_window`
6548        // (`with = "duration_codec"`) — so the gate applies on serde
6549        // deserialize for the typed Supervisor slot. A
6550        // `{"restartWindow":"1.5s"}` payload that previously round-
6551        // tripped to a different canonical string on next serialize
6552        // is now refused at deserialize with the integer-magnitude
6553        // diagnostic.
6554        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6555            "restartWindow":"1.5s",
6556            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6557        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6558        let msg = err.to_string();
6559        assert!(
6560            msg.contains("not a non-negative integer"),
6561            "expected integer-magnitude diagnostic in {msg:?}"
6562        );
6563        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
6564    }
6565
6566    #[test]
6567    fn restart_window_serde_rejects_leading_plus() {
6568        // The `u64::from_str` leading-`+` permissiveness gap that
6569        // motivated the digit-only gate (the `f64`-side accepted
6570        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
6571        // is now closed on the shared codec — surfaces as a structured
6572        // diagnostic at the serde layer for every typed-duration slot.
6573        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6574            "restartWindow":"+30s",
6575            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6576        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6577        let msg = err.to_string();
6578        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
6579        assert!(
6580            msg.contains("not a non-negative integer"),
6581            "missing canonical-form reason in {msg:?}"
6582        );
6583    }
6584
6585    #[test]
6586    fn parse_rejects_leading_zero_magnitude() {
6587        // `"030s"` is digit-only, so the existing non-digit-only / sign
6588        // / fractional arm doesn't catch it — `u64::from_str("030")`
6589        // returns `Ok(30)`, so before this gate `"030s"` parsed to
6590        // `Duration::from_secs(30)` and round-tripped through `render`
6591        // to `"30s"` — a *different* canonical string on the next emit,
6592        // breaking the THEORY.md Part V render-determinism contract
6593        // exactly the way `"+30s"` did before the leading-`+` arm
6594        // landed. Peer with the `rate_limit_codec` leading-zero arm
6595        // (4f46830) on the same canonical-form-drift axis.
6596        let err = duration_codec::parse("030s").unwrap_err();
6597        assert!(
6598            err.contains("non-canonical leading zero"),
6599            "expected leading-zero diagnostic in {err:?}"
6600        );
6601        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6602        assert!(
6603            err.contains("\"30s\""),
6604            "missing canonical-form remediation in {err:?}"
6605        );
6606        assert!(
6607            err.contains("THEORY.md"),
6608            "missing render-determinism citation in {err:?}"
6609        );
6610    }
6611
6612    #[test]
6613    fn parse_rejects_multi_digit_zero_magnitude() {
6614        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
6615        // digit-only, parse losslessly to `Duration::ZERO`, but render
6616        // back to `"0s"` (the single-byte canonical form) on the next
6617        // emit. The leading-zero arm refuses the drift class at the
6618        // codec layer; the semantic-zero gate downstream
6619        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
6620        // the single-byte canonical form `"0s"` separately on the
6621        // typed-validate layer.
6622        let err = duration_codec::parse("00s").unwrap_err();
6623        assert!(
6624            err.contains("non-canonical leading zero"),
6625            "expected leading-zero diagnostic in {err:?}"
6626        );
6627        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
6628    }
6629
6630    #[test]
6631    fn parse_rejects_leading_zero_per_hour_window() {
6632        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
6633        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
6634        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
6635        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
6636        // `h` / bare-integer-as-seconds) inherits the same gate.
6637        let err = duration_codec::parse("01h").unwrap_err();
6638        assert!(
6639            err.contains("non-canonical leading zero"),
6640            "expected leading-zero diagnostic in {err:?}"
6641        );
6642        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
6643    }
6644
6645    #[test]
6646    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
6647        // The `parse_accepts_bare_integer_as_seconds` happy-path
6648        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
6649        // multi-byte starts-with-`0`, parses losslessly to
6650        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
6651        // bare-integer surface accepts permissive unit-empty
6652        // shorthand but still must reject leading-zero padding.
6653        let err = duration_codec::parse("030").unwrap_err();
6654        assert!(
6655            err.contains("non-canonical leading zero"),
6656            "expected leading-zero diagnostic in {err:?}"
6657        );
6658        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6659    }
6660
6661    #[test]
6662    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
6663        // The codec-layer / typed-validate-layer boundary: `"0s"` /
6664        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
6665        // each round-trips losslessly through `render`
6666        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
6667        // accepts them. The downstream semantic-zero gates
6668        // (`SupervisorError::ZeroRestartWindow`,
6669        // `AplicacaoError::PolicyTimeoutZero`,
6670        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
6671        // zero-magnitude authoring at the typed-validate layer above,
6672        // peer with the `rate_limit_codec` codec-layer / typed-
6673        // validate-layer partition for `"0/s"`.
6674        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
6675        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
6676        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
6677    }
6678
6679    #[test]
6680    fn parse_accepts_canonical_magnitude_with_leading_one() {
6681        // The complementary boundary: a future tightening cannot
6682        // drift into rejecting valid canonical magnitudes that
6683        // happen to start with `1` (or any digit `[1-9]`). Pin
6684        // every canonical-unit suffix so the leading-zero arm
6685        // remains strictly narrower than the digit-only arm.
6686        assert_eq!(
6687            duration_codec::parse("100ms").unwrap(),
6688            Duration::from_millis(100)
6689        );
6690        assert_eq!(
6691            duration_codec::parse("100s").unwrap(),
6692            Duration::from_secs(100)
6693        );
6694        assert_eq!(
6695            duration_codec::parse("10m").unwrap(),
6696            Duration::from_secs(600)
6697        );
6698        assert_eq!(
6699            duration_codec::parse("10h").unwrap(),
6700            Duration::from_secs(36_000)
6701        );
6702    }
6703
6704    #[test]
6705    fn restart_window_serde_rejects_leading_zero() {
6706        // The shared codec backs `SupervisorSpec::restart_window`
6707        // (`with = "duration_codec"`) — so the leading-zero arm
6708        // applies on serde deserialize for the typed Supervisor slot.
6709        // A `{"restartWindow":"030s"}` payload that previously round-
6710        // tripped to a different canonical string on next serialize
6711        // is now refused at deserialize with the leading-zero
6712        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
6713        // / `restart_window_serde_rejects_fractional_seconds` on the
6714        // same canonical-form-drift axis.
6715        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6716            "restartWindow":"030s",
6717            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6718        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6719        let msg = err.to_string();
6720        assert!(
6721            msg.contains("non-canonical leading zero"),
6722            "expected leading-zero diagnostic in {msg:?}"
6723        );
6724        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
6725    }
6726
6727    #[test]
6728    fn parse_rejects_leading_whitespace() {
6729        // `" 30s"` — the canonical paste-from-aligned-doc /
6730        // paste-from-YAML-quoted-plain-scalar footgun. Before this
6731        // gate the top-level `s.trim()` at parse entry silently ate
6732        // the leading space and parsed the value to
6733        // `Duration::from_secs(30)`, which then round-tripped through
6734        // `render` to `"30s"` (a *different* canonical string on the
6735        // next emit) — the exact canonical-form-drift class the
6736        // leading-`+` / leading-zero arms already close, extended
6737        // to the whitespace-byte class. Peer with the sibling
6738        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
6739        // the M3 `:politicas` axis.
6740        let err = duration_codec::parse(" 30s").unwrap_err();
6741        assert!(
6742            err.contains("contains whitespace byte"),
6743            "expected whitespace diagnostic in {err:?}"
6744        );
6745        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6746        assert!(
6747            err.contains("THEORY.md"),
6748            "missing render-determinism contract citation in {err:?}"
6749        );
6750    }
6751
6752    #[test]
6753    fn parse_rejects_trailing_whitespace() {
6754        // `"30s "` — the canonical shell-history / trailing-space
6755        // paste footgun. Before this gate the top-level `s.trim()`
6756        // silently ate the trailing space and parsed to
6757        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
6758        // next emit — same canonical-form drift as the leading-space
6759        // sibling, closed on the same whitespace-byte arm.
6760        let err = duration_codec::parse("30s ").unwrap_err();
6761        assert!(
6762            err.contains("contains whitespace byte"),
6763            "expected whitespace diagnostic in {err:?}"
6764        );
6765        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6766    }
6767
6768    #[test]
6769    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
6770        // `"30 s"` — the canonical typographically-spaced author
6771        // shape (the same idiom every prose reference to a duration
6772        // renders as, mistakenly retained when the value is pasted
6773        // into a codec-shaped slot). Before this gate the per-part
6774        // `num_part.trim()` / `unit.trim()` calls silently ate the
6775        // whitespace between the magnitude and the unit and parsed
6776        // the value to `Duration::from_secs(30)`, round-tripping to
6777        // `"30s"` — the codec's *internal* whitespace-tolerance
6778        // vector, orthogonal to the leading / trailing surface but
6779        // the same canonical-form-drift class. Pins the arm as
6780        // strictly stronger than the pre-existing top-level
6781        // `s.trim()` behavior: it fires on whitespace anywhere in
6782        // the value, not just at the string boundary.
6783        let err = duration_codec::parse("30 s").unwrap_err();
6784        assert!(
6785            err.contains("contains whitespace byte"),
6786            "expected whitespace diagnostic in {err:?}"
6787        );
6788        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6789    }
6790
6791    #[test]
6792    fn parse_rejects_tab_byte() {
6793        // `"\t30s"` — the canonical paste-from-indented-doc /
6794        // paste-from-YAML-block-scalar footgun where a tab byte leads
6795        // the magnitude. Pins that the gate covers tab (`0x09`) as
6796        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
6797        // members and both would be silently swallowed by `s.trim()`
6798        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
6799        // space alone to the full ASCII-whitespace set (space `0x20`,
6800        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
6801        // the tab arm as a representative of the non-space members.
6802        let err = duration_codec::parse("\t30s").unwrap_err();
6803        assert!(
6804            err.contains("contains whitespace byte"),
6805            "expected whitespace diagnostic in {err:?}"
6806        );
6807        assert!(
6808            err.contains("0x09"),
6809            "missing offending tab byte in {err:?}"
6810        );
6811    }
6812
6813    #[test]
6814    fn restart_window_serde_rejects_whitespace() {
6815        // The shared codec backs `SupervisorSpec::restart_window`
6816        // (`with = "duration_codec"`) — so the whitespace arm
6817        // applies on serde deserialize for the typed Supervisor slot.
6818        // A `{"restartWindow":" 30s"}` payload that previously round-
6819        // tripped to a different canonical string on next serialize
6820        // is now refused at deserialize with the whitespace-byte
6821        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
6822        // / `restart_window_serde_rejects_leading_plus` /
6823        // `restart_window_serde_rejects_fractional_seconds` on the
6824        // same canonical-form-drift axis.
6825        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6826            "restartWindow":" 30s",
6827            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6828        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6829        let msg = err.to_string();
6830        assert!(
6831            msg.contains("contains whitespace byte"),
6832            "expected whitespace diagnostic in {msg:?}"
6833        );
6834        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
6835    }
6836
6837    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
6838    //
6839    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
6840    // duration codec — closes the strictly-complementary class the
6841    // byte-scan cannot see, through the lifted
6842    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
6843    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
6844    // and `:politicas :circuit-breaker :window` simultaneously via
6845    // this shared codec.
6846
6847    #[test]
6848    fn duration_codec_parse_rejects_leading_nbsp() {
6849        // NBSP prefix — the strictly-complementary drift class the
6850        // ASCII byte-scan cannot see. `str::trim` strips it silently
6851        // and the value drifts to `"30s"` on next serialize.
6852        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
6853        assert!(
6854            err.contains("non-ASCII Unicode whitespace character"),
6855            "expected non-ASCII whitespace diagnostic in {err:?}"
6856        );
6857        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
6858    }
6859
6860    #[test]
6861    fn duration_codec_parse_rejects_trailing_line_separator() {
6862        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
6863        // footgun.
6864        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
6865        assert!(
6866            err.contains("non-ASCII Unicode whitespace character"),
6867            "expected non-ASCII whitespace diagnostic in {err:?}"
6868        );
6869        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
6870    }
6871
6872    #[test]
6873    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
6874        // Positive-control pin: every ASCII-only canonical form the
6875        // renderer emits stays accepted through the new arm.
6876        assert_eq!(
6877            duration_codec::parse("30s").unwrap(),
6878            Duration::from_secs(30)
6879        );
6880        assert_eq!(
6881            duration_codec::parse("500ms").unwrap(),
6882            Duration::from_millis(500)
6883        );
6884        assert_eq!(
6885            duration_codec::parse("1h").unwrap(),
6886            Duration::from_secs(3600)
6887        );
6888    }
6889
6890    #[test]
6891    fn restart_window_serde_rejects_non_ascii_whitespace() {
6892        // The shared codec backs `SupervisorSpec::restart_window` — so
6893        // the new non-ASCII Unicode whitespace arm applies on serde
6894        // deserialize for the typed Supervisor slot. A
6895        // `{"restartWindow":" 30s"}` payload that previously
6896        // survived the ASCII byte-scan (only ASCII whitespace was
6897        // refused) is now refused at deserialize with the
6898        // non-ASCII-whitespace-and-codepoint diagnostic.
6899        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
6900            \"restartWindow\":\"\u{00A0}30s\",\
6901            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
6902        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6903        let msg = err.to_string();
6904        assert!(
6905            msg.contains("non-ASCII Unicode whitespace character"),
6906            "expected non-ASCII whitespace diagnostic in {msg:?}"
6907        );
6908        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
6909    }
6910
6911    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
6912
6913    #[test]
6914    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
6915        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
6916        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
6917        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
6918        // name the exact camelCase JSON keys the
6919        // `#[serde(rename_all = "camelCase")]` attribute on
6920        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
6921        // field carries `Some(_)` / non-empty) and pin that each canonical
6922        // byte-sequence appears verbatim in the JSON — a future accidental
6923        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
6924        // name flip at the derive attribute (any of which would silently
6925        // break every downstream JSON consumer that reaches for one of the
6926        // four consts via `Value::get(...)`) surfaces here as a build-time
6927        // test failure at `supervisor.rs`, not as an apply-time
6928        // `.get(<stale-canonical-const>)` returning `None` far from the
6929        // derive-attr drift's commit. Peer with the sibling
6930        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
6931        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
6932        // M2 typed-slot family established, extended here to close the
6933        // top-level Supervisor axis.
6934        let spec = SupervisorSpec {
6935            estrategia: RestartStrategy::OneForOne,
6936            max_restarts: 5,
6937            restart_window: Some(Duration::from_secs(60)),
6938            children: vec![ChildSpec {
6939                caixa: "w".into(),
6940                versao: "^0.1".into(),
6941                restart: RestartPolicy::Permanent,
6942            }],
6943        };
6944        let json = serde_json::to_string(&spec).unwrap();
6945        for key in [
6946            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6947            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6948            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6949            crate::render::SUPERVISOR_KEY_CHILDREN,
6950        ] {
6951            let quoted = format!("\"{key}\"");
6952            assert!(
6953                json.contains(&quoted),
6954                "serialized SupervisorSpec must carry the lifted \
6955                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
6956                 the JSON emission (got: {json})",
6957            );
6958        }
6959    }
6960
6961    #[test]
6962    fn supervisor_key_consts_are_pairwise_distinct() {
6963        // Cross-axis drift-detection pin: a future collapse of two
6964        // canonical top-level byte-strings onto the same value (e.g. an
6965        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
6966        // also read `"estrategia"`) would silently reroute every
6967        // downstream probe on one axis onto the sibling axis's overlay
6968        // entry and pass every propagation-probe test that expected only
6969        // the stale axis's value. Peer of the sibling four-way distinct
6970        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
6971        let all = [
6972            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6973            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6974            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6975            crate::render::SUPERVISOR_KEY_CHILDREN,
6976        ];
6977        for (i, a) in all.iter().enumerate() {
6978            for b in all.iter().skip(i + 1) {
6979                assert_ne!(
6980                    a, b,
6981                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
6982                     canonical byte-sequences — got `{a}` == `{b}`",
6983                );
6984            }
6985        }
6986    }
6987
6988    #[test]
6989    fn supervisor_key_consts_are_lower_camel_case_shape() {
6990        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
6991        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6992        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6993        // capital, no whitespace / dots) — the canonical shape the
6994        // `#[serde(rename_all = "camelCase")]` derive produces on
6995        // `SupervisorSpec`. A future flip to a non-camelCase attribute
6996        // at the derive surfaces both here (this test fails on the
6997        // stale-constant shape) and at
6998        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6999        // (that test fails on the mismatch between const and derive).
7000        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
7001        // (d8b8b4f) on the sibling M2 `:limits` axis.
7002        for key in [
7003            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7004            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7005            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7006            crate::render::SUPERVISOR_KEY_CHILDREN,
7007        ] {
7008            assert!(
7009                !key.is_empty(),
7010                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
7011            );
7012            let first = key.chars().next().unwrap();
7013            assert!(
7014                first.is_ascii_lowercase(),
7015                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
7016                 (got {key:?}, leads with {first:?})",
7017            );
7018            assert!(
7019                key.chars().all(|c| c.is_ascii_alphanumeric()),
7020                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
7021                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7022            );
7023        }
7024    }
7025
7026    #[test]
7027    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
7028        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
7029        // (camelCase JSON keys, no leading colon) must never collide
7030        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
7031        // consts (kebab-case author-facing labels with leading colon)
7032        // that sit next to them at `caixa_core::render`. Both families
7033        // cover the same four typed Supervisor slots on two distinct
7034        // axes (author-side kebab vs renderer-side camelCase);
7035        // collapsing either family onto the other's byte-shape would
7036        // silently reroute the render-side probe onto the author-facing
7037        // surface, or vice versa. Peer of the byte-distinctness
7038        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
7039        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
7040        let pairs = [
7041            (
7042                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7043                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
7044            ),
7045            (
7046                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7047                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
7048            ),
7049            (
7050                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7051                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
7052            ),
7053            (
7054                crate::render::SUPERVISOR_KEY_CHILDREN,
7055                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
7056            ),
7057        ];
7058        for (json_key, author_key) in pairs {
7059            assert_ne!(
7060                json_key, author_key,
7061                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
7062                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
7063                 got JSON `{json_key}` == author `{author_key}`",
7064            );
7065        }
7066    }
7067
7068    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
7069
7070    #[test]
7071    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
7072        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
7073        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
7074        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
7075        // keys the `#[serde(rename_all = "camelCase")]` attribute on
7076        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
7077        // pin that each canonical byte-sequence appears verbatim in the
7078        // JSON — a future accidental `rename_all = "snake_case"` /
7079        // `"kebab-case"` / verbatim-field-name flip at the derive
7080        // attribute (any of which would silently break every downstream
7081        // JSON consumer that reaches for one of the three consts via
7082        // `Value::get(...)`) surfaces here as a build-time test failure at
7083        // `supervisor.rs`, not as an apply-time
7084        // `.get(<stale-canonical-const>)` returning `None` far from the
7085        // derive-attr drift's commit. Peer with the enclosing
7086        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7087        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
7088        // discipline the SupervisorSpec top-level lift established,
7089        // extended here to the sibling per-`:children` entry `ChildSpec`
7090        // derive so the last M2 typed-struct sub-block
7091        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
7092        // surface without a lifted serde-key peer joins the substrate's
7093        // "one canonical byte-string per typed serialized-key axis"
7094        // discipline.
7095        let c = ChildSpec {
7096            caixa: "worker".into(),
7097            versao: "^0.1".into(),
7098            restart: RestartPolicy::Permanent,
7099        };
7100        let json = serde_json::to_string(&c).unwrap();
7101        for key in [
7102            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7103            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7104            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7105        ] {
7106            let quoted = format!("\"{key}\"");
7107            assert!(
7108                json.contains(&quoted),
7109                "serialized ChildSpec must carry the lifted \
7110                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
7111                 in the JSON emission (got: {json})",
7112            );
7113        }
7114    }
7115
7116    #[test]
7117    fn supervisor_child_key_consts_are_pairwise_distinct() {
7118        // Cross-axis drift-detection pin: a future collapse of two
7119        // canonical `ChildSpec` per-entry byte-strings onto the same
7120        // value (e.g. an accidental copy-paste flip of
7121        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
7122        // silently reroute every downstream probe on one axis onto the
7123        // sibling axis's overlay entry and pass every propagation-probe
7124        // test that expected only the stale axis's value. Peer of the
7125        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
7126        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
7127        // pair (ce80ca0).
7128        let all = [
7129            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7130            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7131            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7132        ];
7133        for (i, a) in all.iter().enumerate() {
7134            for b in all.iter().skip(i + 1) {
7135                assert_ne!(
7136                    a, b,
7137                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
7138                     distinct canonical byte-sequences — got `{a}` == `{b}`",
7139                );
7140            }
7141        }
7142    }
7143
7144    #[test]
7145    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
7146        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
7147        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7148        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7149        // capital, no whitespace / dots) — the canonical shape the
7150        // `#[serde(rename_all = "camelCase")]` derive produces on
7151        // `ChildSpec`. A future flip to a non-camelCase attribute at the
7152        // derive surfaces both here (this test fails on the
7153        // stale-constant shape) and at
7154        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
7155        // (that test fails on the mismatch between const and derive).
7156        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
7157        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
7158        for key in [
7159            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7160            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7161            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7162        ] {
7163            assert!(
7164                !key.is_empty(),
7165                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
7166            );
7167            let first = key.chars().next().unwrap();
7168            assert!(
7169                first.is_ascii_lowercase(),
7170                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
7171                 byte (got {key:?}, leads with {first:?})",
7172            );
7173            assert!(
7174                key.chars().all(|c| c.is_ascii_alphanumeric()),
7175                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
7176                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7177            );
7178        }
7179    }
7180
7181    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
7182
7183    #[test]
7184    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
7185        // The fail-before-pass-after pin: pre-lift there was no
7186        // single-source binding between the [`RestartStrategy`] variant
7187        // name the un-`rename`d `Serialize` derive emits under
7188        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
7189        // every downstream cluster-side dispatcher (the future
7190        // wasm-operator's per-supervisor sibling-restart branch, the
7191        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7192        // admission-time enum-arm bind, the `caixa-operator`'s
7193        // hierarchical reconciliation scheduler's per-strategy fan-out)
7194        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
7195        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
7196        // override, or a variant rename in the source — would silently
7197        // rebrand the emitted scalar under one spelling while every
7198        // downstream dispatcher still probed the other, with the failure
7199        // surfacing at the operator's reconcile posture (subtrees coming
7200        // up under the `default()` `OneForOne` arm rather than the typed
7201        // slot's declared strategy — a bad child would then only take
7202        // itself down instead of the sibling set the author intended, so
7203        // shared-state children fall out of sync) far from the source
7204        // rebrand commit and with no field naming the drift. Pinning the
7205        // two paths (the `Serialize` derive's serialized string AND the
7206        // [`RestartStrategy::as_str`] helper) to the same four lifted
7207        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
7208        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
7209        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
7210        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
7211        // byte-strings makes any future drift on either endpoint fail
7212        // here at caixa-core build time. Peer of the M3
7213        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7214        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
7215        // three-path-convergence discipline, extended to close the
7216        // OTP-shaped per-supervisor sibling-restart axis.
7217        for (variant, expected) in [
7218            (
7219                RestartStrategy::OneForOne,
7220                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7221            ),
7222            (
7223                RestartStrategy::OneForAll,
7224                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7225            ),
7226            (
7227                RestartStrategy::RestForOne,
7228                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7229            ),
7230            (
7231                RestartStrategy::SimpleOneForOne,
7232                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7233            ),
7234        ] {
7235            let json = serde_json::to_string(&variant).unwrap();
7236            assert_eq!(
7237                json,
7238                format!("\"{expected}\""),
7239                "RestartStrategy::{variant:?} must serialize to {expected:?}"
7240            );
7241            assert_eq!(
7242                variant.as_str(),
7243                expected,
7244                "RestartStrategy::{variant:?}.as_str() must return the lifted \
7245                 SUPERVISOR_ESTRATEGIA_* constant"
7246            );
7247        }
7248    }
7249
7250    #[test]
7251    fn supervisor_estrategia_consts_are_pairwise_distinct() {
7252        // Cross-arm drift-detection pin: a future collapse of two
7253        // canonical variant byte-strings onto the same value (e.g. an
7254        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
7255        // to also read `"OneForOne"`) would silently reroute every
7256        // downstream operator's per-strategy dispatch onto the sibling
7257        // arm's reconcile branch and pass every propagation-probe test
7258        // that expected only the stale arm's value — the mis-strategied
7259        // subtree would come up with the wrong sibling-restart posture
7260        // on every subsequent failure. Peer of the sibling four-way
7261        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
7262        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
7263        let all = [
7264            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7265            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7266            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7267            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7268        ];
7269        for (i, a) in all.iter().enumerate() {
7270            for (j, b) in all.iter().enumerate() {
7271                if i != j {
7272                    assert_ne!(
7273                        a, b,
7274                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
7275                         — got duplicate {a:?} at indices {i} and {j}",
7276                    );
7277                }
7278            }
7279        }
7280    }
7281
7282    #[test]
7283    fn restart_strategy_display_routes_through_as_str_helper() {
7284        // The fail-before-pass-after pin on the first half of the
7285        // three-path convergence: pre-convergence the sibling
7286        // OTP-shape typed enum [`RestartStrategy`] carried a
7287        // [`std::fmt::Display`] surface via its
7288        // `#[discriminant(also_display)]` gen-platform derive route,
7289        // which arrived kebab-case as `"one-for-one"` /
7290        // `"one-for-all"` / `"rest-for-one"` /
7291        // `"simple-one-for-one"` while the wire format ran as
7292        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
7293        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
7294        // Every consumer reaching for a strategy byte-string past the
7295        // wire format had to pick between three paths
7296        // ([`RestartStrategy::as_str`], the `Serialize` derive's
7297        // serialized string, or `format!("{v}")` on the
7298        // discriminant-Display route), any two of which a future
7299        // variant rename or `#[serde(rename_all = "kebab-case")]`
7300        // attribute would silently desynchronize. Wiring
7301        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
7302        // closes the third path: every `format!("{v}")` call reaches
7303        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7304        // const the wire format and the [`RestartStrategy::as_str`]
7305        // helper already route through, so a future variant rename
7306        // lands at exactly one place. Pin the routing here so a future
7307        // `impl std::fmt::Display for RestartStrategy`
7308        // reimplementation that hand-rolls the arms instead of
7309        // delegating to [`RestartStrategy::as_str`] fails at
7310        // caixa-core build time. Peer of the M3
7311        // `placement_strategy_display_routes_through_as_str_helper`
7312        // (cc8f749) which the M3 axis converged first.
7313        for &variant in RestartStrategy::ALL {
7314            assert_eq!(
7315                variant.to_string(),
7316                variant.as_str(),
7317                "RestartStrategy::{variant:?} Display must route through \
7318                 RestartStrategy::as_str (single source of truth: the lifted \
7319                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
7320            );
7321        }
7322    }
7323
7324    #[test]
7325    fn restart_strategy_display_matches_serialized_wire_byte_string() {
7326        // The fail-before-pass-after pin on the second half of the
7327        // three-path convergence: `Display` (user-facing text) agrees
7328        // byte-for-byte with the `Serialize` derive's wire format
7329        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
7330        // scalar) on every variant. Pre-convergence the two paths
7331        // were structurally independent — a future
7332        // `#[serde(rename_all = "kebab-case")]` attribute on the
7333        // enum would silently rebrand the emitted wire scalar
7334        // (`one-for-one`, `one-for-all`, `rest-for-one`,
7335        // `simple-one-for-one`) while every consumer that
7336        // pretty-prints the strategy (the future wasm-operator's
7337        // per-supervisor sibling-restart-strategy diagnostic line,
7338        // the future `feira app graph` per-supervisor strategy line,
7339        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7340        // materializer's admission-webhook rejection body) would
7341        // still emit the PascalCase form the `as_str` / `Display`
7342        // route returns, with the mismatch surfacing at consumer
7343        // parse time / operator dispatch time far from the source
7344        // rebrand commit. Pin the two paths byte-for-byte here so any
7345        // future serde-attribute or variant-rename drift is a
7346        // caixa-core-build-time test failure at this call, not a
7347        // silent per-consumer dispatch miss. Peer of the M3
7348        // `placement_strategy_display_matches_serialized_wire_byte_string`
7349        // (cc8f749) which the M3 axis converged first.
7350        for &variant in RestartStrategy::ALL {
7351            let wire = serde_json::to_string(&variant).unwrap();
7352            let unquoted = wire
7353                .strip_prefix('"')
7354                .and_then(|s| s.strip_suffix('"'))
7355                .expect("serialized RestartStrategy is a JSON string");
7356            assert_eq!(
7357                variant.to_string(),
7358                unquoted,
7359                "RestartStrategy::{variant:?} Display byte-string must match the \
7360                 Serialize derive's wire byte-string (three-path convergence: \
7361                 Display + as_str + Serialize all resolve to the same \
7362                 SUPERVISOR_ESTRATEGIA_* const)"
7363            );
7364        }
7365    }
7366
7367    #[test]
7368    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
7369        // Fail-before-pass-after byte-parity pin on the lifted
7370        // `impl AsRef<str> for RestartStrategy` — asserts the
7371        // standard-library trait impl and the substrate-primitive
7372        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
7373        // to the same `&str` per instance across the four-arm
7374        // closed set, so any future silent detour that routes the
7375        // impl through a divergent projection (a per-arm inline
7376        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
7377        // re-inlining that opens a compile-time link to the un-lifted
7378        // arm-literal, a swap onto the kebab-case
7379        // [`gen_platform::Discriminant`] catalog identity that would
7380        // collide the wire axis with the dispatcher-catalog axis) trips
7381        // at caixa-core test time under `PartialEq` rather than at a
7382        // downstream `impl AsRef<str>`-bound consumer's silent split.
7383        // Sweeps every one of the four arms
7384        // [`RestartStrategy::ALL`] carries so no arm's projection is
7385        // covered only by the sibling wire-format `Serialize` derive
7386        // path. Peer of the sibling
7387        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
7388        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
7389        // top-level `:versao` typed newtype — the two pins together
7390        // cover the substrate primitive's `AsRef<str>` projection axis
7391        // on the paired newtype + closed-set-typed-enum surface.
7392        for &variant in RestartStrategy::ALL {
7393            assert_eq!(
7394                <RestartStrategy as AsRef<str>>::as_ref(&variant),
7395                variant.as_str(),
7396                "AsRef<str> impl on RestartStrategy::{variant:?} must \
7397                 byte-equal RestartStrategy::as_str on the same instance \
7398                 — divergence signals a silent detour off the substrate-\
7399                 primitive accessor"
7400            );
7401        }
7402    }
7403
7404    #[test]
7405    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
7406        // Fail-before-pass-after byte-parity pin on the three-path
7407        // convergence discipline the M2 sibling-restart primitive now
7408        // carries on the `&str`-projection axis:
7409        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
7410        // lifted impl), `format!("{s}")` (the pre-existing
7411        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
7412        // primitive `pub const fn` accessor both trait impls delegate
7413        // through) must resolve to the same byte-string on every
7414        // instance across the four-arm closed set. Refuses any future
7415        // divergence between the two trait impls (a stray
7416        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7417        // rather than delegating through the shared accessor; a
7418        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7419        // literal cascade) that would silently split the two
7420        // projection paths of the same closed-set typed enum. Mirrors
7421        // the sibling three-path-convergence discipline the peer
7422        // [`crate::CaixaVersion`] typed newtype carries on its
7423        // `AsRef<str>` / `Display` / `as_str` triple
7424        // (version.rs pin
7425        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7426        // 16d5c7e).
7427        for &variant in RestartStrategy::ALL {
7428            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
7429            let via_display: String = format!("{variant}");
7430            let via_accessor: &str = variant.as_str();
7431            assert_eq!(via_as_ref, via_accessor);
7432            assert_eq!(via_display, via_accessor);
7433            assert_eq!(via_as_ref, via_display.as_str());
7434        }
7435    }
7436
7437    #[test]
7438    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
7439        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
7440        // exhaustive-iteration surface: every variant appears exactly
7441        // once, and the slice length matches the arm count of the
7442        // closed set. Every consumer that walks the accepted-strategy
7443        // set (a future `feira supervisor --estrategia …` CLI-side
7444        // arg-parse's "did you mean" hint, a future M4 admission-
7445        // webhook's rejection body naming the accepted-`:estrategia`
7446        // list, the [`RestartStrategy::from_wire`] reverse-projection
7447        // consumers that iterate the accept-set for diagnostic
7448        // rendering) reads through this slice, so a future arm addition
7449        // that grows the enum but forgets to grow [`Self::ALL`]
7450        // silently truncates every downstream consumer's accept-set at
7451        // the same pre-addition boundary — this pin fails at caixa-core
7452        // build time on the pairwise-distinct + arm-count invariants.
7453        //
7454        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
7455        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7456        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7457        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7458        // pins on the peer closed-set typed-enum axes.
7459        let all: &[RestartStrategy] = RestartStrategy::ALL;
7460        assert_eq!(
7461            all.len(),
7462            4,
7463            "RestartStrategy::ALL must enumerate every variant of the \
7464             four-arm closed set (OneForOne, OneForAll, RestForOne, \
7465             SimpleOneForOne); got {all:?}"
7466        );
7467        for (i, a) in all.iter().enumerate() {
7468            for (j, b) in all.iter().enumerate() {
7469                if i != j {
7470                    assert_ne!(
7471                        a, b,
7472                        "RestartStrategy::ALL must carry every variant exactly \
7473                         once — got duplicate {a:?} at indices {i} and {j}"
7474                    );
7475                }
7476            }
7477        }
7478        for variant in [
7479            RestartStrategy::OneForOne,
7480            RestartStrategy::OneForAll,
7481            RestartStrategy::RestForOne,
7482            RestartStrategy::SimpleOneForOne,
7483        ] {
7484            assert!(
7485                all.contains(&variant),
7486                "RestartStrategy::ALL must contain {variant:?} — a future arm \
7487                 addition that grows the enum but forgets to grow the ALL slice \
7488                 silently truncates every downstream consumer's accept-set at \
7489                 the pre-addition boundary"
7490            );
7491        }
7492    }
7493
7494    #[test]
7495    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
7496        // Fail-before-pass-after pin on the forward accept-set of the
7497        // [`RestartStrategy::from_wire`] reverse projection: every
7498        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7499        // constant the [`RestartStrategy::as_str`] emitter walks parses
7500        // back to its paired variant. Any future arm addition that
7501        // grows the emitter's `as_str` match but forgets to grow the
7502        // parser's `from_wire` match silently splits the two halves of
7503        // the round-trip — the wire byte-string one non-serde consumer
7504        // parses from the one the emitter wrote — with the failure
7505        // surfacing at parse time far from the rebrand commit. Pinning
7506        // the four-arm accept-set here catches the drift at caixa-core
7507        // build time.
7508        //
7509        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
7510        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
7511        // accept-set pins on the peer closed-set typed-enum `str → Self`
7512        // axes.
7513        for (wire, expected) in [
7514            (
7515                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7516                RestartStrategy::OneForOne,
7517            ),
7518            (
7519                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7520                RestartStrategy::OneForAll,
7521            ),
7522            (
7523                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7524                RestartStrategy::RestForOne,
7525            ),
7526            (
7527                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7528                RestartStrategy::SimpleOneForOne,
7529            ),
7530        ] {
7531            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7532                panic!(
7533                    "RestartStrategy::from_wire({wire:?}) must accept every \
7534                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
7535                     lifted canonical byte-string that RestartStrategy::{expected:?} \
7536                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
7537                )
7538            });
7539            assert_eq!(
7540                parsed, expected,
7541                "RestartStrategy::from_wire({wire:?}) must return \
7542                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
7543            );
7544        }
7545    }
7546
7547    #[test]
7548    fn restart_strategy_from_wire_round_trips_through_as_str() {
7549        // Fail-before-pass-after pin on the closed round-trip between
7550        // the forward [`RestartStrategy::as_str`] emitter and the
7551        // reverse [`RestartStrategy::from_wire`] parser: for every
7552        // variant in [`RestartStrategy::ALL`], parsing the emitter's
7553        // output must return exactly the same variant. Any per-arm
7554        // divergence — a future arm added to `as_str` but not
7555        // `from_wire`, an accidental copy-paste flip in one but not
7556        // the other — silently splits the emit and parse halves and
7557        // the failure surfaces at consumer parse time far from the
7558        // drift site. The `ALL`-iterating shape means a future arm
7559        // addition picks up the coverage by construction.
7560        //
7561        // Peer of the sibling
7562        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
7563        // (18c7342) round-trip pin on
7564        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
7565        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
7566        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
7567        for &variant in RestartStrategy::ALL {
7568            let wire = variant.as_str();
7569            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7570                panic!(
7571                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7572                     must be Some({variant:?}) — the two halves of the round-trip \
7573                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
7574                     got None on wire byte-string {wire:?}"
7575                )
7576            });
7577            assert_eq!(
7578                parsed, variant,
7579                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7580                 must round-trip to the same variant; got {parsed:?}"
7581            );
7582        }
7583    }
7584
7585    #[test]
7586    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
7587        // Fail-before-pass-after pin on the closed-set refusal
7588        // discipline of [`RestartStrategy::from_wire`]: every
7589        // byte-string outside the four-arm accept-set returns `None`
7590        // rather than silently collapsing onto the [`Default`]
7591        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
7592        // exercised here sweeps the load-bearing drift shapes: the
7593        // empty string (a stripped serde-attribute drift), all-
7594        // whitespace strings (the canonical text-editor accidental
7595        // padding shape), the kebab-case dispatcher-catalog identities
7596        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
7597        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
7598        // derived [`std::str::FromStr`] accept-set, which parses the
7599        // *other* axis of this enum's two-axis split and must not leak
7600        // into the `from_wire` PascalCase-wire accept-set), the
7601        // lowercased single-word forms (`"oneforone"`), the padded
7602        // canonical scalar (`" OneForOne "`), the trailing-newline
7603        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
7604        // (`"AllForOne"` — the canonical typo direction).
7605        //
7606        // Peer of the sibling
7607        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
7608        // (2aa6d23) +
7609        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
7610        // (18c7342) refusal pins on the peer closed-set typed-enum
7611        // axes.
7612        for bad in [
7613            "",
7614            " ",
7615            "\n",
7616            "\t",
7617            "one-for-one",
7618            "one-for-all",
7619            "rest-for-one",
7620            "simple-one-for-one",
7621            "oneforone",
7622            "OneForOnes",
7623            "one_for_one",
7624            "one for one",
7625            "ONEFORONE",
7626            "OneForOne ",
7627            " OneForOne",
7628            " SimpleOneForOne ",
7629            "OneForOne\n",
7630            "restforone",
7631            "REST_FOR_ONE",
7632            "AllForOne",
7633            "Simple",
7634            "?",
7635        ] {
7636            assert!(
7637                RestartStrategy::from_wire(bad).is_none(),
7638                "RestartStrategy::from_wire({bad:?}) must return None — the \
7639                 parser's accept-set is exactly the four RestartStrategy::as_str \
7640                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
7641                 and this byte-string is outside that closed set"
7642            );
7643        }
7644    }
7645
7646    #[test]
7647    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
7648        // Fail-before-pass-after pin on the fourth path of the four-path
7649        // convergence: `from_wire` (the reverse projection) inverts the
7650        // `Serialize` derive's wire byte-string on every variant.
7651        // Together with the pre-existing three-path convergence
7652        // (`Display` + `as_str` + `Serialize` all resolve to the same
7653        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
7654        // pinned by
7655        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
7656        // this closes the round-trip: the wire byte-string the
7657        // `Serialize` derive emits parses back to the same variant
7658        // through `from_wire`, so any future serde-attribute or variant-
7659        // rename drift on the emit half now surfaces as a matched drift
7660        // on the parse half at caixa-core build time — the two halves
7661        // migrate as a unit through the lifted consts on any future
7662        // rename, and the round-trip cannot silently split.
7663        //
7664        // Peer of the sibling
7665        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7666        // (18c7342) wire-format pin on
7667        // [`crate::aplicacao::PlacementStrategy::from_wire`].
7668        for &variant in RestartStrategy::ALL {
7669            let wire = serde_json::to_string(&variant).unwrap();
7670            let unquoted = wire
7671                .strip_prefix('"')
7672                .and_then(|s| s.strip_suffix('"'))
7673                .expect("serialized RestartStrategy is a JSON string");
7674            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
7675                panic!(
7676                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
7677                     Serialize derive's wire byte-string for \
7678                     RestartStrategy::{variant:?} — the four-path convergence \
7679                     (Display + as_str + Serialize + from_wire) resolves through \
7680                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
7681                )
7682            });
7683            assert_eq!(
7684                parsed, variant,
7685                "RestartStrategy::from_wire of the Serialize derive's wire \
7686                 byte-string for RestartStrategy::{variant:?} must round-trip \
7687                 to the same variant; got {parsed:?}"
7688            );
7689        }
7690    }
7691
7692    #[test]
7693    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
7694        // Fail-before-pass-after byte-parity pin on the newly lifted
7695        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
7696        // library trait impl and the substrate-primitive
7697        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
7698        // the same four-arm accept-set across every arm the exhaustive
7699        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7700        // detour that routes the trait impl through a divergent projection
7701        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
7702        // … }` re-inlining that opens a compile-time link to the un-
7703        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
7704        // attribute drift that silently splits the wire byte-string from
7705        // every consumer that reaches for this typed dispatch, an
7706        // accidental swap onto the kebab-case dispatcher-catalog axis the
7707        // pre-existing [`std::str::FromStr`] impl parses through and which
7708        // would collide the two-axis wire/catalog split the sibling
7709        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
7710        // trips at caixa-core test time under `assert_eq!` rather than at
7711        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
7712        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
7713        // carries so no arm's projection is covered only by the sibling
7714        // method-named `from_wire` path. Peer of the sibling
7715        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
7716        // (3c83606),
7717        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
7718        // (bf33136), and the M3
7719        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
7720        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
7721        // onto the first M2-OTP-shape closed-set typed enum on the caixa
7722        // surface.
7723        for &variant in RestartStrategy::ALL {
7724            let wire = variant.as_str();
7725            assert_eq!(
7726                <RestartStrategy as TryFrom<&str>>::try_from(wire),
7727                Ok(variant),
7728                "TryFrom<&str> impl on RestartStrategy must round-trip \
7729                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
7730                 Ok(RestartStrategy::{variant:?}) — divergence from \
7731                 RestartStrategy::from_wire signals a silent detour off \
7732                 the substrate-primitive accessor"
7733            );
7734            assert_eq!(
7735                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
7736                RestartStrategy::from_wire(wire),
7737                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
7738                 RestartStrategy::from_wire on the same input"
7739            );
7740        }
7741    }
7742
7743    #[test]
7744    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
7745        // Rejection witness on the `impl TryFrom<&str> for
7746        // RestartStrategy` — sweeps a candidate set of byte-strings
7747        // outside the four-arm PascalCase wire accept-set the sibling
7748        // [`RestartStrategy::as_str`] emits and asserts every one lands on
7749        // `Err(())`, so a future accidental widening of the trait impl's
7750        // accept-set (a stray additional
7751        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
7752        // path, a silent inclusion of the kebab-case dispatcher-catalog
7753        // byte-string the pre-existing [`std::str::FromStr`] impl the
7754        // [`gen_platform::FromStrKind`] derive installs parses onto the
7755        // wire axis — which would collide the two-axis
7756        // wire/dispatcher-catalog split the sibling
7757        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
7758        // an English-rebrand or plural-arm silent alias that would
7759        // widen the wire accept-set past the OTP-canonical four) trips at
7760        // caixa-core test time. The candidate set includes the empty
7761        // string, whitespace-only padding, the kebab-case dispatcher-
7762        // catalog byte-strings on the sibling axis (a caller who confuses
7763        // the two axes trips here rather than at a downstream consumer's
7764        // silent reject), a lowercase / uppercase / mixed-case fold of
7765        // each PascalCase arm (a caller who assumes case-fold acceptance
7766        // trips here), leading/trailing whitespace padding, the trailing-
7767        // newline shape, quote-wrapped candidates, and a residual set of
7768        // plausible-but-wrong English rebrand candidates. Peer of the
7769        // sibling
7770        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
7771        // (3c83606) and
7772        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
7773        // (6fd00cd) rejection witnesses.
7774        let rejected: &[&str] = &[
7775            "",
7776            " ",
7777            "\n",
7778            "\t",
7779            "one-for-one",
7780            "one-for-all",
7781            "rest-for-one",
7782            "simple-one-for-one",
7783            "oneforone",
7784            "one_for_one",
7785            "OneForOnes",
7786            "ONEFORONE",
7787            "oneforall",
7788            "restforone",
7789            "simpleoneforone",
7790            "OneForOne ",
7791            " OneForOne",
7792            " OneForAll ",
7793            "OneForOne\n",
7794            "RestForOne\t",
7795            "OneForEach",
7796            "AllForOne",
7797            "one for one",
7798            "\"OneForOne\"",
7799            "?",
7800        ];
7801        for &input in rejected {
7802            assert_eq!(
7803                <RestartStrategy as TryFrom<&str>>::try_from(input),
7804                Err(()),
7805                "TryFrom<&str> impl on RestartStrategy must reject the \
7806                 non-wire byte-string {input:?} — silent acceptance signals \
7807                 an accept-set widening off the paired \
7808                 RestartStrategy::from_wire resolver"
7809            );
7810        }
7811    }
7812
7813    #[test]
7814    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
7815        // Cross-axis partition pin: the paired `TryFrom<&str>` and
7816        // `from_wire` reverse projections must resolve identically on
7817        // *every* input, not just the ones [`RestartStrategy::ALL`]
7818        // enumerates. Sweeps a mixed candidate set spanning accepted
7819        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
7820        // dispatcher-catalog byte-strings, empty, whitespace-padded,
7821        // quoted, English-rebrand candidates) inputs and asserts the
7822        // trait's `Result::ok()` projection byte-equals the method-named
7823        // resolver's `Option<Self>` return-shape on each, locking the two
7824        // paths together by construction so any future detour (a stray
7825        // `try_from` special-case that widens or narrows the accept-set
7826        // outside the paired `from_wire` resolver, an accidental swap
7827        // onto the kebab-case [`std::str::FromStr`] impl the
7828        // [`gen_platform::FromStrKind`] derive installs on the sibling
7829        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
7830        // the sibling
7831        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
7832        // pin — extends the round-trip discipline onto the M2-OTP-shape
7833        // sibling-restart axis.
7834        let candidates: &[&str] = &[
7835            "OneForOne",
7836            "OneForAll",
7837            "RestForOne",
7838            "SimpleOneForOne",
7839            "",
7840            "one-for-one",
7841            "one-for-all",
7842            "rest-for-one",
7843            "simple-one-for-one",
7844            "oneforone",
7845            "unknown",
7846            "OneForOne ",
7847            " OneForOne",
7848            "\"OneForOne\"",
7849            "OneForEach",
7850            "?",
7851        ];
7852        for &input in candidates {
7853            let via_trait: Option<RestartStrategy> =
7854                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
7855            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
7856            assert_eq!(
7857                via_trait, via_method,
7858                "TryFrom<&str> and from_wire must resolve identically on \
7859                 input {input:?} — divergence signals the two reverse-\
7860                 projection paths have drifted onto different accept-sets"
7861            );
7862        }
7863    }
7864
7865    #[test]
7866    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
7867        // Fail-before-pass-after byte-parity pin on the newly lifted
7868        // `impl From<RestartStrategy> for &'static str` — asserts the
7869        // standard-library trait impl and the substrate-primitive
7870        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
7871        // the same four-arm emit-set across every arm the exhaustive
7872        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7873        // detour that routes the trait impl through a divergent
7874        // projection (a per-arm inline `match strategy { OneForOne =>
7875        // "OneForOne", … }` re-inlining that opens a compile-time link to
7876        // the un-lifted arm-literal, an accidental swap onto the sibling
7877        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
7878        // would collide the two-axis wire/catalog split the sibling
7879        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
7880        // at caixa-core test time under `assert_eq!` rather than at a
7881        // downstream `impl Into<&'static str>`-bound consumer's silent
7882        // split. Sweeps every one of the four arms
7883        // [`RestartStrategy::ALL`] carries so no arm's projection is
7884        // covered only by the sibling method-named `as_str` /
7885        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
7886        // `<&'static str as From<RestartStrategy>>::from` output in a
7887        // `const`-shape binding to make the `'static` lifetime promise a
7888        // build-time invariant — a future accidental downgrade of any of
7889        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7890        // constants to a non-`&'static str` (a `String::leak()`-produced
7891        // return, a `Box::leak`-cast) trips at caixa-core build time
7892        // rather than at a downstream `'static`-bound consumer.
7893        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7894        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7895        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7896        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7897        for &variant in RestartStrategy::ALL {
7898            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7899            let via_method: &'static str = variant.as_str();
7900            assert_eq!(
7901                via_trait, via_method,
7902                "From<RestartStrategy> for &'static str impl must round-trip \
7903                 RestartStrategy::{variant:?} to the same lifted \
7904                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
7905                 divergence signals a silent detour off the substrate-primitive \
7906                 accessor"
7907            );
7908            let via_into: &'static str = variant.into();
7909            assert_eq!(
7910                via_into, via_method,
7911                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
7912                 byte-equal RestartStrategy::as_str on the same input — the \
7913                 blanket-derived Into shape must resolve to the same as_str \
7914                 dispatch as the explicit From impl"
7915            );
7916        }
7917        assert_eq!(
7918            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7919            [
7920                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7921                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7922                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7923                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7924            ],
7925            "const-context RestartStrategy::as_str must resolve to the four \
7926             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
7927             downgrade of any arm to a non-const or non-static byte-string \
7928             breaks the `&'static str`-lifetime promise the paired \
7929             From<RestartStrategy> for &'static str impl carries by \
7930             construction"
7931        );
7932    }
7933
7934    #[test]
7935    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
7936        // Cross-axis partition pin: the paired trait-idiomatic
7937        // `From<RestartStrategy> for &'static str` forward projection and
7938        // the method-named [`RestartStrategy::as_str`] forward projection
7939        // must resolve identically on *every* arm, not just the ones
7940        // named in the primary byte-parity pin above. Sweeps every
7941        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
7942        // output byte-equals the method-named accessor's return-value on
7943        // each, locking the two forward-projection paths together by
7944        // construction so any future detour (a stray `From` special-case
7945        // that lands on a divergent per-arm literal outside the paired
7946        // `as_str` dispatch, a hypothetical rebrand touching one axis
7947        // without the other) trips at caixa-core test time. Peer of the
7948        // sibling reverse-projection partition pin
7949        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7950        // — extends the round-trip discipline onto the trait-idiomatic
7951        // *forward* axis, closing the two-way `Self ↔ &'static str`
7952        // round-trip on the trait-idiomatic pair
7953        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
7954        // well as the pre-existing method-named pair
7955        // (`as_str` + `from_wire`).
7956        for &variant in RestartStrategy::ALL {
7957            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7958            let via_method: &'static str = variant.as_str();
7959            assert_eq!(
7960                via_trait, via_method,
7961                "From<RestartStrategy> for &'static str and \
7962                 RestartStrategy::as_str must resolve identically on \
7963                 RestartStrategy::{variant:?} — divergence signals the \
7964                 two forward-projection paths have drifted onto different \
7965                 emit-sets"
7966            );
7967        }
7968        // Round-trip witness: every arm's forward `From` output re-parses
7969        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
7970        // to the original variant. Closes the two-way `RestartStrategy ↔
7971        // &'static str` round-trip on the trait-idiomatic axis pair,
7972        // mirroring the pre-existing method-named `as_str` + `from_wire`
7973        // round-trip on the substrate-primitive axis pair.
7974        for &variant in RestartStrategy::ALL {
7975            let emitted: &'static str = variant.into();
7976            let re_parsed: Result<RestartStrategy, ()> =
7977                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7978            assert_eq!(
7979                re_parsed,
7980                Ok(variant),
7981                "trait-idiomatic axis pair must round-trip \
7982                 RestartStrategy::{variant:?} through `.into::<&'static \
7983                 str>()` and back through `TryFrom<&str>` — a break signals \
7984                 the forward-emit and reverse-parse axes have drifted onto \
7985                 different vocabularies"
7986            );
7987        }
7988    }
7989
7990    #[test]
7991    fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
7992        // Fail-before-pass-after byte-parity pin on the newly lifted
7993        // `impl From<&RestartStrategy> for &'static str` — asserts the
7994        // borrowed-input standard-library trait impl and the substrate-
7995        // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
7996        // resolve to the same four-arm emit-set across every arm the
7997        // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
7998        // `From` trait does not auto-derive the borrowed-input sibling
7999        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8000        // where T: Copy, U: From<T>` blanket in `core`), so the
8001        // borrowed-input axis is a distinct trait-idiomatic surface
8002        // that a `.iter().map(Into::into)` shape over
8003        // [`RestartStrategy::ALL`] (whose iterator yields
8004        // `&RestartStrategy`, not `RestartStrategy`) reaches through
8005        // this impl and no other — the paired owned-input
8006        // [`From<RestartStrategy>`] impl requires an explicit
8007        // `.copied()` / dereference before the trait fires.
8008        // Materializes the `<&'static str as
8009        // From<&RestartStrategy>>::from` output in a `const`-shape
8010        // binding to make the `'static` lifetime promise a build-time
8011        // invariant.
8012        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8013        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8014        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8015        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8016        for variant in RestartStrategy::ALL {
8017            let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
8018            let via_method: &'static str = variant.as_str();
8019            assert_eq!(
8020                via_trait, via_method,
8021                "From<&RestartStrategy> for &'static str impl must \
8022                 round-trip &RestartStrategy::{variant:?} to the same \
8023                 lifted SUPERVISOR_ESTRATEGIA_* const \
8024                 RestartStrategy::as_str returns — divergence signals a \
8025                 silent detour off the substrate-primitive accessor"
8026            );
8027            let via_into: &'static str = variant.into();
8028            assert_eq!(
8029                via_into, via_method,
8030                "Into<&'static str>::into on &RestartStrategy::{variant:?} \
8031                 must byte-equal RestartStrategy::as_str on the same input — \
8032                 the blanket-derived Into shape must resolve to the same \
8033                 as_str dispatch as the explicit From impl"
8034            );
8035        }
8036        assert_eq!(
8037            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8038            [
8039                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8040                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8041                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8042                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8043            ],
8044            "const-context RestartStrategy::as_str must resolve to the \
8045             four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
8046             input From<&RestartStrategy> for &'static str impl inherits \
8047             its `'static` lifetime promise from the same accessor the \
8048             owned-input sibling routes through"
8049        );
8050    }
8051
8052    #[test]
8053    fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8054        // Cross-axis partition pin: the paired trait-idiomatic
8055        // owned-input `From<RestartStrategy> for &'static str` (523157d
8056        // campaign-shape) and borrowed-input `From<&RestartStrategy> for
8057        // &'static str` (this lift) forward projections must resolve
8058        // identically on every arm, locking the two input-shape paths
8059        // together so any future detour trips at caixa-core test time.
8060        // Then a witness that a `.iter().map(Into::into)` pipe over
8061        // [`RestartStrategy::ALL`] (whose iterator yields
8062        // `&RestartStrategy`) materializes the four-arm accept-set
8063        // through the borrowed-input axis alone — the exact shape a
8064        // future wasm-operator per-supervisor sibling-restart-strategy
8065        // diagnostic line, a future substrate-wide per-arm diagnostic
8066        // column, or a
8067        // `HashMap::<&'static str, RestartStrategy>::from_iter(
8068        //     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
8069        // per-strategy lookup reaches through — closing the two-way
8070        // owned/borrowed input-shape symmetry on the forward-projection
8071        // trait-idiomatic axis. Peer of the sibling
8072        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8073        // (64aa742) /
8074        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8075        // (5ab993a) /
8076        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8077        // (807b0b5) partition pins on the sibling closed-set typed-enum
8078        // discriminator axes — extends the borrowed-input axis
8079        // discipline onto the first M2 OTP-shape sibling-restart
8080        // closed-set typed enum on the caixa surface. Also closes the
8081        // direct two-way `&Self → &'static str → Self` round-trip via
8082        // the paired [`TryFrom<&str>`] axis — unlike the peer
8083        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
8084        // lowercase Portuguese diagnostic bytes while the reverse
8085        // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
8086        // trip through an intermediate wire-vocab hop), the
8087        // [`RestartStrategy::as_str`] emit and
8088        // [`RestartStrategy::from_wire`] parse share the same
8089        // `PascalCase` vocabulary by construction, so the borrowed-
8090        // input forward axis and the reverse axis compose directly.
8091        for &variant in RestartStrategy::ALL {
8092            let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8093            let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
8094            assert_eq!(
8095                owned, borrowed,
8096                "From<RestartStrategy> and From<&RestartStrategy> for \
8097                 &'static str must resolve identically on \
8098                 RestartStrategy::{variant:?} — divergence signals the \
8099                 owned-input and borrowed-input forward-projection paths \
8100                 have drifted onto different emit-sets"
8101            );
8102        }
8103        let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
8104        let via_method: Vec<&'static str> =
8105            RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
8106        assert_eq!(
8107            via_iter, via_method,
8108            "`.iter().map(Into::into)` over RestartStrategy::ALL must \
8109             byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
8110             borrowed-input `From<&RestartStrategy> for &'static str` \
8111             axis is what makes the `.iter().map(Into::into)` shape route \
8112             through the substrate-primitive `RestartStrategy::as_str` \
8113             accessor rather than through a per-call-site `.copied()` / \
8114             dereference detour"
8115        );
8116        for variant in RestartStrategy::ALL {
8117            let emitted: &'static str = variant.into();
8118            let re_parsed: Result<RestartStrategy, ()> =
8119                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8120            assert_eq!(
8121                re_parsed,
8122                Ok(*variant),
8123                "trait-idiomatic borrowed-input forward-projection + \
8124                 reverse-projection axis pair must round-trip \
8125                 &RestartStrategy::{variant:?} through `.into::<&'static \
8126                 str>()` (via the borrowed-input axis) and back through \
8127                 `TryFrom<&str>` — a break signals the borrowed-input \
8128                 forward-emit and reverse-parse axes have drifted onto \
8129                 different vocabularies"
8130            );
8131        }
8132    }
8133
8134    #[test]
8135    fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
8136        // Fail-before-pass-after byte-parity pin on the newly lifted
8137        // `impl From<RestartStrategy> for String` — asserts the
8138        // owned-`String`-returning standard-library trait impl and the
8139        // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
8140        // accessor resolve to the same four-arm emit-set across every
8141        // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
8142        // Rust's standard library does not carry a blanket
8143        // `impl<T: AsRef<str>> From<T> for String` (nor an
8144        // `impl<T: fmt::Display> From<T> for String`), so the
8145        // owned-`String` forward-projection axis is a distinct
8146        // trait-idiomatic surface that a
8147        // `let key: String = strategy.into();`-shaped call site
8148        // reaches through this impl and no other — the paired sibling
8149        // `From<RestartStrategy> for &'static str` impl forces every
8150        // owned-`String` call site through an explicit
8151        // `.to_owned()` / `String::from` restatement.
8152        for &variant in RestartStrategy::ALL {
8153            let via_trait: String = <String as From<RestartStrategy>>::from(variant);
8154            let via_method: &'static str = variant.as_str();
8155            assert_eq!(
8156                via_trait.as_str(),
8157                via_method,
8158                "From<RestartStrategy> for String impl must round-trip \
8159                 RestartStrategy::{variant:?} to the same lifted \
8160                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8161                 returns — divergence signals a silent detour off the \
8162                 substrate-primitive accessor"
8163            );
8164            let via_into: String = variant.into();
8165            assert_eq!(
8166                via_into.as_str(),
8167                via_method,
8168                "Into<String>::into on RestartStrategy::{variant:?} must \
8169                 byte-equal RestartStrategy::as_str on the same input — the \
8170                 blanket-derived Into shape must resolve to the same as_str \
8171                 dispatch as the explicit From impl"
8172            );
8173        }
8174    }
8175
8176    #[test]
8177    fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
8178        // Cross-axis partition pin: the paired trait-idiomatic
8179        // owned-`String` `From<RestartStrategy> for String` (this lift)
8180        // and owned-`&'static str` `From<RestartStrategy> for &'static
8181        // str` (523157d) forward projections must resolve identically
8182        // on every arm, locking the two return-type-shape paths
8183        // together so any future detour trips at caixa-core test time.
8184        // Also byte-parity witness against the sibling
8185        // [`ToString::to_string`] surface routed through
8186        // [`std::fmt::Display`] — the three owned-heap-string paths
8187        // (`.into::<String>()`, `String::from`, `.to_string()`) must
8188        // resolve identically on every arm so a future consumer that
8189        // picks any of the three lands on the same lifted
8190        // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
8191        // witness through the paired trait-idiomatic reverse
8192        // [`TryFrom<&str>`] axis on the owned-`String`'s
8193        // [`String::as_str`] borrow that closes the two-way
8194        // `Self → String → Self` round-trip on the trait-idiomatic
8195        // owned-`String` forward + reverse axis pair.
8196        for &variant in RestartStrategy::ALL {
8197            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8198            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8199            assert_eq!(
8200                owned_string.as_str(),
8201                owned_static,
8202                "From<RestartStrategy> for String and From<RestartStrategy> \
8203                 for &'static str must resolve identically on \
8204                 RestartStrategy::{variant:?} — divergence signals the \
8205                 owned-`String` and owned-`&'static str` forward-projection \
8206                 return-type-shape paths have drifted onto different \
8207                 emit-sets"
8208            );
8209            let via_to_string: String = variant.to_string();
8210            assert_eq!(
8211                owned_string, via_to_string,
8212                "From<RestartStrategy> for String must byte-equal \
8213                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8214                 divergence signals the trait-idiomatic owned-`String` \
8215                 forward-projection axis and the ToString-through-Display \
8216                 axis have drifted onto different emit-sets"
8217            );
8218        }
8219        let via_iter: Vec<String> = RestartStrategy::ALL
8220            .iter()
8221            .copied()
8222            .map(String::from)
8223            .collect();
8224        let via_method: Vec<String> = RestartStrategy::ALL
8225            .iter()
8226            .map(|s| s.as_str().to_owned())
8227            .collect();
8228        assert_eq!(
8229            via_iter, via_method,
8230            "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
8231             must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
8232             every arm — the owned-`String` `From<RestartStrategy> for \
8233             String` axis is what makes the `String::from` composition \
8234             route through the substrate-primitive `RestartStrategy::as_str` \
8235             accessor rather than through a per-call-site `.to_owned()` / \
8236             `String::from(strategy.as_str())` detour"
8237        );
8238        for &variant in RestartStrategy::ALL {
8239            let emitted: String = variant.into();
8240            let re_parsed: Result<RestartStrategy, ()> =
8241                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8242            assert_eq!(
8243                re_parsed,
8244                Ok(variant),
8245                "trait-idiomatic owned-`String` forward-projection + \
8246                 reverse-projection axis pair must round-trip \
8247                 RestartStrategy::{variant:?} through `.into::<String>()` \
8248                 and back through `TryFrom<&str>` on the owned-`String`'s \
8249                 String::as_str borrow — a break signals the owned-`String` \
8250                 forward-emit and reverse-parse axes have drifted onto \
8251                 different vocabularies"
8252            );
8253        }
8254    }
8255
8256    #[test]
8257    fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
8258        // Fail-before-pass-after byte-parity pin on the newly lifted
8259        // `impl From<&RestartStrategy> for String` — asserts the
8260        // borrowed-input owned-`String`-returning standard-library trait
8261        // impl and the substrate-primitive [`RestartStrategy::as_str`]
8262        // `pub const fn` accessor resolve to the same four-arm emit-set
8263        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
8264        // enumerates. Rust's standard library does not carry a blanket
8265        // `impl<T: AsRef<str>> From<&T> for String` (nor an
8266        // `impl<T: fmt::Display> From<&T> for String`), so the
8267        // borrowed-input owned-`String` forward-projection axis is a
8268        // distinct trait-idiomatic surface that a
8269        // `let key: String = (&strategy).into();`-shaped call site
8270        // reaches through this impl and no other — the paired sibling
8271        // `From<RestartStrategy> for String` impl forces every
8272        // borrowed-input call site through an explicit `Copy` deref
8273        // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
8274        // `.to_string()` detour.
8275        for &variant in RestartStrategy::ALL {
8276            let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
8277            let via_method: &'static str = variant.as_str();
8278            assert_eq!(
8279                via_trait.as_str(),
8280                via_method,
8281                "From<&RestartStrategy> for String impl must round-trip \
8282                 &RestartStrategy::{variant:?} to the same lifted \
8283                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8284                 returns — divergence signals a silent detour off the \
8285                 substrate-primitive accessor"
8286            );
8287            let via_into: String = (&variant).into();
8288            assert_eq!(
8289                via_into.as_str(),
8290                via_method,
8291                "Into<String>::into on &RestartStrategy::{variant:?} must \
8292                 byte-equal RestartStrategy::as_str on the same input — the \
8293                 blanket-derived Into shape must resolve to the same as_str \
8294                 dispatch as the explicit From impl"
8295            );
8296        }
8297    }
8298
8299    #[test]
8300    fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
8301        // Cross-axis partition pin: the newly lifted trait-idiomatic
8302        // borrowed-input owned-`String` `From<&RestartStrategy> for
8303        // String` (this lift), the paired owned-input owned-`String`
8304        // `From<RestartStrategy> for String` (7baa18a), the paired
8305        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8306        // for &'static str` (e941836), and the paired owned-input
8307        // owned-`&'static str` `From<RestartStrategy> for &'static str`
8308        // (523157d) — every corner of the `{Self, &Self} × {&'static
8309        // str, String}` 2×2 trait-idiomatic projection family — must
8310        // resolve identically on every arm, locking the four
8311        // return-shape × input-shape paths together so any future
8312        // detour trips at caixa-core test time. Also byte-parity
8313        // witness against the sibling [`ToString::to_string`] surface
8314        // routed through [`std::fmt::Display`] and a direct round-trip
8315        // witness through the paired trait-idiomatic reverse
8316        // [`TryFrom<&str>`] axis on the owned-`String`'s
8317        // [`String::as_str`] borrow that closes the two-way
8318        // `&Self → String → Self` round-trip on the trait-idiomatic
8319        // borrowed-input owned-`String` forward + reverse axis pair.
8320        for &variant in RestartStrategy::ALL {
8321            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
8322            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8323            let borrowed_static: &'static str =
8324                <&'static str as From<&RestartStrategy>>::from(&variant);
8325            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8326            assert_eq!(
8327                borrowed_string, owned_string,
8328                "From<&RestartStrategy> for String and From<RestartStrategy> \
8329                 for String must resolve identically on \
8330                 RestartStrategy::{variant:?} — divergence signals the \
8331                 borrowed-input and owned-input owned-`String` \
8332                 forward-projection input-shape paths have drifted onto \
8333                 different emit-sets"
8334            );
8335            assert_eq!(
8336                borrowed_string.as_str(),
8337                borrowed_static,
8338                "From<&RestartStrategy> for String and From<&RestartStrategy> \
8339                 for &'static str must resolve identically on \
8340                 RestartStrategy::{variant:?} — divergence signals the \
8341                 borrowed-input `&'static str` and owned-`String` \
8342                 return-shape paths have drifted onto different emit-sets"
8343            );
8344            assert_eq!(
8345                borrowed_string.as_str(),
8346                owned_static,
8347                "From<&RestartStrategy> for String and From<RestartStrategy> \
8348                 for &'static str must resolve identically on \
8349                 RestartStrategy::{variant:?} — divergence signals a break \
8350                 in the diagonal corner of the {{Self, &Self}} × \
8351                 {{&'static str, String}} 2×2 trait-idiomatic \
8352                 projection family"
8353            );
8354            let via_to_string: String = variant.to_string();
8355            assert_eq!(
8356                borrowed_string, via_to_string,
8357                "From<&RestartStrategy> for String must byte-equal \
8358                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8359                 divergence signals the trait-idiomatic borrowed-input \
8360                 owned-`String` forward-projection axis and the \
8361                 ToString-through-Display axis have drifted onto different \
8362                 emit-sets"
8363            );
8364        }
8365        let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
8366        let via_method: Vec<String> = RestartStrategy::ALL
8367            .iter()
8368            .map(|s| s.as_str().to_owned())
8369            .collect();
8370        assert_eq!(
8371            via_iter, via_method,
8372            "`.iter().map(String::from)` over RestartStrategy::ALL — a \
8373             call site whose iteration axis holds `&RestartStrategy` by \
8374             construction — must byte-equal `.iter().map(|s| \
8375             s.as_str().to_owned())` on every arm — the borrowed-input \
8376             owned-`String` `From<&RestartStrategy> for String` axis is \
8377             what makes the `String::from` composition route through the \
8378             substrate-primitive `RestartStrategy::as_str` accessor \
8379             without a spurious `Copy` deref (which would only be \
8380             reachable through the owned-input `From<RestartStrategy> for \
8381             String` axis by first calling `.copied()` on the iterator)"
8382        );
8383        for &variant in RestartStrategy::ALL {
8384            let emitted: String = (&variant).into();
8385            let re_parsed: Result<RestartStrategy, ()> =
8386                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8387            assert_eq!(
8388                re_parsed,
8389                Ok(variant),
8390                "trait-idiomatic borrowed-input owned-`String` \
8391                 forward-projection + reverse-projection axis pair must \
8392                 round-trip &RestartStrategy::{variant:?} through \
8393                 `.into::<String>()` on the borrowed-input surface and \
8394                 back through `TryFrom<&str>` on the owned-`String`'s \
8395                 String::as_str borrow — a break signals the \
8396                 borrowed-input owned-`String` forward-emit and \
8397                 reverse-parse axes have drifted onto different \
8398                 vocabularies"
8399            );
8400        }
8401    }
8402
8403    #[test]
8404    fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
8405        // Fail-before-pass-after byte-parity pin on the newly lifted
8406        // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
8407        // asserts the standard-library trait impl and the substrate-
8408        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
8409        // accessor resolve to the same four-arm emit-set across every
8410        // arm the exhaustive [`super::RestartStrategy::ALL`] slice
8411        // enumerates. Rust's standard library does not carry a blanket
8412        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
8413        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
8414        // the `Cow<'static, str>` forward-projection axis is a
8415        // distinct trait-idiomatic surface that a
8416        // `let key: Cow<'static, str> = strategy.into();`-shaped call
8417        // site reaches through this impl and no other — the paired
8418        // sibling `From<RestartStrategy> for &'static str` and
8419        // `From<RestartStrategy> for String` impls force every
8420        // `Cow<'static, str>`-parameterized call site through a
8421        // `Cow::Borrowed(strategy.as_str())` /
8422        // `Cow::Owned(strategy.to_string())` composition whose type
8423        // bounds have no compile-time link back to the substrate
8424        // primitive.
8425        //
8426        // Also asserts the projection lands on the zero-alloc
8427        // [`std::borrow::Cow::Borrowed`] arm (not the
8428        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8429        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8430        // return lifetime by construction makes the borrowed arm the
8431        // type-correct projection with no runtime allocation. Any
8432        // future silent detour that routes the impl through the owned
8433        // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
8434        // that would allocate on every call site where the
8435        // `&'static str` return of [`super::RestartStrategy::as_str`]
8436        // makes the zero-alloc borrowed projection type-correct) trips
8437        // at caixa-core test time under the
8438        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
8439        // than at a downstream `Cow<'static, str>`-bound consumer's
8440        // silent allocation.
8441        //
8442        // First peer on the substrate-wide trait-idiomatic
8443        // [`std::borrow::Cow<'static, str>`] forward-projection family
8444        // to extend the axis off the top-level [`super::CaixaKind`]
8445        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
8446        // first M2 OTP-shape closed-set fieldless typed enum on the
8447        // caixa surface.
8448        for &variant in RestartStrategy::ALL {
8449            let via_trait: std::borrow::Cow<'static, str> =
8450                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8451            let via_method: &'static str = variant.as_str();
8452            assert_eq!(
8453                via_trait.as_ref(),
8454                via_method,
8455                "From<RestartStrategy> for Cow<'static, str> impl must \
8456                 round-trip RestartStrategy::{variant:?} to the same \
8457                 lifted SUPERVISOR_ESTRATEGIA_* const \
8458                 RestartStrategy::as_str returns — divergence signals a \
8459                 silent detour off the substrate-primitive accessor"
8460            );
8461            assert!(
8462                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
8463                "From<RestartStrategy> for Cow<'static, str> impl must \
8464                 land on the zero-alloc Cow::Borrowed arm on \
8465                 RestartStrategy::{variant:?} — a Cow::Owned outcome \
8466                 signals the projection has silently allocated where \
8467                 the substrate-primitive RestartStrategy::as_str \
8468                 `&'static str` return makes the borrowed arm the \
8469                 type-correct projection"
8470            );
8471            let via_into: std::borrow::Cow<'static, str> = variant.into();
8472            assert_eq!(
8473                via_into.as_ref(),
8474                via_method,
8475                "Into<Cow<'static, str>>::into on \
8476                 RestartStrategy::{variant:?} must byte-equal \
8477                 RestartStrategy::as_str on the same input — the \
8478                 blanket-derived Into shape must resolve to the same \
8479                 as_str dispatch as the explicit From impl"
8480            );
8481            assert!(
8482                matches!(via_into, std::borrow::Cow::Borrowed(_)),
8483                "Into<Cow<'static, str>>::into on \
8484                 RestartStrategy::{variant:?} must land on the \
8485                 zero-alloc Cow::Borrowed arm — the blanket-derived \
8486                 Into shape must resolve to the same Cow::Borrowed \
8487                 dispatch as the explicit From impl"
8488            );
8489        }
8490    }
8491
8492    #[test]
8493    fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
8494        // Cross-axis partition pin: the newly lifted trait-idiomatic
8495        // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
8496        // (this lift), the paired owned-input `From<RestartStrategy>
8497        // for &'static str` (523157d), and the paired owned-input
8498        // `From<RestartStrategy> for String` (7baa18a) forward
8499        // projections must resolve identically on every arm, locking
8500        // the three return-shape paths together by construction so any
8501        // future detour trips at caixa-core test time. Also byte-parity
8502        // witness against the sibling [`ToString::to_string`] surface
8503        // routed through [`std::fmt::Display`] — every owned-heap-
8504        // string path (the `Cow::Owned` promotion of this axis's
8505        // `.into_owned()`, `From<RestartStrategy> for String`, and
8506        // `.to_string()`) resolves to the same lifted
8507        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
8508        //
8509        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
8510        // witness over [`super::RestartStrategy::ALL`] that
8511        // materializes the four-arm accept-set through the
8512        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
8513        // shape a future `axum::response::IntoResponse` per-strategy
8514        // rejection-body composer, a future M4 admission-webhook
8515        // per-strategy rejection-reason emitter whose typing rules out
8516        // the sibling [`AsRef<str>`] borrowed return, or a future
8517        // substrate-wide per-strategy diagnostic surface that binds
8518        // through a [`Cow<'static, str>`] boundary reaches through.
8519        // The pipe witness also pins the zero-alloc discipline: every
8520        // element in the collected vector satisfies the
8521        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
8522        // accidental silent-allocation regression on the pipe's
8523        // iteration axis is a caixa-core-test-time failure.
8524        for &variant in RestartStrategy::ALL {
8525            let via_cow: std::borrow::Cow<'static, str> =
8526                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8527            let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8528            let via_string: String = <String as From<RestartStrategy>>::from(variant);
8529            assert_eq!(
8530                via_cow.as_ref(),
8531                via_static,
8532                "From<RestartStrategy> for Cow<'static, str> and \
8533                 From<RestartStrategy> for &'static str must resolve \
8534                 identically on RestartStrategy::{variant:?} — \
8535                 divergence signals the Cow<'static, str> and \
8536                 &'static str return-shape paths have drifted onto \
8537                 different emit-sets"
8538            );
8539            assert_eq!(
8540                via_cow.as_ref(),
8541                via_string.as_str(),
8542                "From<RestartStrategy> for Cow<'static, str> and \
8543                 From<RestartStrategy> for String must resolve \
8544                 identically on RestartStrategy::{variant:?} — \
8545                 divergence signals the Cow<'static, str> and String \
8546                 return-shape paths have drifted onto different \
8547                 emit-sets"
8548            );
8549            let via_to_string: String = variant.to_string();
8550            assert_eq!(
8551                via_cow.as_ref(),
8552                via_to_string.as_str(),
8553                "From<RestartStrategy> for Cow<'static, str> must \
8554                 byte-equal RestartStrategy::to_string on \
8555                 RestartStrategy::{variant:?} — divergence signals the \
8556                 trait-idiomatic Cow<'static, str> forward-projection \
8557                 axis and the ToString-through-Display axis have \
8558                 drifted onto different emit-sets"
8559            );
8560        }
8561        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8562            .iter()
8563            .copied()
8564            .map(std::borrow::Cow::from)
8565            .collect();
8566        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8567            .iter()
8568            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
8569            .collect();
8570        assert_eq!(
8571            via_iter, via_method,
8572            "`.iter().copied().map(Cow::from)` over \
8573             RestartStrategy::ALL must byte-equal `.iter().map(|s| \
8574             Cow::Borrowed(s.as_str()))` on every arm — the \
8575             trait-idiomatic `From<RestartStrategy> for Cow<'static, \
8576             str>` axis is what makes the `Cow::from` composition \
8577             route through the substrate-primitive \
8578             `RestartStrategy::as_str` accessor with the zero-alloc \
8579             Cow::Borrowed arm by construction, rather than a \
8580             per-call-site `Cow::Owned(strategy.to_string())` \
8581             allocation"
8582        );
8583        for cow in &via_iter {
8584            assert!(
8585                matches!(cow, std::borrow::Cow::Borrowed(_)),
8586                "every element of the \
8587                 .iter().copied().map(Cow::from) pipe over \
8588                 RestartStrategy::ALL must land on the zero-alloc \
8589                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
8590                 signals the pipe's iteration axis has silently \
8591                 allocated where the substrate-primitive \
8592                 RestartStrategy::as_str `&'static str` return makes \
8593                 the borrowed arm the type-correct projection"
8594            );
8595        }
8596    }
8597
8598    #[test]
8599    fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
8600        // Fail-before-pass-after byte-parity pin on the newly lifted
8601        // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
8602        // asserts the borrowed-input standard-library trait impl and
8603        // the substrate-primitive [`super::RestartStrategy::as_str`]
8604        // `pub const fn` accessor resolve to the same four-arm emit-
8605        // set across every arm the exhaustive
8606        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
8607        // standard library does not carry a blanket
8608        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
8609        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
8610        // the borrowed-input `Cow<'static, str>` forward-projection
8611        // axis is a distinct trait-idiomatic surface that a
8612        // `let key: Cow<'static, str> = (&strategy).into();`-shaped
8613        // call site or a
8614        // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
8615        // reaches through this impl and no other — the paired owned-
8616        // input `From<RestartStrategy> for Cow<'static, str>` impl
8617        // (7dd28b3) forces every borrowed-input call site through an
8618        // explicit `Copy` deref (`Cow::from(*strategy)`) or a
8619        // `Cow::Borrowed(strategy.as_str())` open-code whose type
8620        // bounds have no compile-time link back to the substrate
8621        // primitive.
8622        //
8623        // Also asserts the projection lands on the zero-alloc
8624        // [`std::borrow::Cow::Borrowed`] arm (not the
8625        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8626        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8627        // return lifetime by construction makes the borrowed arm the
8628        // type-correct projection with no runtime allocation on the
8629        // borrowed-input surface just as on the paired owned-input
8630        // surface.
8631        //
8632        // Second peer on the substrate-wide trait-idiomatic
8633        // [`std::borrow::Cow<'static, str>`] forward-projection family
8634        // on this enum — closes the `{Self, &Self}` input-shape
8635        // corner of the [`Cow<'static, str>`] axis on the first M2
8636        // OTP-shape closed-set fieldless typed enum peer on the caixa
8637        // surface (`:supervisor :estrategia`), exactly as d45c409
8638        // closed it on the top-level [`super::CaixaKind`] one commit
8639        // after the owning half (99c1735) landed. Every future
8640        // closed-set fieldless typed enum peer on the substrate is a
8641        // future target of the campaign.
8642        for &variant in RestartStrategy::ALL {
8643            let via_trait: std::borrow::Cow<'static, str> =
8644                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
8645            let via_method: &'static str = variant.as_str();
8646            assert_eq!(
8647                via_trait.as_ref(),
8648                via_method,
8649                "From<&RestartStrategy> for Cow<'static, str> impl must \
8650                 round-trip &RestartStrategy::{variant:?} to the same \
8651                 lifted SUPERVISOR_ESTRATEGIA_* const \
8652                 RestartStrategy::as_str returns — divergence signals a \
8653                 silent detour off the substrate-primitive accessor"
8654            );
8655            assert!(
8656                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
8657                "From<&RestartStrategy> for Cow<'static, str> impl must \
8658                 land on the zero-alloc Cow::Borrowed arm on \
8659                 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
8660                 signals the projection has silently allocated where \
8661                 the substrate-primitive RestartStrategy::as_str \
8662                 `&'static str` return makes the borrowed arm the \
8663                 type-correct projection"
8664            );
8665            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
8666            assert_eq!(
8667                via_into.as_ref(),
8668                via_method,
8669                "Into<Cow<'static, str>>::into on \
8670                 &RestartStrategy::{variant:?} must byte-equal \
8671                 RestartStrategy::as_str on the same input — the \
8672                 blanket-derived Into shape must resolve to the same \
8673                 as_str dispatch as the explicit From impl"
8674            );
8675            assert!(
8676                matches!(via_into, std::borrow::Cow::Borrowed(_)),
8677                "Into<Cow<'static, str>>::into on \
8678                 &RestartStrategy::{variant:?} must land on the \
8679                 zero-alloc Cow::Borrowed arm — the blanket-derived \
8680                 Into shape must resolve to the same Cow::Borrowed \
8681                 dispatch as the explicit From impl"
8682            );
8683        }
8684    }
8685
8686    #[test]
8687    fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
8688        // Cross-axis partition pin: the newly lifted trait-idiomatic
8689        // borrowed-input `From<&RestartStrategy> for
8690        // std::borrow::Cow<'static, str>` (this lift), the paired
8691        // owned-input `From<RestartStrategy> for
8692        // std::borrow::Cow<'static, str>` (7dd28b3), the paired
8693        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8694        // for &'static str`, and the paired borrowed-input owned-
8695        // `String` `From<&RestartStrategy> for String` must resolve
8696        // identically on every arm, locking the four
8697        // return-shape × input-shape paths together by construction so
8698        // any future detour trips at caixa-core test time. Also byte-
8699        // parity witness against the sibling [`ToString::to_string`]
8700        // surface routed through [`std::fmt::Display`] — every owned-
8701        // heap-string path (this axis's `.into_owned()` promotion, the
8702        // paired [`From<&RestartStrategy> for String`], and
8703        // `.to_string()`) resolves to the same lifted
8704        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
8705        //
8706        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
8707        // over [`super::RestartStrategy::ALL`] — whose iterator yields
8708        // `&RestartStrategy` by construction, so the borrowed-input
8709        // [`Cow<'static, str>`] axis is what routes the pipe through
8710        // the substrate-primitive [`super::RestartStrategy::as_str`]
8711        // accessor without a spurious [`Copy`] deref (which would only
8712        // be reachable through the owned-input
8713        // [`From<RestartStrategy> for Cow<'static, str>`] axis by
8714        // first calling `.copied()` on the iterator). The pipe witness
8715        // also pins the zero-alloc discipline: every element in the
8716        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
8717        // arm predicate, so a future accidental silent-allocation
8718        // regression on the pipe's iteration axis is a caixa-core-
8719        // test-time failure.
8720        for &strategy in RestartStrategy::ALL {
8721            let borrowed_cow: std::borrow::Cow<'static, str> =
8722                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
8723            let owned_cow: std::borrow::Cow<'static, str> =
8724                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
8725            let borrowed_static: &'static str =
8726                <&'static str as From<&RestartStrategy>>::from(&strategy);
8727            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
8728            assert_eq!(
8729                borrowed_cow, owned_cow,
8730                "From<&RestartStrategy> for Cow<'static, str> and \
8731                 From<RestartStrategy> for Cow<'static, str> must \
8732                 resolve identically on RestartStrategy::{strategy:?} — \
8733                 divergence signals the borrowed-input and owned-input \
8734                 Cow<'static, str> forward-projection input-shape \
8735                 paths have drifted onto different emit-sets"
8736            );
8737            assert_eq!(
8738                borrowed_cow.as_ref(),
8739                borrowed_static,
8740                "From<&RestartStrategy> for Cow<'static, str> and \
8741                 From<&RestartStrategy> for &'static str must resolve \
8742                 identically on RestartStrategy::{strategy:?} — \
8743                 divergence signals the borrowed-input Cow<'static, \
8744                 str> and &'static str return-shape paths have drifted \
8745                 onto different emit-sets"
8746            );
8747            assert_eq!(
8748                borrowed_cow.as_ref(),
8749                borrowed_string.as_str(),
8750                "From<&RestartStrategy> for Cow<'static, str> and \
8751                 From<&RestartStrategy> for String must resolve \
8752                 identically on RestartStrategy::{strategy:?} — \
8753                 divergence signals the borrowed-input Cow<'static, \
8754                 str> and owned-`String` return-shape paths have \
8755                 drifted onto different emit-sets"
8756            );
8757            let via_to_string: String = strategy.to_string();
8758            assert_eq!(
8759                borrowed_cow.as_ref(),
8760                via_to_string.as_str(),
8761                "From<&RestartStrategy> for Cow<'static, str> must \
8762                 byte-equal RestartStrategy::to_string on \
8763                 RestartStrategy::{strategy:?} — divergence signals \
8764                 the trait-idiomatic borrowed-input Cow<'static, str> \
8765                 forward-projection axis and the ToString-through-\
8766                 Display axis have drifted onto different emit-sets"
8767            );
8768        }
8769        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8770            .iter()
8771            .map(std::borrow::Cow::from)
8772            .collect();
8773        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8774            .iter()
8775            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
8776            .collect();
8777        assert_eq!(
8778            via_iter, via_method,
8779            "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
8780             call site whose iteration axis holds `&RestartStrategy` \
8781             by construction — must byte-equal `.iter().map(|s| \
8782             Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
8783             input Cow<'static, str> `From<&RestartStrategy> for \
8784             Cow<'static, str>` axis is what makes the `Cow::from` \
8785             composition route through the substrate-primitive \
8786             `RestartStrategy::as_str` accessor with the zero-alloc \
8787             Cow::Borrowed arm by construction and without a spurious \
8788             `Copy` deref (which would only be reachable through the \
8789             owned-input `From<RestartStrategy> for Cow<'static, str>` \
8790             axis by first calling `.copied()` on the iterator)"
8791        );
8792        for cow in &via_iter {
8793            assert!(
8794                matches!(cow, std::borrow::Cow::Borrowed(_)),
8795                "every element of the .iter().map(Cow::from) pipe \
8796                 over RestartStrategy::ALL must land on the zero-\
8797                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
8798                 any arm signals the pipe's iteration axis has \
8799                 silently allocated where the substrate-primitive \
8800                 RestartStrategy::as_str `&'static str` return makes \
8801                 the borrowed arm the type-correct projection"
8802            );
8803        }
8804    }
8805
8806    #[test]
8807    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
8808        // Fail-before-pass-after byte-parity pin on the newly lifted
8809        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
8810        // library trait impl and the substrate-primitive
8811        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
8812        // the same three-arm accept-set across every arm the exhaustive
8813        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
8814        // detour that routes the trait impl through a divergent
8815        // projection (a per-arm inline `match s { "Permanent" =>
8816        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
8817        // link to the un-lifted arm-literal, a hypothetical
8818        // `#[serde(rename_all = "…")]` attribute drift that silently
8819        // splits the wire byte-string from every consumer that reaches
8820        // for this typed dispatch, an accidental swap onto the kebab-case
8821        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
8822        // impl parses through and which would collide the two-axis
8823        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
8824        // doc block makes load-bearing) trips at caixa-core test time
8825        // under `assert_eq!` rather than at a downstream
8826        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
8827        // every one of the three arms [`RestartPolicy::ALL`] carries so
8828        // no arm's projection is covered only by the sibling method-
8829        // named `from_wire` path. Peer of the sibling
8830        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
8831        // (5b828ed) — extends the trait-idiomatic reverse-projection
8832        // axis onto the third and final M2-OTP-shape closed-set typed
8833        // enum on the caixa surface (the paired per-child restart-
8834        // decision-policy sibling on the same M2 `:supervisor` slot).
8835        for &variant in RestartPolicy::ALL {
8836            let wire = variant.as_str();
8837            assert_eq!(
8838                <RestartPolicy as TryFrom<&str>>::try_from(wire),
8839                Ok(variant),
8840                "TryFrom<&str> impl on RestartPolicy must round-trip \
8841                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
8842                 Ok(RestartPolicy::{variant:?}) — divergence from \
8843                 RestartPolicy::from_wire signals a silent detour off \
8844                 the substrate-primitive accessor"
8845            );
8846            assert_eq!(
8847                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
8848                RestartPolicy::from_wire(wire),
8849                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
8850                 equal RestartPolicy::from_wire on the same input"
8851            );
8852        }
8853    }
8854
8855    #[test]
8856    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
8857        // Rejection witness on the `impl TryFrom<&str> for
8858        // RestartPolicy` — sweeps a candidate set of byte-strings
8859        // outside the three-arm PascalCase wire accept-set the sibling
8860        // [`RestartPolicy::as_str`] emits and asserts every one lands on
8861        // `Err(())`, so a future accidental widening of the trait impl's
8862        // accept-set (a stray additional
8863        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
8864        // path, a silent inclusion of the kebab-case dispatcher-catalog
8865        // byte-string the pre-existing [`std::str::FromStr`] impl the
8866        // [`gen_platform::FromStrKind`] derive installs parses onto the
8867        // wire axis — which would collide the two-axis
8868        // wire/dispatcher-catalog split the sibling
8869        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
8870        // an English-rebrand or plural-arm silent alias that would widen
8871        // the wire accept-set past the OTP-canonical three) trips at
8872        // caixa-core test time. The candidate set includes the empty
8873        // string, whitespace-only padding, the kebab-case dispatcher-
8874        // catalog byte-strings on the sibling axis (a caller who
8875        // confuses the two axes trips here rather than at a downstream
8876        // consumer's silent reject), a lowercase / uppercase / mixed-case
8877        // fold of each PascalCase arm (a caller who assumes case-fold
8878        // acceptance trips here), leading/trailing whitespace padding,
8879        // the trailing-newline shape, quote-wrapped candidates, and a
8880        // residual set of plausible-but-wrong English rebrand
8881        // candidates. Peer of the sibling
8882        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
8883        // (5b828ed) rejection witness.
8884        let rejected: &[&str] = &[
8885            "",
8886            " ",
8887            "\n",
8888            "\t",
8889            "permanent",
8890            "temporary",
8891            "transient",
8892            "PERMANENT",
8893            "TEMPORARY",
8894            "TRANSIENT",
8895            "Permanents",
8896            "Permanent ",
8897            " Permanent",
8898            " Temporary ",
8899            "Permanent\n",
8900            "Transient\t",
8901            "\"Permanent\"",
8902            "Ephemeral",
8903            "Always",
8904            "Never",
8905            "OnAbnormalExit",
8906            "intrinsic",
8907            "?",
8908        ];
8909        for &input in rejected {
8910            assert_eq!(
8911                <RestartPolicy as TryFrom<&str>>::try_from(input),
8912                Err(()),
8913                "TryFrom<&str> impl on RestartPolicy must reject the \
8914                 non-wire byte-string {input:?} — silent acceptance \
8915                 signals an accept-set widening off the paired \
8916                 RestartPolicy::from_wire resolver"
8917            );
8918        }
8919    }
8920
8921    #[test]
8922    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
8923        // Cross-axis partition pin: the paired `TryFrom<&str>` and
8924        // `from_wire` reverse projections must resolve identically on
8925        // *every* input, not just the ones [`RestartPolicy::ALL`]
8926        // enumerates. Sweeps a mixed candidate set spanning accepted
8927        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
8928        // case dispatcher-catalog byte-strings, empty, whitespace-
8929        // padded, quoted, English-rebrand candidates) inputs and asserts
8930        // the trait's `Result::ok()` projection byte-equals the method-
8931        // named resolver's `Option<Self>` return-shape on each, locking
8932        // the two paths together by construction so any future detour
8933        // (a stray `try_from` special-case that widens or narrows the
8934        // accept-set outside the paired `from_wire` resolver, an
8935        // accidental swap onto the kebab-case [`std::str::FromStr`]
8936        // impl the [`gen_platform::FromStrKind`] derive installs on the
8937        // sibling dispatcher-catalog axis) trips at caixa-core test
8938        // time. Peer of the sibling
8939        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
8940        // pin — extends the round-trip discipline onto the M2-OTP-shape
8941        // per-child restart-policy axis.
8942        let candidates: &[&str] = &[
8943            "Permanent",
8944            "Temporary",
8945            "Transient",
8946            "",
8947            "permanent",
8948            "temporary",
8949            "transient",
8950            "PERMANENT",
8951            "unknown",
8952            "Permanent ",
8953            " Permanent",
8954            "\"Permanent\"",
8955            "Ephemeral",
8956            "OnAbnormalExit",
8957            "?",
8958        ];
8959        for &input in candidates {
8960            let via_trait: Option<RestartPolicy> =
8961                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
8962            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
8963            assert_eq!(
8964                via_trait, via_method,
8965                "TryFrom<&str> and from_wire must resolve identically on \
8966                 input {input:?} — divergence signals the two reverse-\
8967                 projection paths have drifted onto different accept-sets"
8968            );
8969        }
8970    }
8971
8972    #[test]
8973    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
8974        // Fail-before-pass-after byte-parity pin on the newly lifted
8975        // `impl From<RestartPolicy> for &'static str` — asserts the
8976        // standard-library trait impl and the substrate-primitive
8977        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
8978        // the same three-arm emit-set across every arm the exhaustive
8979        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
8980        // detour that routes the trait impl through a divergent
8981        // projection (a per-arm inline `match policy { Permanent =>
8982        // "Permanent", … }` re-inlining that opens a compile-time link
8983        // to the un-lifted arm-literal, an accidental swap onto the
8984        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
8985        // axis that would collide the two-axis wire/catalog split the
8986        // sibling [`RestartPolicy::from_wire`] doc block makes
8987        // load-bearing) trips at caixa-core test time under
8988        // `assert_eq!` rather than at a downstream
8989        // `impl Into<&'static str>`-bound consumer's silent split.
8990        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
8991        // carries so no arm's projection is covered only by the sibling
8992        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
8993        // paths. Materializes the `<&'static str as
8994        // From<RestartPolicy>>::from` output in a `const`-shape binding
8995        // to make the `'static` lifetime promise a build-time invariant
8996        // — a future accidental downgrade of any of the three arms'
8997        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
8998        // non-`&'static str` (a `String::leak()`-produced return, a
8999        // `Box::leak`-cast) trips at caixa-core build time rather than
9000        // at a downstream `'static`-bound consumer. Peer of the sibling
9001        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
9002        // (523157d) — extends the trait-idiomatic forward-projection
9003        // axis onto the second (and second-of-two-in-M2) closed-set
9004        // typed enum on the caixa surface (the paired per-child
9005        // restart-decision-policy sibling on the same M2 `:supervisor`
9006        // slot).
9007        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
9008        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
9009        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
9010        for &variant in RestartPolicy::ALL {
9011            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9012            let via_method: &'static str = variant.as_str();
9013            assert_eq!(
9014                via_trait, via_method,
9015                "From<RestartPolicy> for &'static str impl must round-trip \
9016                 RestartPolicy::{variant:?} to the same lifted \
9017                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
9018                 divergence signals a silent detour off the substrate-primitive \
9019                 accessor"
9020            );
9021            let via_into: &'static str = variant.into();
9022            assert_eq!(
9023                via_into, via_method,
9024                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
9025                 byte-equal RestartPolicy::as_str on the same input — the \
9026                 blanket-derived Into shape must resolve to the same as_str \
9027                 dispatch as the explicit From impl"
9028            );
9029        }
9030        assert_eq!(
9031            [PERMANENT, TEMPORARY, TRANSIENT],
9032            [
9033                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9034                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9035                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9036            ],
9037            "const-context RestartPolicy::as_str must resolve to the three \
9038             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
9039             downgrade of any arm to a non-const or non-static byte-string \
9040             breaks the `&'static str`-lifetime promise the paired \
9041             From<RestartPolicy> for &'static str impl carries by \
9042             construction"
9043        );
9044    }
9045
9046    #[test]
9047    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
9048        // Cross-axis partition pin: the paired trait-idiomatic
9049        // `From<RestartPolicy> for &'static str` forward projection and
9050        // the method-named [`RestartPolicy::as_str`] forward projection
9051        // must resolve identically on *every* arm, not just the ones
9052        // named in the primary byte-parity pin above. Sweeps every
9053        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
9054        // output byte-equals the method-named accessor's return-value on
9055        // each, locking the two forward-projection paths together by
9056        // construction so any future detour (a stray `From` special-case
9057        // that lands on a divergent per-arm literal outside the paired
9058        // `as_str` dispatch, a hypothetical rebrand touching one axis
9059        // without the other) trips at caixa-core test time. Peer of the
9060        // sibling forward-projection partition pin
9061        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
9062        // (523157d) — extends the round-trip discipline onto the
9063        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
9064        // surface, closing the two-way `Self ↔ &'static str` round-trip
9065        // on the trait-idiomatic pair (`From<Self> for &'static str` +
9066        // `TryFrom<&str> for Self`) as well as the pre-existing method-
9067        // named pair (`as_str` + `from_wire`).
9068        for &variant in RestartPolicy::ALL {
9069            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9070            let via_method: &'static str = variant.as_str();
9071            assert_eq!(
9072                via_trait, via_method,
9073                "From<RestartPolicy> for &'static str and \
9074                 RestartPolicy::as_str must resolve identically on \
9075                 RestartPolicy::{variant:?} — divergence signals the \
9076                 two forward-projection paths have drifted onto different \
9077                 emit-sets"
9078            );
9079        }
9080        // Round-trip witness: every arm's forward `From` output re-parses
9081        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
9082        // to the original variant. Closes the two-way `RestartPolicy ↔
9083        // &'static str` round-trip on the trait-idiomatic axis pair,
9084        // mirroring the pre-existing method-named `as_str` + `from_wire`
9085        // round-trip on the substrate-primitive axis pair.
9086        for &variant in RestartPolicy::ALL {
9087            let emitted: &'static str = variant.into();
9088            let re_parsed: Result<RestartPolicy, ()> =
9089                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
9090            assert_eq!(
9091                re_parsed,
9092                Ok(variant),
9093                "trait-idiomatic axis pair must round-trip \
9094                 RestartPolicy::{variant:?} through `.into::<&'static \
9095                 str>()` and back through `TryFrom<&str>` — a break signals \
9096                 the forward-emit and reverse-parse axes have drifted onto \
9097                 different vocabularies"
9098            );
9099        }
9100    }
9101
9102    #[test]
9103    fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
9104        // Fail-before-pass-after byte-parity pin on the newly lifted
9105        // `impl From<&RestartPolicy> for &'static str` — asserts the
9106        // borrowed-input standard-library trait impl and the substrate-
9107        // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
9108        // resolve to the same three-arm emit-set across every arm the
9109        // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
9110        // `From` trait does not auto-derive the borrowed-input sibling
9111        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
9112        // where T: Copy, U: From<T>` blanket in `core`), so the
9113        // borrowed-input axis is a distinct trait-idiomatic surface
9114        // that a `.iter().map(Into::into)` shape over
9115        // [`RestartPolicy::ALL`] (whose iterator yields
9116        // `&RestartPolicy`, not `RestartPolicy`) reaches through this
9117        // impl and no other — the paired owned-input
9118        // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
9119        // / dereference before the trait fires. Materializes the
9120        // `<&'static str as From<&RestartPolicy>>::from` output in a
9121        // `const`-shape binding to make the `'static` lifetime promise
9122        // a build-time invariant.
9123        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
9124        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
9125        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
9126        for variant in RestartPolicy::ALL {
9127            let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
9128            let via_method: &'static str = variant.as_str();
9129            assert_eq!(
9130                via_trait, via_method,
9131                "From<&RestartPolicy> for &'static str impl must round-trip \
9132                 &RestartPolicy::{variant:?} to the same lifted \
9133                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9134                 returns — divergence signals a silent detour off the \
9135                 substrate-primitive accessor"
9136            );
9137            let via_into: &'static str = variant.into();
9138            assert_eq!(
9139                via_into, via_method,
9140                "Into<&'static str>::into on &RestartPolicy::{variant:?} \
9141                 must byte-equal RestartPolicy::as_str on the same input — \
9142                 the blanket-derived Into shape must resolve to the same \
9143                 as_str dispatch as the explicit From impl"
9144            );
9145        }
9146        assert_eq!(
9147            [PERMANENT, TEMPORARY, TRANSIENT],
9148            [
9149                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9150                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9151                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9152            ],
9153            "const-context RestartPolicy::as_str must resolve to the three \
9154             lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
9155             From<&RestartPolicy> for &'static str impl inherits its \
9156             `'static` lifetime promise from the same accessor the \
9157             owned-input sibling routes through"
9158        );
9159    }
9160
9161    #[test]
9162    fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
9163        // Cross-axis partition pin: the paired trait-idiomatic
9164        // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
9165        // campaign-shape) and borrowed-input `From<&RestartPolicy> for
9166        // &'static str` (this lift) forward projections must resolve
9167        // identically on every arm, locking the two input-shape paths
9168        // together so any future detour trips at caixa-core test time.
9169        // Then a witness that a `.iter().map(Into::into)` pipe over
9170        // [`RestartPolicy::ALL`] (whose iterator yields
9171        // `&RestartPolicy`) materializes the three-arm accept-set
9172        // through the borrowed-input axis alone — the exact shape a
9173        // future wasm-operator per-child post-exit restart-decision
9174        // diagnostic line, a future substrate-wide per-arm diagnostic
9175        // column, or a
9176        // `HashMap::<&'static str, RestartPolicy>::from_iter(
9177        //     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
9178        // per-policy lookup reaches through — closing the two-way
9179        // owned/borrowed input-shape symmetry on the forward-projection
9180        // trait-idiomatic axis. Peer of the sibling
9181        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9182        // (64aa742) /
9183        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9184        // (5ab993a) /
9185        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9186        // (807b0b5) /
9187        // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9188        // (e941836) partition pins on the sibling closed-set typed-enum
9189        // discriminator axes — extends the borrowed-input axis
9190        // discipline onto the second-of-two M2 OTP-shape closed-set
9191        // typed enum on the caixa surface (per-child restart-decision
9192        // policy). Also closes the direct two-way `&Self → &'static
9193        // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
9194        // — unlike the peer [`crate::CaixaKind`] axis pair (whose
9195        // forward `From` emits lowercase Portuguese diagnostic bytes
9196        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
9197        // forcing the round-trip through an intermediate wire-vocab
9198        // hop), the [`RestartPolicy::as_str`] emit and
9199        // [`RestartPolicy::from_wire`] parse share the same
9200        // `PascalCase` vocabulary by construction, so the borrowed-
9201        // input forward axis and the reverse axis compose directly.
9202        for &variant in RestartPolicy::ALL {
9203            let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9204            let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
9205            assert_eq!(
9206                owned, borrowed,
9207                "From<RestartPolicy> and From<&RestartPolicy> for \
9208                 &'static str must resolve identically on \
9209                 RestartPolicy::{variant:?} — divergence signals the \
9210                 owned-input and borrowed-input forward-projection paths \
9211                 have drifted onto different emit-sets"
9212            );
9213        }
9214        let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
9215        let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
9216        assert_eq!(
9217            via_iter, via_method,
9218            "`.iter().map(Into::into)` over RestartPolicy::ALL must \
9219             byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
9220             borrowed-input `From<&RestartPolicy> for &'static str` axis \
9221             is what makes the `.iter().map(Into::into)` shape route \
9222             through the substrate-primitive `RestartPolicy::as_str` \
9223             accessor rather than through a per-call-site `.copied()` / \
9224             dereference detour"
9225        );
9226        for variant in RestartPolicy::ALL {
9227            let emitted: &'static str = variant.into();
9228            let re_parsed: Result<RestartPolicy, ()> =
9229                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
9230            assert_eq!(
9231                re_parsed,
9232                Ok(*variant),
9233                "trait-idiomatic borrowed-input forward-projection + \
9234                 reverse-projection axis pair must round-trip \
9235                 &RestartPolicy::{variant:?} through `.into::<&'static \
9236                 str>()` (via the borrowed-input axis) and back through \
9237                 `TryFrom<&str>` — a break signals the borrowed-input \
9238                 forward-emit and reverse-parse axes have drifted onto \
9239                 different vocabularies"
9240            );
9241        }
9242    }
9243
9244    #[test]
9245    fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
9246        // Fail-before-pass-after byte-parity pin on the newly lifted
9247        // `impl From<RestartPolicy> for String` — asserts the
9248        // owned-`String`-returning standard-library trait impl and the
9249        // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
9250        // accessor resolve to the same three-arm emit-set across every
9251        // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
9252        // Rust's standard library does not carry a blanket
9253        // `impl<T: AsRef<str>> From<T> for String` (nor an
9254        // `impl<T: fmt::Display> From<T> for String`), so the
9255        // owned-`String` forward-projection axis is a distinct
9256        // trait-idiomatic surface that a `let key: String =
9257        // policy.into();`-shaped call site reaches through this impl
9258        // and no other — the paired sibling `From<RestartPolicy> for
9259        // &'static str` impl forces every owned-`String` call site
9260        // through an explicit `.to_owned()` / `String::from`
9261        // restatement. Peer of the first-mover
9262        // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
9263        // (7baa18a) — extends the trait-idiomatic owned-`String`
9264        // forward-projection axis onto the second-of-two M2 OTP-shape
9265        // closed-set typed enums on the caixa surface (per-child
9266        // restart-decision-policy sibling on the same M2 `:supervisor`
9267        // slot).
9268        for &variant in RestartPolicy::ALL {
9269            let via_trait: String = <String as From<RestartPolicy>>::from(variant);
9270            let via_method: &'static str = variant.as_str();
9271            assert_eq!(
9272                via_trait.as_str(),
9273                via_method,
9274                "From<RestartPolicy> for String impl must round-trip \
9275                 RestartPolicy::{variant:?} to the same lifted \
9276                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9277                 returns — divergence signals a silent detour off the \
9278                 substrate-primitive accessor"
9279            );
9280            let via_into: String = variant.into();
9281            assert_eq!(
9282                via_into.as_str(),
9283                via_method,
9284                "Into<String>::into on RestartPolicy::{variant:?} must \
9285                 byte-equal RestartPolicy::as_str on the same input — the \
9286                 blanket-derived Into shape must resolve to the same as_str \
9287                 dispatch as the explicit From impl"
9288            );
9289        }
9290    }
9291
9292    #[test]
9293    fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
9294        // Cross-axis partition pin: the paired trait-idiomatic
9295        // owned-`String` `From<RestartPolicy> for String` (this lift)
9296        // and owned-`&'static str` `From<RestartPolicy> for &'static
9297        // str` (9fb37d0) forward projections must resolve identically
9298        // on every arm, locking the two return-type-shape paths
9299        // together so any future detour trips at caixa-core test time.
9300        // Also byte-parity witness against the sibling
9301        // [`ToString::to_string`] surface routed through
9302        // [`std::fmt::Display`] — the three owned-heap-string paths
9303        // (`.into::<String>()`, `String::from`, `.to_string()`) must
9304        // resolve identically on every arm so a future consumer that
9305        // picks any of the three lands on the same lifted
9306        // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
9307        // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
9308        // that materializes the three-arm accept-set through the
9309        // owned-`String` axis alone — the exact shape a future
9310        // wasm-operator per-child post-exit restart-decision
9311        // diagnostic line composer or a
9312        // `HashMap::<String, RestartPolicy>::from_iter(
9313        //     RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
9314        // owned-key per-policy lookup reaches through — closing the
9315        // owned-`String` forward-projection axis's iterator-pipe
9316        // shape. Then a direct round-trip witness through the paired
9317        // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
9318        // owned-`String`'s [`String::as_str`] borrow that closes the
9319        // two-way `Self → String → Self` round-trip on the trait-
9320        // idiomatic owned-`String` forward + reverse axis pair —
9321        // unlike the peer [`crate::CaixaKind`] axis pair (whose
9322        // forward `From` emits lowercase Portuguese diagnostic bytes
9323        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
9324        // forcing the round-trip through an intermediate wire-vocab
9325        // hop), the [`RestartPolicy::as_str`] emit and
9326        // [`RestartPolicy::from_wire`] parse share the same
9327        // `PascalCase` vocabulary by construction, so the owned-
9328        // `String` forward axis and the reverse axis compose directly.
9329        for &variant in RestartPolicy::ALL {
9330            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
9331            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9332            assert_eq!(
9333                owned_string.as_str(),
9334                owned_static,
9335                "From<RestartPolicy> for String and From<RestartPolicy> \
9336                 for &'static str must resolve identically on \
9337                 RestartPolicy::{variant:?} — divergence signals the \
9338                 owned-`String` and owned-`&'static str` forward-projection \
9339                 return-type-shape paths have drifted onto different \
9340                 emit-sets"
9341            );
9342            let via_to_string: String = variant.to_string();
9343            assert_eq!(
9344                owned_string, via_to_string,
9345                "From<RestartPolicy> for String must byte-equal \
9346                 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
9347                 divergence signals the trait-idiomatic owned-`String` \
9348                 forward-projection axis and the ToString-through-Display \
9349                 axis have drifted onto different emit-sets"
9350            );
9351        }
9352        let via_iter: Vec<String> = RestartPolicy::ALL
9353            .iter()
9354            .copied()
9355            .map(String::from)
9356            .collect();
9357        let via_method: Vec<String> = RestartPolicy::ALL
9358            .iter()
9359            .map(|p| p.as_str().to_owned())
9360            .collect();
9361        assert_eq!(
9362            via_iter, via_method,
9363            "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
9364             must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
9365             every arm — the owned-`String` `From<RestartPolicy> for \
9366             String` axis is what makes the `String::from` composition \
9367             route through the substrate-primitive `RestartPolicy::as_str` \
9368             accessor rather than through a per-call-site `.to_owned()` / \
9369             `String::from(policy.as_str())` detour"
9370        );
9371        for &variant in RestartPolicy::ALL {
9372            let emitted: String = variant.into();
9373            let re_parsed: Result<RestartPolicy, ()> =
9374                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
9375            assert_eq!(
9376                re_parsed,
9377                Ok(variant),
9378                "trait-idiomatic owned-`String` forward-projection + \
9379                 reverse-projection axis pair must round-trip \
9380                 RestartPolicy::{variant:?} through `.into::<String>()` \
9381                 and back through `TryFrom<&str>` on the owned-`String`'s \
9382                 String::as_str borrow — a break signals the owned-`String` \
9383                 forward-emit and reverse-parse axes have drifted onto \
9384                 different vocabularies"
9385            );
9386        }
9387    }
9388
9389    #[test]
9390    fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
9391        // Fail-before-pass-after byte-parity pin on the newly lifted
9392        // `impl From<&RestartPolicy> for String` — asserts the
9393        // borrowed-input owned-`String`-returning standard-library
9394        // trait impl and the substrate-primitive
9395        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
9396        // the same three-arm emit-set across every arm the exhaustive
9397        // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
9398        // library does not carry a blanket `impl<T: AsRef<str>>
9399        // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
9400        // for String`), so the borrowed-input owned-`String` forward-
9401        // projection axis is a distinct trait-idiomatic surface that a
9402        // `let key: String = (&policy).into();`-shaped call site
9403        // reaches through this impl and no other — the paired sibling
9404        // `From<RestartPolicy> for String` impl forces every borrowed-
9405        // input call site through an explicit `Copy` deref
9406        // (`String::from(*policy)`) or an `.as_str().to_owned()` /
9407        // `.to_string()` detour. Peer of the first-mover
9408        // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
9409        // (579385f) — extends the trait-idiomatic borrowed-input
9410        // owned-`String` forward-projection axis onto the second-of-
9411        // two M2 OTP-shape closed-set typed enums on the caixa surface
9412        // (per-child restart-decision-policy sibling on the same M2
9413        // `:supervisor` slot).
9414        for &variant in RestartPolicy::ALL {
9415            let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
9416            let via_method: &'static str = variant.as_str();
9417            assert_eq!(
9418                via_trait.as_str(),
9419                via_method,
9420                "From<&RestartPolicy> for String impl must round-trip \
9421                 &RestartPolicy::{variant:?} to the same lifted \
9422                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9423                 returns — divergence signals a silent detour off the \
9424                 substrate-primitive accessor"
9425            );
9426            let via_into: String = (&variant).into();
9427            assert_eq!(
9428                via_into.as_str(),
9429                via_method,
9430                "Into<String>::into on &RestartPolicy::{variant:?} must \
9431                 byte-equal RestartPolicy::as_str on the same input — \
9432                 the blanket-derived Into shape must resolve to the \
9433                 same as_str dispatch as the explicit From impl"
9434            );
9435        }
9436    }
9437
9438    #[test]
9439    fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
9440        // Cross-axis partition pin: the newly lifted trait-idiomatic
9441        // borrowed-input owned-`String` `From<&RestartPolicy> for
9442        // String` (this lift), the paired owned-input owned-`String`
9443        // `From<RestartPolicy> for String` (7851725), the paired
9444        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
9445        // for &'static str` (842c7f3), and the paired owned-input
9446        // owned-`&'static str` `From<RestartPolicy> for &'static str`
9447        // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
9448        // str, String}` 2×2 trait-idiomatic projection family — must
9449        // resolve identically on every arm, locking the four
9450        // return-shape × input-shape paths together so any future
9451        // detour trips at caixa-core test time. Also byte-parity
9452        // witness against the sibling [`ToString::to_string`] surface
9453        // routed through [`std::fmt::Display`] and a direct round-trip
9454        // witness through the paired trait-idiomatic reverse
9455        // [`TryFrom<&str>`] axis on the owned-`String`'s
9456        // [`String::as_str`] borrow that closes the two-way
9457        // `&Self → String → Self` round-trip on the trait-idiomatic
9458        // borrowed-input owned-`String` forward + reverse axis pair.
9459        // Peer of the first-mover
9460        // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
9461        // (579385f) — closes the whole `{Self, &Self} × {&'static str,
9462        // String}` 2×2 projection corner on both M2 OTP-shape sibling
9463        // peers.
9464        for &variant in RestartPolicy::ALL {
9465            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
9466            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
9467            let borrowed_static: &'static str =
9468                <&'static str as From<&RestartPolicy>>::from(&variant);
9469            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9470            assert_eq!(
9471                borrowed_string, owned_string,
9472                "From<&RestartPolicy> for String and From<RestartPolicy> \
9473                 for String must resolve identically on \
9474                 RestartPolicy::{variant:?} — divergence signals the \
9475                 borrowed-input and owned-input owned-`String` \
9476                 forward-projection input-shape paths have drifted onto \
9477                 different emit-sets"
9478            );
9479            assert_eq!(
9480                borrowed_string.as_str(),
9481                borrowed_static,
9482                "From<&RestartPolicy> for String and From<&RestartPolicy> \
9483                 for &'static str must resolve identically on \
9484                 RestartPolicy::{variant:?} — divergence signals the \
9485                 borrowed-input `&'static str` and owned-`String` \
9486                 return-shape paths have drifted onto different \
9487                 emit-sets"
9488            );
9489            assert_eq!(
9490                borrowed_string.as_str(),
9491                owned_static,
9492                "From<&RestartPolicy> for String and From<RestartPolicy> \
9493                 for &'static str must resolve identically on \
9494                 RestartPolicy::{variant:?} — divergence signals a \
9495                 break in the diagonal corner of the {{Self, &Self}} × \
9496                 {{&'static str, String}} 2×2 trait-idiomatic \
9497                 projection family"
9498            );
9499            let via_to_string: String = variant.to_string();
9500            assert_eq!(
9501                borrowed_string, via_to_string,
9502                "From<&RestartPolicy> for String must byte-equal \
9503                 RestartPolicy::to_string on RestartPolicy::{variant:?} \
9504                 — divergence signals the trait-idiomatic borrowed-input \
9505                 owned-`String` forward-projection axis and the \
9506                 ToString-through-Display axis have drifted onto \
9507                 different emit-sets"
9508            );
9509        }
9510        let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
9511        let via_method: Vec<String> = RestartPolicy::ALL
9512            .iter()
9513            .map(|p| p.as_str().to_owned())
9514            .collect();
9515        assert_eq!(
9516            via_iter, via_method,
9517            "`.iter().map(String::from)` over RestartPolicy::ALL — a \
9518             call site whose iteration axis holds `&RestartPolicy` by \
9519             construction — must byte-equal `.iter().map(|p| \
9520             p.as_str().to_owned())` on every arm — the borrowed-input \
9521             owned-`String` `From<&RestartPolicy> for String` axis is \
9522             what makes the `String::from` composition route through \
9523             the substrate-primitive `RestartPolicy::as_str` accessor \
9524             without a spurious `Copy` deref (which would only be \
9525             reachable through the owned-input `From<RestartPolicy> \
9526             for String` axis by first calling `.copied()` on the \
9527             iterator)"
9528        );
9529        for &variant in RestartPolicy::ALL {
9530            let emitted: String = (&variant).into();
9531            let re_parsed: Result<RestartPolicy, ()> =
9532                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
9533            assert_eq!(
9534                re_parsed,
9535                Ok(variant),
9536                "trait-idiomatic borrowed-input owned-`String` \
9537                 forward-projection + reverse-projection axis pair must \
9538                 round-trip &RestartPolicy::{variant:?} through \
9539                 `.into::<String>()` on the borrowed-input surface and \
9540                 back through `TryFrom<&str>` on the owned-`String`'s \
9541                 String::as_str borrow — a break signals the \
9542                 borrowed-input owned-`String` forward-emit and \
9543                 reverse-parse axes have drifted onto different \
9544                 vocabularies"
9545            );
9546        }
9547    }
9548
9549    #[test]
9550    fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
9551        // Fail-before-pass-after byte-parity pin on the newly lifted
9552        // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
9553        // asserts the standard-library trait impl and the substrate-
9554        // primitive [`super::RestartPolicy::as_str`] `pub const fn`
9555        // accessor resolve to the same three-arm emit-set across every
9556        // arm the exhaustive [`super::RestartPolicy::ALL`] slice
9557        // enumerates. Rust's standard library does not carry a blanket
9558        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
9559        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
9560        // the `Cow<'static, str>` forward-projection axis is a
9561        // distinct trait-idiomatic surface that a
9562        // `let key: Cow<'static, str> = policy.into();`-shaped call
9563        // site reaches through this impl and no other — the paired
9564        // sibling `From<RestartPolicy> for &'static str` and
9565        // `From<RestartPolicy> for String` impls force every
9566        // `Cow<'static, str>`-parameterized call site through a
9567        // `Cow::Borrowed(policy.as_str())` /
9568        // `Cow::Owned(policy.to_string())` composition whose type
9569        // bounds have no compile-time link back to the substrate
9570        // primitive.
9571        //
9572        // Also asserts the projection lands on the zero-alloc
9573        // [`std::borrow::Cow::Borrowed`] arm (not the
9574        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9575        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
9576        // return lifetime by construction makes the borrowed arm the
9577        // type-correct projection with no runtime allocation. Any
9578        // future silent detour that routes the impl through the owned
9579        // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
9580        // that would allocate on every call site where the
9581        // `&'static str` return of [`super::RestartPolicy::as_str`]
9582        // makes the zero-alloc borrowed projection type-correct) trips
9583        // at caixa-core test time under the
9584        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
9585        // than at a downstream `Cow<'static, str>`-bound consumer's
9586        // silent allocation.
9587        //
9588        // Second peer on the substrate-wide trait-idiomatic
9589        // [`std::borrow::Cow<'static, str>`] forward-projection family
9590        // to extend the axis off the top-level [`super::CaixaKind`]
9591        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
9592        // second (and second-of-two-in-M2) M2 OTP-shape closed-set
9593        // fieldless typed enum peer on the caixa surface — closes the
9594        // M2 OTP-shape tier of the campaign on the owned-input axis
9595        // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
9596        // now carry the owned-input Cow<'static, str> forward
9597        // projection).
9598        for &variant in RestartPolicy::ALL {
9599            let via_trait: std::borrow::Cow<'static, str> =
9600                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
9601            let via_method: &'static str = variant.as_str();
9602            assert_eq!(
9603                via_trait.as_ref(),
9604                via_method,
9605                "From<RestartPolicy> for Cow<'static, str> impl must \
9606                 round-trip RestartPolicy::{variant:?} to the same \
9607                 lifted SUPERVISOR_CHILD_RESTART_* const \
9608                 RestartPolicy::as_str returns — divergence signals a \
9609                 silent detour off the substrate-primitive accessor"
9610            );
9611            assert!(
9612                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9613                "From<RestartPolicy> for Cow<'static, str> impl must \
9614                 land on the zero-alloc Cow::Borrowed arm on \
9615                 RestartPolicy::{variant:?} — a Cow::Owned outcome \
9616                 signals the projection has silently allocated where \
9617                 the substrate-primitive RestartPolicy::as_str \
9618                 `&'static str` return makes the borrowed arm the \
9619                 type-correct projection"
9620            );
9621            let via_into: std::borrow::Cow<'static, str> = variant.into();
9622            assert_eq!(
9623                via_into.as_ref(),
9624                via_method,
9625                "Into<Cow<'static, str>>::into on \
9626                 RestartPolicy::{variant:?} must byte-equal \
9627                 RestartPolicy::as_str on the same input — the \
9628                 blanket-derived Into shape must resolve to the same \
9629                 as_str dispatch as the explicit From impl"
9630            );
9631            assert!(
9632                matches!(via_into, std::borrow::Cow::Borrowed(_)),
9633                "Into<Cow<'static, str>>::into on \
9634                 RestartPolicy::{variant:?} must land on the \
9635                 zero-alloc Cow::Borrowed arm — the blanket-derived \
9636                 Into shape must resolve to the same Cow::Borrowed \
9637                 dispatch as the explicit From impl"
9638            );
9639        }
9640    }
9641
9642    #[test]
9643    fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9644        // Cross-axis partition pin: the newly lifted trait-idiomatic
9645        // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
9646        // (this lift), the paired owned-input `From<RestartPolicy>
9647        // for &'static str` (9fb37d0), and the paired owned-input
9648        // `From<RestartPolicy> for String` (7851725) forward
9649        // projections must resolve identically on every arm, locking
9650        // the three return-shape paths together by construction so any
9651        // future detour trips at caixa-core test time. Also byte-parity
9652        // witness against the sibling [`ToString::to_string`] surface
9653        // routed through [`std::fmt::Display`] — every owned-heap-
9654        // string path (the `Cow::Owned` promotion of this axis's
9655        // `.into_owned()`, `From<RestartPolicy> for String`, and
9656        // `.to_string()`) resolves to the same lifted
9657        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
9658        //
9659        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
9660        // witness over [`super::RestartPolicy::ALL`] that
9661        // materializes the three-arm accept-set through the
9662        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
9663        // shape a future `axum::response::IntoResponse` per-policy
9664        // rejection-body composer, a future M4 admission-webhook
9665        // per-policy rejection-reason emitter whose typing rules out
9666        // the sibling [`AsRef<str>`] borrowed return, or a future
9667        // substrate-wide per-policy diagnostic surface that binds
9668        // through a [`Cow<'static, str>`] boundary reaches through.
9669        // The pipe witness also pins the zero-alloc discipline: every
9670        // element in the collected vector satisfies the
9671        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
9672        // accidental silent-allocation regression on the pipe's
9673        // iteration axis is a caixa-core-test-time failure. Peer of
9674        // the first-mover
9675        // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
9676        // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
9677        // — closes the whole owned-input `Cow<'static, str>` +
9678        // paired `{&'static str, String}` cross-axis-parity corner on
9679        // both M2 OTP-shape sibling peers.
9680        for &variant in RestartPolicy::ALL {
9681            let via_cow: std::borrow::Cow<'static, str> =
9682                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
9683            let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9684            let via_string: String = <String as From<RestartPolicy>>::from(variant);
9685            assert_eq!(
9686                via_cow.as_ref(),
9687                via_static,
9688                "From<RestartPolicy> for Cow<'static, str> and \
9689                 From<RestartPolicy> for &'static str must resolve \
9690                 identically on RestartPolicy::{variant:?} — \
9691                 divergence signals the Cow<'static, str> and \
9692                 &'static str return-shape paths have drifted onto \
9693                 different emit-sets"
9694            );
9695            assert_eq!(
9696                via_cow.as_ref(),
9697                via_string.as_str(),
9698                "From<RestartPolicy> for Cow<'static, str> and \
9699                 From<RestartPolicy> for String must resolve \
9700                 identically on RestartPolicy::{variant:?} — \
9701                 divergence signals the Cow<'static, str> and String \
9702                 return-shape paths have drifted onto different \
9703                 emit-sets"
9704            );
9705            let via_to_string: String = variant.to_string();
9706            assert_eq!(
9707                via_cow.as_ref(),
9708                via_to_string.as_str(),
9709                "From<RestartPolicy> for Cow<'static, str> must \
9710                 byte-equal RestartPolicy::to_string on \
9711                 RestartPolicy::{variant:?} — divergence signals the \
9712                 trait-idiomatic Cow<'static, str> forward-projection \
9713                 axis and the ToString-through-Display axis have \
9714                 drifted onto different emit-sets"
9715            );
9716        }
9717        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
9718            .iter()
9719            .copied()
9720            .map(std::borrow::Cow::from)
9721            .collect();
9722        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
9723            .iter()
9724            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
9725            .collect();
9726        assert_eq!(
9727            via_iter, via_method,
9728            "`.iter().copied().map(Cow::from)` over \
9729             RestartPolicy::ALL must byte-equal `.iter().map(|p| \
9730             Cow::Borrowed(p.as_str()))` on every arm — the \
9731             trait-idiomatic `From<RestartPolicy> for Cow<'static, \
9732             str>` axis is what makes the `Cow::from` composition \
9733             route through the substrate-primitive \
9734             `RestartPolicy::as_str` accessor with the zero-alloc \
9735             Cow::Borrowed arm by construction, rather than a \
9736             per-call-site `Cow::Owned(policy.to_string())` \
9737             allocation"
9738        );
9739        for cow in &via_iter {
9740            assert!(
9741                matches!(cow, std::borrow::Cow::Borrowed(_)),
9742                "every element of the \
9743                 .iter().copied().map(Cow::from) pipe over \
9744                 RestartPolicy::ALL must land on the zero-alloc \
9745                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
9746                 signals the pipe's iteration axis has silently \
9747                 allocated where the substrate-primitive \
9748                 RestartPolicy::as_str `&'static str` return makes \
9749                 the borrowed arm the type-correct projection"
9750            );
9751        }
9752    }
9753
9754    #[test]
9755    fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
9756        // Fail-before-pass-after byte-parity pin on the newly lifted
9757        // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
9758        // asserts the borrowed-input standard-library trait impl and
9759        // the substrate-primitive [`super::RestartPolicy::as_str`]
9760        // `pub const fn` accessor resolve to the same three-arm emit-
9761        // set across every arm the exhaustive
9762        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
9763        // standard library does not carry a blanket
9764        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
9765        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
9766        // the borrowed-input `Cow<'static, str>` forward-projection
9767        // axis is a distinct trait-idiomatic surface that a
9768        // `let key: Cow<'static, str> = (&policy).into();`-shaped
9769        // call site or a
9770        // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
9771        // reaches through this impl and no other — the paired owned-
9772        // input `From<RestartPolicy> for Cow<'static, str>` impl
9773        // (0612398) forces every borrowed-input call site through an
9774        // explicit `Copy` deref (`Cow::from(*policy)`) or a
9775        // `Cow::Borrowed(policy.as_str())` open-code whose type
9776        // bounds have no compile-time link back to the substrate
9777        // primitive.
9778        //
9779        // Also asserts the projection lands on the zero-alloc
9780        // [`std::borrow::Cow::Borrowed`] arm (not the
9781        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9782        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
9783        // return lifetime by construction makes the borrowed arm the
9784        // type-correct projection with no runtime allocation on the
9785        // borrowed-input surface just as on the paired owned-input
9786        // surface.
9787        //
9788        // Closes the `{Self, &Self}` input-shape corner on the M2
9789        // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
9790        // the second-of-two-in-M2 closed-set fieldless typed enum peer
9791        // on the caixa surface (`:supervisor :children :restart`),
9792        // exactly as d45c409 closed it on the top-level
9793        // [`super::CaixaKind`] one commit after the owning half
9794        // (99c1735) landed and as 9b3e4b3 closed it on the sibling
9795        // M2 OTP-shape [`super::RestartStrategy`] one commit after
9796        // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
9797        // tier of the substrate-wide Cow<'static, str> forward-
9798        // projection campaign on both input-shape corners
9799        // ({Self, &Self}) of both M2 OTP-shape sibling peers.
9800        for &variant in RestartPolicy::ALL {
9801            let via_trait: std::borrow::Cow<'static, str> =
9802                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
9803            let via_method: &'static str = variant.as_str();
9804            assert_eq!(
9805                via_trait.as_ref(),
9806                via_method,
9807                "From<&RestartPolicy> for Cow<'static, str> impl must \
9808                 round-trip &RestartPolicy::{variant:?} to the same \
9809                 lifted SUPERVISOR_CHILD_RESTART_* const \
9810                 RestartPolicy::as_str returns — divergence signals a \
9811                 silent detour off the substrate-primitive accessor"
9812            );
9813            assert!(
9814                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9815                "From<&RestartPolicy> for Cow<'static, str> impl must \
9816                 land on the zero-alloc Cow::Borrowed arm on \
9817                 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
9818                 signals the projection has silently allocated where \
9819                 the substrate-primitive RestartPolicy::as_str \
9820                 `&'static str` return makes the borrowed arm the \
9821                 type-correct projection"
9822            );
9823            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
9824            assert_eq!(
9825                via_into.as_ref(),
9826                via_method,
9827                "Into<Cow<'static, str>>::into on \
9828                 &RestartPolicy::{variant:?} must byte-equal \
9829                 RestartPolicy::as_str on the same input — the \
9830                 blanket-derived Into shape must resolve to the same \
9831                 as_str dispatch as the explicit From impl"
9832            );
9833            assert!(
9834                matches!(via_into, std::borrow::Cow::Borrowed(_)),
9835                "Into<Cow<'static, str>>::into on \
9836                 &RestartPolicy::{variant:?} must land on the \
9837                 zero-alloc Cow::Borrowed arm — the blanket-derived \
9838                 Into shape must resolve to the same Cow::Borrowed \
9839                 dispatch as the explicit From impl"
9840            );
9841        }
9842    }
9843
9844    #[test]
9845    fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9846        // Cross-axis partition pin: the newly lifted trait-idiomatic
9847        // borrowed-input `From<&RestartPolicy> for
9848        // std::borrow::Cow<'static, str>` (this lift), the paired
9849        // owned-input `From<RestartPolicy> for
9850        // std::borrow::Cow<'static, str>` (0612398), the paired
9851        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
9852        // for &'static str`, and the paired borrowed-input owned-
9853        // `String` `From<&RestartPolicy> for String` must resolve
9854        // identically on every arm, locking the four
9855        // return-shape × input-shape paths together by construction so
9856        // any future detour trips at caixa-core test time. Also byte-
9857        // parity witness against the sibling [`ToString::to_string`]
9858        // surface routed through [`std::fmt::Display`] — every owned-
9859        // heap-string path (this axis's `.into_owned()` promotion, the
9860        // paired [`From<&RestartPolicy> for String`], and
9861        // `.to_string()`) resolves to the same lifted
9862        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
9863        //
9864        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
9865        // over [`super::RestartPolicy::ALL`] — whose iterator yields
9866        // `&RestartPolicy` by construction, so the borrowed-input
9867        // [`Cow<'static, str>`] axis is what routes the pipe through
9868        // the substrate-primitive [`super::RestartPolicy::as_str`]
9869        // accessor without a spurious [`Copy`] deref (which would only
9870        // be reachable through the owned-input
9871        // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
9872        // calling `.copied()` on the iterator). The pipe witness also
9873        // pins the zero-alloc discipline: every element in the
9874        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
9875        // arm predicate, so a future accidental silent-allocation
9876        // regression on the pipe's iteration axis is a caixa-core-
9877        // test-time failure. Peer of the sibling
9878        // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
9879        // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
9880        // the whole borrowed-input `Cow<'static, str>` +
9881        // paired `{&'static str, String}` cross-axis-parity corner on
9882        // both M2 OTP-shape sibling peers.
9883        for &policy in RestartPolicy::ALL {
9884            let borrowed_cow: std::borrow::Cow<'static, str> =
9885                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
9886            let owned_cow: std::borrow::Cow<'static, str> =
9887                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
9888            let borrowed_static: &'static str =
9889                <&'static str as From<&RestartPolicy>>::from(&policy);
9890            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
9891            assert_eq!(
9892                borrowed_cow, owned_cow,
9893                "From<&RestartPolicy> for Cow<'static, str> and \
9894                 From<RestartPolicy> for Cow<'static, str> must \
9895                 resolve identically on RestartPolicy::{policy:?} — \
9896                 divergence signals the borrowed-input and owned-input \
9897                 Cow<'static, str> forward-projection input-shape \
9898                 paths have drifted onto different emit-sets"
9899            );
9900            assert_eq!(
9901                borrowed_cow.as_ref(),
9902                borrowed_static,
9903                "From<&RestartPolicy> for Cow<'static, str> and \
9904                 From<&RestartPolicy> for &'static str must resolve \
9905                 identically on RestartPolicy::{policy:?} — \
9906                 divergence signals the borrowed-input Cow<'static, \
9907                 str> and &'static str return-shape paths have drifted \
9908                 onto different emit-sets"
9909            );
9910            assert_eq!(
9911                borrowed_cow.as_ref(),
9912                borrowed_string.as_str(),
9913                "From<&RestartPolicy> for Cow<'static, str> and \
9914                 From<&RestartPolicy> for String must resolve \
9915                 identically on RestartPolicy::{policy:?} — \
9916                 divergence signals the borrowed-input Cow<'static, \
9917                 str> and owned-`String` return-shape paths have \
9918                 drifted onto different emit-sets"
9919            );
9920            let via_to_string: String = policy.to_string();
9921            assert_eq!(
9922                borrowed_cow.as_ref(),
9923                via_to_string.as_str(),
9924                "From<&RestartPolicy> for Cow<'static, str> must \
9925                 byte-equal RestartPolicy::to_string on \
9926                 RestartPolicy::{policy:?} — divergence signals \
9927                 the trait-idiomatic borrowed-input Cow<'static, str> \
9928                 forward-projection axis and the ToString-through-\
9929                 Display axis have drifted onto different emit-sets"
9930            );
9931        }
9932        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
9933            .iter()
9934            .map(std::borrow::Cow::from)
9935            .collect();
9936        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
9937            .iter()
9938            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
9939            .collect();
9940        assert_eq!(
9941            via_iter, via_method,
9942            "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
9943             call site whose iteration axis holds `&RestartPolicy` \
9944             by construction — must byte-equal `.iter().map(|p| \
9945             Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
9946             input Cow<'static, str> `From<&RestartPolicy> for \
9947             Cow<'static, str>` axis is what makes the `Cow::from` \
9948             composition route through the substrate-primitive \
9949             `RestartPolicy::as_str` accessor with the zero-alloc \
9950             Cow::Borrowed arm by construction and without a spurious \
9951             `Copy` deref (which would only be reachable through the \
9952             owned-input `From<RestartPolicy> for Cow<'static, str>` \
9953             axis by first calling `.copied()` on the iterator)"
9954        );
9955        for cow in &via_iter {
9956            assert!(
9957                matches!(cow, std::borrow::Cow::Borrowed(_)),
9958                "every element of the .iter().map(Cow::from) pipe \
9959                 over RestartPolicy::ALL must land on the zero-\
9960                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
9961                 any arm signals the pipe's iteration axis has \
9962                 silently allocated where the substrate-primitive \
9963                 RestartPolicy::as_str `&'static str` return makes \
9964                 the borrowed arm the type-correct projection"
9965            );
9966        }
9967    }
9968
9969    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
9970
9971    #[test]
9972    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
9973        // The fail-before-pass-after pin: pre-lift there was no
9974        // single-source binding between the [`RestartPolicy`] variant
9975        // name the un-`rename`d `Serialize` derive emits under
9976        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
9977        // byte-string every downstream cluster-side dispatcher (the
9978        // future wasm-operator's per-child post-exit restart-decision
9979        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
9980        // materializer's admission-time enum-arm bind, the
9981        // `caixa-operator`'s hierarchical reconciliation scheduler's
9982        // per-child-policy fan-out) probes verbatim. A future
9983        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
9984        // or a per-variant `#[serde(rename = "…")]` override, or a
9985        // variant rename in the source — would silently rebrand the
9986        // emitted scalar under one spelling while every downstream
9987        // dispatcher still probed the other, with the failure surfacing
9988        // at the operator's reconcile posture (children coming up under
9989        // the `default()` `Permanent` arm rather than the typed slot's
9990        // declared policy — a `:temporary` `oneShot` child would be
9991        // restarted on clean exit, treating the successful-completion
9992        // signal as failure and re-running the completion-terminal
9993        // one-shot indefinitely; a `:transient` child that clean-exited
9994        // would be restarted, masking the clean-completion contract)
9995        // far from the source rebrand commit and with no field naming
9996        // the drift. Pinning the two paths (the `Serialize` derive's
9997        // serialized string AND the [`RestartPolicy::as_str`] helper)
9998        // to the same three lifted
9999        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
10000        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
10001        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
10002        // byte-strings makes any future drift on either endpoint fail
10003        // here at caixa-core build time. Peer of the sibling
10004        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
10005        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
10006        // and the M3
10007        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
10008        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
10009        // same three-path-convergence discipline, extended to close the
10010        // third OTP-shaped closed-enum discriminator axis on the caixa
10011        // typed surface (per-child restart-decision policy).
10012        for (variant, expected) in [
10013            (
10014                RestartPolicy::Permanent,
10015                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10016            ),
10017            (
10018                RestartPolicy::Temporary,
10019                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10020            ),
10021            (
10022                RestartPolicy::Transient,
10023                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10024            ),
10025        ] {
10026            let json = serde_json::to_string(&variant).unwrap();
10027            assert_eq!(
10028                json,
10029                format!("\"{expected}\""),
10030                "RestartPolicy::{variant:?} must serialize to {expected:?}"
10031            );
10032            assert_eq!(
10033                variant.as_str(),
10034                expected,
10035                "RestartPolicy::{variant:?}.as_str() must return the lifted \
10036                 SUPERVISOR_CHILD_RESTART_* constant"
10037            );
10038        }
10039    }
10040
10041    #[test]
10042    fn supervisor_child_restart_consts_are_pairwise_distinct() {
10043        // Cross-arm drift-detection pin: a future collapse of two
10044        // canonical variant byte-strings onto the same value (e.g. an
10045        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
10046        // to also read `"Permanent"`) would silently reroute every
10047        // downstream operator's per-child-policy dispatch onto the
10048        // sibling arm's reconcile branch and pass every propagation-probe
10049        // test that expected only the stale arm's value — a `:transient`
10050        // child would come up under the `:permanent` restart-decision
10051        // posture on every subsequent clean exit, so a completion-terminal
10052        // child would be restarted indefinitely against its declared
10053        // policy. Peer of the sibling
10054        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
10055        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
10056        // and the four-way distinct pin
10057        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
10058        // top-level `SUPERVISOR_KEY_*` axis.
10059        let all = [
10060            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10061            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10062            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10063        ];
10064        for (i, a) in all.iter().enumerate() {
10065            for (j, b) in all.iter().enumerate() {
10066                if i != j {
10067                    assert_ne!(
10068                        a, b,
10069                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
10070                         — got duplicate {a:?} at indices {i} and {j}",
10071                    );
10072                }
10073            }
10074        }
10075    }
10076
10077    #[test]
10078    fn restart_policy_display_routes_through_as_str_helper() {
10079        // The fail-before-pass-after pin on the first half of the
10080        // three-path convergence: pre-convergence [`RestartPolicy`]
10081        // carried a [`std::fmt::Display`] surface via its
10082        // `#[discriminant(also_display)]` gen-platform derive route,
10083        // which arrived kebab-case as `"permanent"` / `"temporary"`
10084        // / `"transient"` on this three-arm enum (whose variant
10085        // names each collapse to their own lowercase form under the
10086        // kebab-case transform) while the wire format ran as
10087        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
10088        // through the un-`rename`d serde derive. Every consumer
10089        // reaching for a policy byte-string past the wire format had
10090        // to pick between three paths ([`RestartPolicy::as_str`],
10091        // the `Serialize` derive's serialized string, or
10092        // `format!("{v}")` on the discriminant-Display route), any
10093        // two of which a future variant rename or
10094        // `#[serde(rename_all = "kebab-case")]` attribute would
10095        // silently desynchronize. Wiring [`std::fmt::Display`]
10096        // through [`RestartPolicy::as_str`] closes the third path:
10097        // every `format!("{v}")` call reaches the same lifted
10098        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
10099        // wire format and the [`RestartPolicy::as_str`] helper
10100        // already route through, so a future variant rename lands at
10101        // exactly one place. Pin the routing here so a future
10102        // `impl std::fmt::Display for RestartPolicy`
10103        // reimplementation that hand-rolls the arms instead of
10104        // delegating to [`RestartPolicy::as_str`] fails at
10105        // caixa-core build time. Peer of the sibling
10106        // [`restart_strategy_display_routes_through_as_str_helper`]
10107        // on the per-supervisor sibling-restart-strategy axis and
10108        // the M3
10109        // `placement_strategy_display_routes_through_as_str_helper`
10110        // (cc8f749) — the third of three OTP-shape closed-enum
10111        // discriminator axes on the caixa typed surface now
10112        // converged onto the same three-path
10113        // (Display → as_str → lifted const) discipline.
10114        for variant in [
10115            RestartPolicy::Permanent,
10116            RestartPolicy::Temporary,
10117            RestartPolicy::Transient,
10118        ] {
10119            assert_eq!(
10120                variant.to_string(),
10121                variant.as_str(),
10122                "RestartPolicy::{variant:?} Display must route through \
10123                 RestartPolicy::as_str (single source of truth: the lifted \
10124                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
10125            );
10126        }
10127    }
10128
10129    #[test]
10130    fn restart_policy_display_matches_serialized_wire_byte_string() {
10131        // The fail-before-pass-after pin on the second half of the
10132        // three-path convergence: `Display` (user-facing text) agrees
10133        // byte-for-byte with the `Serialize` derive's wire format
10134        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
10135        // scalar) on every variant. Pre-convergence the two paths
10136        // were structurally independent — a future
10137        // `#[serde(rename_all = "kebab-case")]` attribute on the
10138        // enum would silently rebrand the emitted wire scalar
10139        // (`permanent`, `temporary`, `transient`) while every
10140        // consumer that pretty-prints the policy (the future
10141        // wasm-operator's per-child post-exit restart-decision
10142        // diagnostic line, the future `feira app graph` per-child
10143        // restart column, the future M4
10144        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
10145        // per-child admission-webhook rejection body) would still
10146        // emit the PascalCase form the `as_str` / `Display` route
10147        // returns, with the mismatch surfacing at consumer parse
10148        // time / operator dispatch time far from the source rebrand
10149        // commit. Pin the two paths byte-for-byte here so any future
10150        // serde-attribute or variant-rename drift is a
10151        // caixa-core-build-time test failure at this call, not a
10152        // silent per-consumer dispatch miss. Peer of the sibling
10153        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
10154        // on the per-supervisor sibling-restart-strategy axis and
10155        // the M3
10156        // `placement_strategy_display_matches_serialized_wire_byte_string`
10157        // (cc8f749).
10158        for variant in [
10159            RestartPolicy::Permanent,
10160            RestartPolicy::Temporary,
10161            RestartPolicy::Transient,
10162        ] {
10163            let wire = serde_json::to_string(&variant).unwrap();
10164            let unquoted = wire
10165                .strip_prefix('"')
10166                .and_then(|s| s.strip_suffix('"'))
10167                .expect("serialized RestartPolicy is a JSON string");
10168            assert_eq!(
10169                variant.to_string(),
10170                unquoted,
10171                "RestartPolicy::{variant:?} Display byte-string must match the \
10172                 Serialize derive's wire byte-string (three-path convergence: \
10173                 Display + as_str + Serialize all resolve to the same \
10174                 SUPERVISOR_CHILD_RESTART_* const)"
10175            );
10176        }
10177    }
10178
10179    #[test]
10180    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
10181        // Fail-before-pass-after byte-parity pin on the lifted
10182        // `impl AsRef<str> for RestartPolicy` — asserts the
10183        // standard-library trait impl and the substrate-primitive
10184        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
10185        // to the same `&str` per instance across the three-arm
10186        // closed set, so any future silent detour that routes the
10187        // impl through a divergent projection (a per-arm inline
10188        // `match self { RestartPolicy::Permanent => "Permanent", … }`
10189        // re-inlining that opens a compile-time link to the un-lifted
10190        // arm-literal, a swap onto the kebab-case
10191        // [`gen_platform::Discriminant`] catalog identity that would
10192        // collide the wire axis with the dispatcher-catalog axis) trips
10193        // at caixa-core test time under `PartialEq` rather than at a
10194        // downstream `impl AsRef<str>`-bound consumer's silent split.
10195        // Sweeps every one of the three arms
10196        // [`RestartPolicy::ALL`] carries so no arm's projection is
10197        // covered only by the sibling wire-format `Serialize` derive
10198        // path. Peer of the sibling
10199        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
10200        // (63eb1a4) on the paired per-supervisor sibling-restart-
10201        // strategy axis and the [`crate::CaixaVersion`]
10202        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
10203        // top-level `:versao` typed newtype — the three pins together
10204        // cover the substrate primitive's `AsRef<str>` projection axis
10205        // on the paired newtype + M2 closed-set-typed-enum surface.
10206        for &variant in RestartPolicy::ALL {
10207            assert_eq!(
10208                <RestartPolicy as AsRef<str>>::as_ref(&variant),
10209                variant.as_str(),
10210                "AsRef<str> impl on RestartPolicy::{variant:?} must \
10211                 byte-equal RestartPolicy::as_str on the same instance \
10212                 — divergence signals a silent detour off the substrate-\
10213                 primitive accessor"
10214            );
10215        }
10216    }
10217
10218    #[test]
10219    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
10220        // Fail-before-pass-after byte-parity pin on the three-path
10221        // convergence discipline the M2 per-child-restart-policy
10222        // primitive now carries on the `&str`-projection axis:
10223        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
10224        // lifted impl), `format!("{v}")` (the pre-existing
10225        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
10226        // primitive `pub const fn` accessor both trait impls delegate
10227        // through) must resolve to the same byte-string on every
10228        // instance across the three-arm closed set. Refuses any future
10229        // divergence between the two trait impls (a stray
10230        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
10231        // rather than delegating through the shared accessor; a
10232        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
10233        // literal cascade) that would silently split the two
10234        // projection paths of the same closed-set typed enum. Mirrors
10235        // the sibling three-path-convergence discipline the peer
10236        // [`RestartStrategy`] typed enum carries on its
10237        // `AsRef<str>` / `Display` / `as_str` triple
10238        // (supervisor.rs pin
10239        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
10240        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
10241        // carries on the same triple (version.rs pin
10242        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
10243        // 16d5c7e).
10244        for &variant in RestartPolicy::ALL {
10245            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
10246            let via_display: String = format!("{variant}");
10247            let via_accessor: &str = variant.as_str();
10248            assert_eq!(via_as_ref, via_accessor);
10249            assert_eq!(via_display, via_accessor);
10250            assert_eq!(via_as_ref, via_display.as_str());
10251        }
10252    }
10253
10254    #[test]
10255    fn restart_policy_all_enumerates_every_variant_exactly_once() {
10256        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
10257        // exhaustive-iteration surface: every variant appears exactly
10258        // once, and the slice length matches the arm count of the
10259        // closed set. Every consumer that walks the accepted-policy
10260        // set (a future `feira supervisor --restart …` CLI-side
10261        // arg-parse's "did you mean" hint, a future M4 admission-
10262        // webhook's per-child rejection body naming the accepted-
10263        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
10264        // projection consumers that iterate the accept-set for
10265        // diagnostic rendering) reads through this slice, so a future
10266        // arm addition that grows the enum but forgets to grow
10267        // [`Self::ALL`] silently truncates every downstream consumer's
10268        // accept-set at the same pre-addition boundary — this pin
10269        // fails at caixa-core build time on the pairwise-distinct +
10270        // arm-count invariants.
10271        //
10272        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
10273        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
10274        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
10275        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
10276        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
10277        // pins on the peer closed-set typed-enum axes.
10278        let all: &[RestartPolicy] = RestartPolicy::ALL;
10279        assert_eq!(
10280            all.len(),
10281            3,
10282            "RestartPolicy::ALL must enumerate every variant of the \
10283             three-arm closed set (Permanent, Temporary, Transient); \
10284             got {all:?}"
10285        );
10286        for (i, a) in all.iter().enumerate() {
10287            for (j, b) in all.iter().enumerate() {
10288                if i != j {
10289                    assert_ne!(
10290                        a, b,
10291                        "RestartPolicy::ALL must carry every variant exactly \
10292                         once — got duplicate {a:?} at indices {i} and {j}"
10293                    );
10294                }
10295            }
10296        }
10297        for variant in [
10298            RestartPolicy::Permanent,
10299            RestartPolicy::Temporary,
10300            RestartPolicy::Transient,
10301        ] {
10302            assert!(
10303                all.contains(&variant),
10304                "RestartPolicy::ALL must contain {variant:?} — a future arm \
10305                 addition that grows the enum but forgets to grow the ALL slice \
10306                 silently truncates every downstream consumer's accept-set at \
10307                 the pre-addition boundary"
10308            );
10309        }
10310    }
10311
10312    #[test]
10313    fn restart_policy_from_wire_accepts_every_lifted_constant() {
10314        // Fail-before-pass-after pin on the forward accept-set of the
10315        // [`RestartPolicy::from_wire`] reverse projection: every
10316        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
10317        // constant the [`RestartPolicy::as_str`] emitter walks parses
10318        // back to its paired variant. Any future arm addition that
10319        // grows the emitter's `as_str` match but forgets to grow the
10320        // parser's `from_wire` match silently splits the two halves of
10321        // the round-trip — the wire byte-string one non-serde consumer
10322        // parses from the one the emitter wrote — with the failure
10323        // surfacing at the operator's reconcile posture (a `:temporary`
10324        // `oneShot` child restarted on clean exit, a `:transient` child
10325        // restarted after clean completion) far from the rebrand
10326        // commit. Pinning the three-arm accept-set here catches the
10327        // drift at caixa-core build time.
10328        //
10329        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
10330        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
10331        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
10332        // accept-set pins on the peer closed-set typed-enum `str → Self`
10333        // axes.
10334        for (wire, expected) in [
10335            (
10336                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10337                RestartPolicy::Permanent,
10338            ),
10339            (
10340                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10341                RestartPolicy::Temporary,
10342            ),
10343            (
10344                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10345                RestartPolicy::Transient,
10346            ),
10347        ] {
10348            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
10349                panic!(
10350                    "RestartPolicy::from_wire({wire:?}) must accept every \
10351                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
10352                     lifted canonical byte-string that RestartPolicy::{expected:?} \
10353                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
10354                )
10355            });
10356            assert_eq!(
10357                parsed, expected,
10358                "RestartPolicy::from_wire({wire:?}) must return \
10359                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
10360            );
10361        }
10362    }
10363
10364    #[test]
10365    fn restart_policy_from_wire_round_trips_through_as_str() {
10366        // Fail-before-pass-after pin on the closed round-trip between
10367        // the forward [`RestartPolicy::as_str`] emitter and the
10368        // reverse [`RestartPolicy::from_wire`] parser: for every
10369        // variant in [`RestartPolicy::ALL`], parsing the emitter's
10370        // output must return exactly the same variant. Any per-arm
10371        // divergence — a future arm added to `as_str` but not
10372        // `from_wire`, an accidental copy-paste flip in one but not
10373        // the other — silently splits the emit and parse halves and
10374        // the failure surfaces at consumer parse time far from the
10375        // drift site. The `ALL`-iterating shape means a future arm
10376        // addition picks up the coverage by construction.
10377        //
10378        // Peer of the sibling
10379        // [`restart_strategy_from_wire_round_trips_through_as_str`]
10380        // (4eec29c) round-trip pin on
10381        // [`RestartStrategy::from_wire`] and the M3
10382        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
10383        // (18c7342) round-trip pin on
10384        // [`crate::aplicacao::PlacementStrategy::from_wire`].
10385        for &variant in RestartPolicy::ALL {
10386            let wire = variant.as_str();
10387            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
10388                panic!(
10389                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
10390                     must be Some({variant:?}) — the two halves of the round-trip \
10391                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
10392                     got None on wire byte-string {wire:?}"
10393                )
10394            });
10395            assert_eq!(
10396                parsed, variant,
10397                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
10398                 must round-trip to the same variant; got {parsed:?}"
10399            );
10400        }
10401    }
10402
10403    #[test]
10404    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
10405        // Fail-before-pass-after pin on the closed-set refusal
10406        // discipline of [`RestartPolicy::from_wire`]: every
10407        // byte-string outside the three-arm accept-set returns `None`
10408        // rather than silently collapsing onto the [`Default`]
10409        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
10410        // exercised here sweeps the load-bearing drift shapes: the
10411        // empty string (a stripped serde-attribute drift), all-
10412        // whitespace strings (the canonical text-editor accidental
10413        // padding shape), the kebab-case dispatcher-catalog identities
10414        // (`"permanent"` / `"temporary"` / `"transient"` — the
10415        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
10416        // accept-set, which parses the *other* axis of this enum's
10417        // two-axis split and must not leak into the `from_wire`
10418        // PascalCase-wire accept-set — a lowercase leak here would
10419        // silently accept the operator's kebab-case
10420        // dispatcher-catalog probe under the wire-axis parser and mis-
10421        // route a `:permanent` intent), the padded canonical scalar
10422        // (`" Permanent "`), the trailing-newline shapes
10423        // (`"Permanent\n"`), the uppercase-single-word forms
10424        // (`"PERMANENT"`), and neighboring-but-unknown arms
10425        // (`"Restart"` — the canonical typo direction toward the
10426        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
10427        //
10428        // Peer of the sibling
10429        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
10430        // (4eec29c) +
10431        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
10432        // (2aa6d23) +
10433        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
10434        // (18c7342) refusal pins on the peer closed-set typed-enum
10435        // axes.
10436        for bad in [
10437            "",
10438            " ",
10439            "\n",
10440            "\t",
10441            "permanent",
10442            "temporary",
10443            "transient",
10444            "PERMANENT",
10445            "TEMPORARY",
10446            "TRANSIENT",
10447            "Permanents",
10448            "Permanent ",
10449            " Permanent",
10450            " Transient ",
10451            "Permanent\n",
10452            "perma",
10453            "Trans",
10454            "OneForOne",
10455            "Restart",
10456            "?",
10457        ] {
10458            assert!(
10459                RestartPolicy::from_wire(bad).is_none(),
10460                "RestartPolicy::from_wire({bad:?}) must return None — the \
10461                 parser's accept-set is exactly the three RestartPolicy::as_str \
10462                 outputs (Permanent, Temporary, Transient), and this \
10463                 byte-string is outside that closed set"
10464            );
10465        }
10466    }
10467
10468    #[test]
10469    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
10470        // Fail-before-pass-after pin on the fourth path of the four-path
10471        // convergence: `from_wire` (the reverse projection) inverts the
10472        // `Serialize` derive's wire byte-string on every variant.
10473        // Together with the pre-existing three-path convergence
10474        // (`Display` + `as_str` + `Serialize` all resolve to the same
10475        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
10476        // pinned by
10477        // [`restart_policy_display_matches_serialized_wire_byte_string`])
10478        // this closes the round-trip: the wire byte-string the
10479        // `Serialize` derive emits parses back to the same variant
10480        // through `from_wire`, so any future serde-attribute or variant-
10481        // rename drift on the emit half now surfaces as a matched drift
10482        // on the parse half at caixa-core build time — the two halves
10483        // migrate as a unit through the lifted consts on any future
10484        // rename, and the round-trip cannot silently split.
10485        //
10486        // Peer of the sibling
10487        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
10488        // (4eec29c) wire-format pin on
10489        // [`RestartStrategy::from_wire`] and the M3
10490        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
10491        // (18c7342) wire-format pin on
10492        // [`crate::aplicacao::PlacementStrategy::from_wire`].
10493        for &variant in RestartPolicy::ALL {
10494            let wire = serde_json::to_string(&variant).unwrap();
10495            let unquoted = wire
10496                .strip_prefix('"')
10497                .and_then(|s| s.strip_suffix('"'))
10498                .expect("serialized RestartPolicy is a JSON string");
10499            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
10500                panic!(
10501                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
10502                     Serialize derive's wire byte-string for \
10503                     RestartPolicy::{variant:?} — the four-path convergence \
10504                     (Display + as_str + Serialize + from_wire) resolves through \
10505                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
10506                )
10507            });
10508            assert_eq!(
10509                parsed, variant,
10510                "RestartPolicy::from_wire of the Serialize derive's wire \
10511                 byte-string for RestartPolicy::{variant:?} must round-trip \
10512                 to the same variant; got {parsed:?}"
10513            );
10514        }
10515    }
10516
10517    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
10518    //
10519    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
10520    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
10521    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
10522    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
10523    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
10524    // the peer per-`:upgrade-from :from` axis. The three pins jointly
10525    // brace the accessor against every future silent detour that would
10526    // desynchronize it from the raw `.caixa` field access every consumer
10527    // previously open-coded.
10528
10529    #[test]
10530    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
10531        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
10532        // [`ChildSpec::nome`] must return the `:children :caixa` field
10533        // byte-for-byte across every DNS-1123-label value the upstream
10534        // [`crate::render::require_valid_dns_1123_label`] gate at
10535        // `SupervisorSpec::validate` admits. Peer of the sibling
10536        // `membro_nome_returns_caixa_byte_equal_across_permutations`
10537        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
10538        // substrate-primitive accessor must byte-equal the raw field
10539        // access verbatim across every author-declared value" discipline
10540        // extended to the M2 supervisor-tree per-`:children` arm. Pins
10541        // against a future silent detour that re-normalized the child
10542        // identity (an accidental `.to_lowercase()` — every `:children
10543        // :caixa` is validated as a DNS-1123 label upstream, so any
10544        // re-normalization is redundant + a drift surface between the
10545        // validator and the accessor), a namespace-prefix rewrite (an
10546        // accidental `format!("{namespace}/{caixa}")` per-CR
10547        // fully-qualified rewrite that didn't land on the peer axes), or
10548        // a per-cluster alias stamp the future wasm-operator's
10549        // hierarchical reconciliation scheduler authors on one consumer
10550        // without the others. Five values sweep the accept-set the
10551        // DNS-1123 gate upstream admits (short single-word / dashed /
10552        // v-suffixed / mixed-digit child names).
10553        for name in [
10554            "worker",
10555            "cache-server",
10556            "scratch-job",
10557            "orders-v2",
10558            "session-8080",
10559        ] {
10560            let c = ChildSpec {
10561                caixa: name.into(),
10562                versao: "^0.1".into(),
10563                restart: RestartPolicy::Permanent,
10564            };
10565            assert_eq!(
10566                c.nome(),
10567                name,
10568                "ChildSpec::nome must return :children :caixa verbatim \
10569                 (got {:?}, expected {name:?})",
10570                c.nome(),
10571            );
10572            assert_eq!(
10573                c.nome(),
10574                c.caixa.as_str(),
10575                "ChildSpec::nome must byte-equal the .caixa field access",
10576            );
10577        }
10578    }
10579
10580    #[test]
10581    fn child_spec_nome_borrows_from_caixa_storage() {
10582        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
10583        // `&str` slice that borrows from the typed slot's own [`String`]
10584        // storage — same-address invariant with `c.caixa.as_str()`. Pins
10585        // against a future silent detour that allocated a fresh `String`
10586        // (`self.caixa.clone()` in the body would type-check but silently
10587        // drop the borrow, and every downstream consumer that assumed
10588        // the returned slice outlives `&self` would break on a stale-
10589        // reference use-after-free — the [`crate::render::insert_first_seen`]
10590        // dedup key at [`SupervisorSpec::validate`], the
10591        // [`validate_no_self_supervision`] equality check against the
10592        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
10593        // borrow — each would silently misbehave if this accessor
10594        // produced a detached copy). Peer of the sibling
10595        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
10596        // M3 per-`:membros` axis and the
10597        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
10598        // first M2 slot scalar accessor.
10599        let c = ChildSpec {
10600            caixa: "worker".into(),
10601            versao: "^0.1".into(),
10602            restart: RestartPolicy::Permanent,
10603        };
10604        let name = c.nome();
10605        let caixa_slice = c.caixa.as_str();
10606        assert_eq!(
10607            name.as_ptr(),
10608            caixa_slice.as_ptr(),
10609            "ChildSpec::nome must borrow from the .caixa String's backing \
10610             storage — a fresh allocation here means the accessor no \
10611             longer names the substrate-primitive typed dispatch and \
10612             every downstream consumer would silently carry a detached \
10613             copy",
10614        );
10615        assert_eq!(
10616            name.len(),
10617            caixa_slice.len(),
10618            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
10619             as well as in address",
10620        );
10621    }
10622
10623    #[test]
10624    fn validate_gates_child_nome_through_lifted_accessor() {
10625        // Bilateral coherence pin: every `:children :caixa` that
10626        // [`SupervisorSpec::validate`] accepts is one
10627        // [`crate::render::require_valid_dns_1123_label`] accepts on the
10628        // accessor-projected value, and vice versa on the reject side.
10629        // This closes the "the validator reads through the accessor"
10630        // contract structurally — a future silent detour that made the
10631        // accessor return a different byte-string than the validator
10632        // gates against would surface here as a coverage mismatch, not
10633        // as an apply-time DNS-1123 rejection at
10634        // `metadata.name: Invalid value` far from the caixa.lisp source.
10635        // Peer of the M2 sibling
10636        // `validate_parses_prior_versao_through_lifted_accessor`
10637        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
10638        // `validate_membros` peer discipline.
10639        //
10640        // Accept-set sweep: five DNS-1123-label values the upstream gate
10641        // admits.
10642        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
10643            let s = SupervisorSpec {
10644                children: vec![ChildSpec {
10645                    caixa: ok_name.into(),
10646                    versao: "^0.1".into(),
10647                    restart: RestartPolicy::Permanent,
10648                }],
10649                ..SupervisorSpec::default()
10650            };
10651            s.validate().unwrap_or_else(|e| {
10652                panic!(
10653                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
10654                     (upstream DNS-1123 gate accepts it): got {e:?}",
10655                );
10656            });
10657            let c = ChildSpec {
10658                caixa: ok_name.into(),
10659                versao: "^0.1".into(),
10660                restart: RestartPolicy::Permanent,
10661            };
10662            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
10663                .unwrap_or_else(|()| {
10664                    panic!(
10665                        "require_valid_dns_1123_label must accept the accessor-projected \
10666                     :children :caixa {ok_name:?}",
10667                    );
10668                });
10669        }
10670        // Reject-set sweep: five DNS-1123-label-violating shapes the
10671        // upstream gate refuses (empty / uppercase / underscore / dot /
10672        // leading-hyphen). Every rejection at the validator must
10673        // correspond to a rejection when the accessor's projected value
10674        // is fed back through the shared gate.
10675        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
10676            let s = SupervisorSpec {
10677                children: vec![ChildSpec {
10678                    caixa: bad_name.into(),
10679                    versao: "^0.1".into(),
10680                    restart: RestartPolicy::Permanent,
10681                }],
10682                ..SupervisorSpec::default()
10683            };
10684            let err = s.validate().unwrap_err();
10685            assert!(
10686                matches!(
10687                    err,
10688                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
10689                ),
10690                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
10691                 via the DNS-1123 gate: got {err:?}",
10692            );
10693            let c = ChildSpec {
10694                caixa: bad_name.into(),
10695                versao: "^0.1".into(),
10696                restart: RestartPolicy::Permanent,
10697            };
10698            assert!(
10699                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
10700                    .is_err(),
10701                "require_valid_dns_1123_label must reject the accessor-projected \
10702                 :children :caixa {bad_name:?}",
10703            );
10704        }
10705    }
10706
10707    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
10708    //
10709    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
10710    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
10711    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
10712    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
10713    // trio on the peer per-`:children` `String`-carry axis. The three pins
10714    // jointly brace the accessor against every future silent detour that
10715    // would desynchronize it from the raw `.versao` field access the
10716    // requirement gate + error carrier previously open-coded.
10717    //
10718    // Closes the last unlifted per-`:children` `String`-carry axis: the
10719    // pair (`nome`, `versao_requirement`) now jointly projects the
10720    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
10721    // consumer that fans on per-child identity + version pin reads,
10722    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
10723    // pair discipline verbatim.
10724    #[test]
10725    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
10726        // The canonical per-`:children` child-`:versao`-scalar pin:
10727        // [`ChildSpec::versao_requirement`] must return the `:children
10728        // :versao` field byte-for-byte across every Cargo-shaped semver
10729        // requirement value the upstream
10730        // [`crate::render::require_valid_versao_requirement`] gate admits.
10731        // Peer of the sibling
10732        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
10733        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
10734        // substrate-primitive accessor must byte-equal the raw field
10735        // access verbatim across every author-declared value" discipline
10736        // extended to the M2 supervisor-tree per-`:children` arm. Pins
10737        // against a future silent detour that re-canonicalized the
10738        // requirement (an accidental `.to_string()` via
10739        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
10740        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
10741        // silently drifted the error carrier's quoted requirement away
10742        // from the source `caixa.lisp`, an accidental whitespace trim on
10743        // `"^ 0.1"` that no consumer ever produced from the field-access
10744        // side, an accidental per-cluster lacre-projected concrete-version
10745        // rewrite that didn't land on the peer requirement-gate call).
10746        // Five values sweep the accept-set the shared
10747        // [`crate::render::require_valid_versao_requirement`] gate admits
10748        // (caret / tilde / exact / wildcard / bare-major).
10749        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
10750            let c = ChildSpec {
10751                caixa: "worker".into(),
10752                versao: req.into(),
10753                restart: RestartPolicy::Permanent,
10754            };
10755            assert_eq!(
10756                c.versao_requirement(),
10757                req,
10758                "ChildSpec::versao_requirement must return :children :versao \
10759                 verbatim (got {:?}, expected {req:?})",
10760                c.versao_requirement(),
10761            );
10762            assert_eq!(
10763                c.versao_requirement(),
10764                c.versao.as_str(),
10765                "ChildSpec::versao_requirement must byte-equal the .versao \
10766                 field access",
10767            );
10768        }
10769    }
10770
10771    #[test]
10772    fn child_spec_versao_requirement_borrows_from_versao_storage() {
10773        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
10774        // return a `&str` slice that borrows from the typed slot's own
10775        // [`String`] storage — same-address invariant with
10776        // `c.versao.as_str()`. Pins against a future silent detour that
10777        // allocated a fresh `String` (`self.versao.clone()` in the body
10778        // would type-check but silently drop the borrow, and every
10779        // downstream consumer that assumed the returned slice outlives
10780        // `&self` — the [`crate::render::require_valid_versao_requirement`]
10781        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
10782        // `.to_string()` carrier's byte-length assumption — would silently
10783        // misbehave if this accessor produced a detached copy). Peer of
10784        // the sibling `child_spec_nome_borrows_from_caixa_storage`
10785        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
10786        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
10787        // pin on the peer per-`:membros` `:versao` axis.
10788        let c = ChildSpec {
10789            caixa: "worker".into(),
10790            versao: "^0.1".into(),
10791            restart: RestartPolicy::Permanent,
10792        };
10793        let req = c.versao_requirement();
10794        let versao_slice = c.versao.as_str();
10795        assert_eq!(
10796            req.as_ptr(),
10797            versao_slice.as_ptr(),
10798            "ChildSpec::versao_requirement must borrow from the .versao \
10799             String's backing storage — a fresh allocation here means the \
10800             accessor no longer names the substrate-primitive typed \
10801             dispatch and every downstream consumer would silently carry \
10802             a detached copy",
10803        );
10804        assert_eq!(
10805            req.len(),
10806            versao_slice.len(),
10807            "ChildSpec::versao_requirement and .versao.as_str() must \
10808             byte-equal in length as well as in address",
10809        );
10810    }
10811
10812    #[test]
10813    fn validate_gates_child_versao_through_lifted_accessor() {
10814        // Bilateral coherence pin: every `:children :versao` that
10815        // [`SupervisorSpec::validate`] accepts is one
10816        // [`crate::render::require_valid_versao_requirement`] accepts on
10817        // the accessor-projected value, and vice versa on the reject side.
10818        // This closes the "the validator reads through the accessor"
10819        // contract structurally — a future silent detour that made the
10820        // accessor return a different byte-string than the validator gates
10821        // against would surface here as a coverage mismatch, not as a
10822        // resolver-time semver-parse rejection at lacre-closure time far
10823        // from the caixa.lisp source. Peer of the sibling
10824        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
10825        // the per-`:children :caixa` axis and the M2
10826        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
10827        // on the peer per-`:upgrade-from :from` axis.
10828        //
10829        // Accept-set sweep: five Cargo-shaped semver requirement values
10830        // the upstream gate admits (caret / tilde / exact / wildcard /
10831        // bare-major).
10832        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
10833            let s = SupervisorSpec {
10834                children: vec![ChildSpec {
10835                    caixa: "worker".into(),
10836                    versao: ok_req.into(),
10837                    restart: RestartPolicy::Permanent,
10838                }],
10839                ..SupervisorSpec::default()
10840            };
10841            s.validate().unwrap_or_else(|e| {
10842                panic!(
10843                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
10844                     (upstream versao-requirement gate accepts it): got {e:?}",
10845                );
10846            });
10847            let c = ChildSpec {
10848                caixa: "worker".into(),
10849                versao: ok_req.into(),
10850                restart: RestartPolicy::Permanent,
10851            };
10852            crate::render::require_valid_versao_requirement(
10853                c.versao_requirement(),
10854                || (),
10855                |_reason| (),
10856            )
10857            .unwrap_or_else(|()| {
10858                panic!(
10859                    "require_valid_versao_requirement must accept the accessor-projected \
10860                     :children :versao {ok_req:?}",
10861                );
10862            });
10863        }
10864        // Reject-set sweep: five requirement-violating shapes the upstream
10865        // gate refuses. The empty string closes the empty-first arm of the
10866        // shared [`crate::render::require_valid_versao_requirement`]
10867        // cascade; the four non-empty arms exercise distinct semver-parse
10868        // failure modes the M3 peer per-`:membros` reject-set already pins
10869        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
10870        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
10871        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
10872        // shared parser routing means the same reject-set must fail
10873        // identically at the M2 supervisor-tree per-`:children` accessor
10874        // arm here. Every rejection at the validator must correspond to a
10875        // rejection when the accessor's projected value is fed back
10876        // through the shared gate.
10877        //
10878        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
10879        // `"not-a-semver"` are intentionally *not* in the reject-set: the
10880        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
10881        // and the identifier-tail arm's grammar admits some non-canonical
10882        // shapes — matching what the M3 peer test suite already documents
10883        // as the shared parser's accept-set edges.)
10884        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
10885            let s = SupervisorSpec {
10886                children: vec![ChildSpec {
10887                    caixa: "worker".into(),
10888                    versao: bad_req.into(),
10889                    restart: RestartPolicy::Permanent,
10890                }],
10891                ..SupervisorSpec::default()
10892            };
10893            let err = s.validate().unwrap_err();
10894            assert!(
10895                matches!(
10896                    err,
10897                    SupervisorError::EmptyChildVersion { .. }
10898                        | SupervisorError::ChildVersaoInvalid { .. }
10899                ),
10900                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
10901                 via the versao-requirement gate: got {err:?}",
10902            );
10903            let c = ChildSpec {
10904                caixa: "worker".into(),
10905                versao: bad_req.into(),
10906                restart: RestartPolicy::Permanent,
10907            };
10908            assert!(
10909                crate::render::require_valid_versao_requirement(
10910                    c.versao_requirement(),
10911                    || (),
10912                    |_reason| (),
10913                )
10914                .is_err(),
10915                "require_valid_versao_requirement must reject the accessor-projected \
10916                 :children :versao {bad_req:?}",
10917            );
10918        }
10919    }
10920
10921    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
10922    //
10923    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
10924    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
10925    // already project the `String`-carry `(caixa, versao)` fields; the
10926    // `Copy`-composite-enum `restart` field is the third and final axis).
10927    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
10928    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
10929    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
10930    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
10931    // strategy scalar accessor — same "one typed dispatch on the substrate
10932    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
10933    // extended onto the M2 supervisor-slot per-`:children` restart-decision
10934    // axis. The pin below covers the accessor's byte-equal projection
10935    // against the raw field access across every variant in the closed
10936    // accept-set (`Permanent`, `Transient`, `Temporary`).
10937
10938    #[test]
10939    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
10940        // The canonical per-`:children` restart-decision-policy-scalar
10941        // pin: [`ChildSpec::restart`] must return the `:children :restart`
10942        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
10943        // typed slot's own [`RestartPolicy`] storage across every variant
10944        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
10945        // Pins against a future silent detour that re-derived the policy
10946        // from a peer axis (an accidental fallback to
10947        // `if is_supervisor_child { Permanent } else { Temporary }` that
10948        // collapsed the child's kind axis into the restart discriminator),
10949        // a variant remap the operator authors on one consumer without the
10950        // other, or a stale-derive detour that substituted
10951        // [`RestartPolicy::default`] when the field held any explicit
10952        // variant (which would silently collapse the distinction between
10953        // "author explicitly declared `:restart Permanent`" and "author
10954        // omitted the slot and inherited the default" the future
10955        // per-cluster restart-decision override slot depends on).
10956        //
10957        // Peer of the sibling per-`:supervisor`
10958        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
10959        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
10960        // axis and the M3
10961        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
10962        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
10963        // — same "the substrate-primitive accessor must byte-equal the raw
10964        // field access verbatim across every author-declared value"
10965        // discipline extended onto the M2 supervisor-slot per-`:children`
10966        // restart-decision-policy axis, closing the last unlifted axis on
10967        // the per-`:children` [`ChildSpec`] type.
10968        for restart in [
10969            RestartPolicy::Permanent,
10970            RestartPolicy::Transient,
10971            RestartPolicy::Temporary,
10972        ] {
10973            let c = ChildSpec {
10974                caixa: "worker".into(),
10975                versao: "^0.1".into(),
10976                restart,
10977            };
10978            assert_eq!(
10979                c.restart(),
10980                restart,
10981                "ChildSpec::restart must return :children :restart \
10982                 verbatim (got {:?}, expected {restart:?})",
10983                c.restart(),
10984            );
10985            assert_eq!(
10986                c.restart(),
10987                c.restart,
10988                "ChildSpec::restart accessor and .restart field access \
10989                 must byte-equal — the accessor is the substrate-primitive \
10990                 typed dispatch every downstream per-child restart-\
10991                 decision consumer must route through",
10992            );
10993        }
10994    }
10995
10996    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
10997    //
10998    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
10999    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
11000    // distribution-strategy accessor discipline onto the M2 supervisor-slot
11001    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
11002    // scalar axis. The two pins below cover (1) the accessor's byte-equal
11003    // projection against the raw field access across every variant in the
11004    // closed accept-set, and (2) the two-consumer coherence between the
11005    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
11006    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
11007    // carrier's `estrategia:` field — peer of the sibling M3
11008    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
11009    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
11010    // pair on the per-`:placement` distribution-strategy axis.
11011
11012    #[test]
11013    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
11014        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
11015        // pin: [`SupervisorSpec::estrategia`] must return the
11016        // `:supervisor :estrategia` field verbatim as a
11017        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
11018        // [`RestartStrategy`] storage across every variant in the closed
11019        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
11020        // `SimpleOneForOne`). Pins against a future silent detour that
11021        // re-derived the strategy from a peer axis (an accidental
11022        // fallback to `if children.is_empty() { SimpleOneForOne } else {
11023        // OneForOne }` collapse that read the children-count axis into
11024        // the strategy discriminator), a variant remap the operator
11025        // authors on one consumer without the other, or a stale-derive
11026        // detour that substituted [`RestartStrategy::default`] when the
11027        // field held any explicit variant (which would silently collapse
11028        // the distinction between "author explicitly declared
11029        // `:estrategia OneForOne`" and "author omitted the slot and
11030        // inherited the default" the future per-cluster strategy override
11031        // slot depends on). Peer of the sibling M3
11032        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
11033        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
11034        // axis — same "the substrate-primitive accessor must byte-equal
11035        // the raw field access verbatim across every author-declared
11036        // value" discipline extended onto the M2 supervisor-slot
11037        // per-`:supervisor` sibling-restart-strategy axis.
11038        for &estrategia in RestartStrategy::ALL {
11039            // `SimpleOneForOne` requires `children.is_empty()`; the peer
11040            // three strategies require a non-empty static children list.
11041            // Build each shape coherently so the pin's fixture would
11042            // itself pass [`SupervisorSpec::validate`] once fed through
11043            // the sibling coherence pin below — the byte-equal projection
11044            // asserted here is a strictly weaker property (a `Copy` field
11045            // read) that does not depend on `validate` running, but
11046            // keeping the fixture validate-clean means a future extension
11047            // of the pin to exercise `validate` end-to-end does not have
11048            // to re-author the children shape.
11049            //
11050            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
11051            // shape partition through the [`gen_platform::IsVariant`]
11052            // derive-generated
11053            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
11054            // than the raw `matches!(estrategia, RestartStrategy::
11055            // SimpleOneForOne)` open-coded pattern-match — same closed-
11056            // set-typed-enum arm-discriminator dispatch discipline the
11057            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
11058            // convergence (915a934) extended onto its two paired positive
11059            // / negated `matches!` sites and the peer
11060            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
11061            // predicate convergence (766ec63) extended onto the M3 mesh-
11062            // slot per-`:placement` distribution-strategy discriminator
11063            // axis. See the sibling `round_trip_all_strategies` and the
11064            // peer `manifest::tests::
11065            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
11066            // fixture for the two peer sites the same lift closes on.
11067            let children = if estrategia.is_simple_one_for_one() {
11068                Vec::new()
11069            } else {
11070                vec![ChildSpec {
11071                    caixa: "worker".into(),
11072                    versao: "^0.1".into(),
11073                    restart: RestartPolicy::Permanent,
11074                }]
11075            };
11076            let s = SupervisorSpec {
11077                estrategia,
11078                children,
11079                ..SupervisorSpec::default()
11080            };
11081            assert_eq!(
11082                s.estrategia(),
11083                estrategia,
11084                "SupervisorSpec::estrategia must return :supervisor :estrategia \
11085                 verbatim (got {:?}, expected {estrategia:?})",
11086                s.estrategia(),
11087            );
11088            assert_eq!(
11089                s.estrategia(),
11090                s.estrategia,
11091                "SupervisorSpec::estrategia accessor and .estrategia field \
11092                 access must byte-equal — the accessor is the substrate-\
11093                 primitive typed dispatch every downstream sibling-restart-\
11094                 strategy consumer must route through",
11095            );
11096        }
11097    }
11098
11099    #[test]
11100    fn validate_reads_through_lifted_estrategia_accessor() {
11101        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
11102        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
11103        // dispatch (which reads through [`SupervisorSpec::estrategia`]
11104        // to fan across the strategy-arm shape-gate cascades) and the
11105        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
11106        // error carrier's `estrategia:` field (which reads through
11107        // [`SupervisorSpec::estrategia`] to name the strategy the empty
11108        // `:children` list was declared against) must both key off the
11109        // lifted accessor, so any future rebrand on the typed slot's
11110        // reader shape lands at exactly one place. Pins the two-site
11111        // coherence by exercising the `NoChildren` error surface end-to-
11112        // end across every non-`SimpleOneForOne` variant and asserting
11113        // the surfaced `estrategia:` field byte-equals the accessor's
11114        // return. Peer of the sibling M3
11115        // `validate_placement_reads_through_lifted_estrategia_accessor`
11116        // (921fe1b) three-consumer coherence pin on the per-`:placement`
11117        // distribution-strategy axis.
11118        for estrategia in [
11119            RestartStrategy::OneForOne,
11120            RestartStrategy::OneForAll,
11121            RestartStrategy::RestForOne,
11122        ] {
11123            let s = SupervisorSpec {
11124                estrategia,
11125                children: Vec::new(),
11126                ..SupervisorSpec::default()
11127            };
11128            let err = s.validate().unwrap_err();
11129            match err {
11130                SupervisorError::NoChildren { estrategia: e } => {
11131                    assert_eq!(
11132                        e,
11133                        s.estrategia(),
11134                        "NoChildren.estrategia must byte-equal \
11135                         SupervisorSpec::estrategia() — the empty-`:children` \
11136                         refusal reads through the lifted accessor",
11137                    );
11138                    assert_eq!(
11139                        e, estrategia,
11140                        "NoChildren.estrategia must carry the author-declared \
11141                         :supervisor :estrategia variant verbatim (got {e:?}, \
11142                         expected {estrategia:?})",
11143                    );
11144                }
11145                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
11146            }
11147        }
11148    }
11149
11150    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
11151    //
11152    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
11153    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
11154    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
11155    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
11156    // The two pins below cover (1) the accessor's byte-equal projection
11157    // against the raw field access across every representative value in
11158    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
11159    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
11160    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
11161    // zero-floor / cap composition — the validate gate and the accessor
11162    // must route through the same substrate-primitive typed dispatch, so
11163    // any future silent detour that had the accessor perform a
11164    // bounds-collapsing clamp would fail here at caixa-core build time.
11165    // Peer of the sibling M3
11166    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
11167    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
11168
11169    #[test]
11170    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
11171        // The canonical per-`:supervisor` restart-budget-count scalar pin:
11172        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
11173        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
11174        // typed slot's own `u32` storage, byte-equal to the raw field
11175        // access across every representative value in the accept-set —
11176        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
11177        // accept-set the surrounding [`SupervisorSpec::validate`] gate
11178        // carves out on the sibling `ZeroMaxRestarts` refusal),
11179        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
11180        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
11181        // (a past-the-guard sentinel that pins the accessor doesn't
11182        // perform a silent bounds-collapse into `1` on the zero arm —
11183        // validate rejects zero but the accessor must ship the raw slot
11184        // verbatim so a validate-time gate regression surfaces at the
11185        // emit boundary rather than being silently absorbed), `u32::MAX`
11186        // (a past-the-guard sentinel that pins the accessor doesn't
11187        // perform a silent bounds-collapse through
11188        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
11189        //
11190        // Peer of the sibling M3
11191        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
11192        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
11193        // required-scalar axis — same "the substrate-primitive accessor
11194        // must byte-equal the raw field access verbatim across every
11195        // value in the `u32` accept-set" discipline extended onto the M2
11196        // supervisor-slot per-`:supervisor` restart-budget-count axis.
11197        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
11198            let s = SupervisorSpec {
11199                max_restarts,
11200                ..SupervisorSpec::default()
11201            };
11202            assert_eq!(
11203                s.max_restarts(),
11204                max_restarts,
11205                "SupervisorSpec::max_restarts must return :supervisor \
11206                 :max-restarts verbatim (got {}, expected {max_restarts})",
11207                s.max_restarts(),
11208            );
11209            assert_eq!(
11210                s.max_restarts(),
11211                s.max_restarts,
11212                "SupervisorSpec::max_restarts accessor and .max_restarts \
11213                 field access must byte-equal — the accessor is the \
11214                 substrate-primitive typed dispatch every downstream \
11215                 restart-budget-count consumer must route through",
11216            );
11217        }
11218    }
11219
11220    #[test]
11221    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
11222        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
11223        // zero-floor + upper-cap bracket must key off
11224        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
11225        // field access. Structurally: a `SupervisorSpec { max_restarts:
11226        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
11227        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
11228        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
11229        // (with the offending count carried verbatim from the accessor
11230        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
11231        // lower boundary of the accept-set) plus a `SupervisorSpec {
11232        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
11233        // boundary) must pass validate. The four together jointly pin the
11234        // accessor + validate-gate composition: any future silent detour
11235        // that had the accessor return a fresh `1` on the zero arm (a
11236        // `.max_restarts().max(1)` collapse) would silently absorb the
11237        // `ZeroMaxRestarts` refusal at the accessor boundary and the
11238        // validate gate would accept a struct-literal `SupervisorSpec {
11239        // max_restarts: 0, .. }` — the composition pin catches that at
11240        // caixa-core build time.
11241        //
11242        // Peer of the sibling M3
11243        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
11244        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
11245        // composition axis — same "the validate / shape-gate predicate
11246        // must route through the substrate-primitive typed dispatch"
11247        // discipline extended onto the peer M2 supervisor-slot
11248        // required-`u32` composition axis.
11249        let child = ChildSpec {
11250            caixa: "worker".into(),
11251            versao: "^0.1".into(),
11252            restart: RestartPolicy::Permanent,
11253        };
11254        // Zero-floor arm.
11255        let s = SupervisorSpec {
11256            max_restarts: 0,
11257            children: vec![child.clone()],
11258            ..SupervisorSpec::default()
11259        };
11260        assert_eq!(
11261            s.validate().unwrap_err(),
11262            SupervisorError::ZeroMaxRestarts,
11263            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
11264             — the accessor and the validate gate must route through the \
11265             same substrate-primitive typed dispatch on the zero-floor arm",
11266        );
11267        // Cap arm — the surfaced `max_restarts:` field must byte-equal
11268        // the accessor's return so a future rebrand on the accessor
11269        // lands in the diagnostic without a coordinated rewrite.
11270        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
11271        let s = SupervisorSpec {
11272            max_restarts: over_cap,
11273            children: vec![child.clone()],
11274            ..SupervisorSpec::default()
11275        };
11276        match s.validate().unwrap_err() {
11277            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
11278                assert_eq!(
11279                    max_restarts,
11280                    s.max_restarts(),
11281                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
11282                     SupervisorSpec::max_restarts() — the cap-arm refusal \
11283                     reads through the lifted accessor",
11284                );
11285                assert_eq!(
11286                    max_restarts, over_cap,
11287                    "MaxRestartsExceedsCap.max_restarts must carry the \
11288                     author-declared :supervisor :max-restarts value \
11289                     verbatim (got {max_restarts}, expected {over_cap})",
11290                );
11291            }
11292            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
11293        }
11294        // Lower + upper accept-set boundaries.
11295        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
11296            let s = SupervisorSpec {
11297                max_restarts,
11298                children: vec![child.clone()],
11299                ..SupervisorSpec::default()
11300            };
11301            assert!(
11302                s.validate().is_ok(),
11303                "validate must accept max_restarts == {max_restarts} \
11304                 (an accept-set boundary of \
11305                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
11306            );
11307        }
11308    }
11309
11310    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
11311    //
11312    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
11313    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
11314    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
11315    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
11316    // supervisor-slot per-`:supervisor` restart-intensity-denominator
11317    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
11318    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
11319    // per-`:supervisor` scalar-value axis. The three pins below cover
11320    // (1) the accessor's byte-equal projection against the raw field
11321    // access across every representative value in the `Option<Duration>`
11322    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
11323    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
11324    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
11325    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
11326    // `if let Some(w) = self.restart_window() { … }` bracket-arm
11327    // composition — the validate gate and the accessor must route through
11328    // the same substrate-primitive typed dispatch, so any future silent
11329    // detour that had the accessor perform a bounds-collapsing clamp
11330    // would fail here at caixa-core build time, and (3) the accessor's
11331    // by-copy idempotence pin — the returned `Option<Duration>` must
11332    // outlive `&self` and two successive calls must return byte-equal
11333    // values. Peer of the sibling M2
11334    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
11335    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
11336    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
11337    // (7073d0f) pin on the per-`:politicas :timeout` axis.
11338
11339    #[test]
11340    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
11341        // The canonical per-`:supervisor` restart-intensity-denominator
11342        // scalar pin: [`SupervisorSpec::restart_window`] must return the
11343        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
11344        // `Option<Duration>`, `Copy`-projected from the typed slot's own
11345        // `Option<Duration>` storage, byte-equal to the raw field access
11346        // across every representative value in the accept-set — `None`
11347        // (the "never reset — every restart across the supervisor's
11348        // lifetime counts against the sibling `:max-restarts` budget"
11349        // sentinel the field's own docstring names and the peer
11350        // `validate_accepts_none_restart_window` pin locks in on the
11351        // [`SupervisorSpec::validate`] entry-side),
11352        // `Some(Duration::from_millis(1))` (the structural minimum a
11353        // validated `:restart-window` may carry, the integer-millisecond
11354        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
11355        // everything sub-ms; `Duration::ZERO` is separately rejected by
11356        // [`SupervisorError::RestartWindowZero`]),
11357        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
11358        // surrounding [`SupervisorSpec::validate`] gate carves out on the
11359        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
11360        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
11361        // accessor doesn't perform a silent bounds-collapse into `None` on
11362        // the zero-Duration arm — validate rejects zero but the accessor
11363        // must ship the raw slot verbatim so a validate-time gate
11364        // regression surfaces at the emit boundary rather than being
11365        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
11366        // sentinel that pins the accessor doesn't perform a silent
11367        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
11368        // return path).
11369        //
11370        // Peer of the sibling M2
11371        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
11372        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
11373        // sibling M3
11374        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
11375        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
11376        // substrate-primitive accessor must byte-equal the raw field
11377        // access verbatim across every value in the `Option<Duration>`
11378        // accept-set" discipline extended onto the M2 supervisor-slot
11379        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
11380        // silent detour that re-derived the restart-window from a peer
11381        // axis (an accidental `.max_restarts.into()` collapse that read
11382        // the restart-budget-count as a duration — the two axes serve
11383        // different halves of the `MaxIntensity / Period` restart-
11384        // intensity ratio, and confusing them silently inverts the
11385        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
11386        // "zero means never reset" collapse (the canonical
11387        // `Option<Duration>` → `Duration` collapse footgun the
11388        // [`SupervisorError::RestartWindowZero`] validate arm guards on
11389        // the peer zero-floor axis; a zero period either trips on the
11390        // first failure or never trips depending on operator
11391        // interpretation, neither of which is the author's "never reset"
11392        // intent that `None` expresses structurally), or a per-arm
11393        // variant swap that landed on one consumer without the other.
11394        for restart_window in [
11395            None,
11396            Some(Duration::from_millis(1)),
11397            Some(SUPERVISOR_RESTART_WINDOW_MAX),
11398            Some(Duration::ZERO),
11399            Some(Duration::MAX),
11400        ] {
11401            let s = SupervisorSpec {
11402                restart_window,
11403                ..SupervisorSpec::default()
11404            };
11405            assert_eq!(
11406                s.restart_window(),
11407                restart_window,
11408                "SupervisorSpec::restart_window must return :supervisor \
11409                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
11410                s.restart_window(),
11411            );
11412            assert_eq!(
11413                s.restart_window(),
11414                s.restart_window,
11415                "SupervisorSpec::restart_window accessor and \
11416                 .restart_window field access must byte-equal — the \
11417                 accessor is the substrate-primitive typed dispatch every \
11418                 downstream restart-intensity-denominator consumer must \
11419                 route through",
11420            );
11421        }
11422    }
11423
11424    #[test]
11425    fn validate_restart_window_bracket_arm_routes_through_accessor() {
11426        // Composition pin: [`SupervisorSpec::validate`]'s
11427        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
11428        // zero-floor + integer-millisecond canonical-form + upper-cap
11429        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
11430        // the raw `.restart_window` field access. Structurally: a
11431        // `SupervisorSpec { restart_window: None, .. }` must pass the
11432        // arm gate structurally (the `if let Some(_)` shape returns
11433        // early on the `None` arm — the accessor and the validate gate
11434        // must agree on `None → skip the bracket cascade` so an authored
11435        // `:restart-window ()` structurally routes through the "never
11436        // reset" sentinel path), a `SupervisorSpec { restart_window:
11437        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
11438        // refusal exactly, a `SupervisorSpec { restart_window:
11439        // Some(Duration::from_micros(1500)), .. }` must surface the
11440        // `RestartWindowNotCanonical` refusal exactly (with the offending
11441        // duration carried verbatim from the accessor return), a
11442        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
11443        // + Duration::from_millis(1)), .. }` must surface the
11444        // `RestartWindowExceedsCap` refusal exactly (with the offending
11445        // duration carried verbatim from the accessor return), and a
11446        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
11447        // .. }` (the lower boundary of the accept-set) plus a
11448        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
11449        // .. }` (the upper boundary) must pass validate. The six together
11450        // jointly pin the accessor + validate-gate composition: any future
11451        // silent detour that had the accessor return a fresh `None` on any
11452        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
11453        // collapse) would silently absorb the `RestartWindowZero` refusal
11454        // at the accessor boundary and the validate gate would accept a
11455        // struct-literal `SupervisorSpec { restart_window:
11456        // Some(Duration::ZERO), .. }` — the composition pin catches that
11457        // at caixa-core build time.
11458        //
11459        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
11460        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
11461        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
11462        // accessor-composition pin on the per-`:politicas :timeout` axis —
11463        // same "the validate / shape-gate predicate must route through
11464        // the substrate-primitive typed dispatch" discipline extended
11465        // onto the peer M2 supervisor-slot optional-`Duration` axis.
11466        let child = ChildSpec {
11467            caixa: "worker".into(),
11468            versao: "^0.1".into(),
11469            restart: RestartPolicy::Permanent,
11470        };
11471        // None arm — must not surface any :restart-window-shaped refusal;
11472        // the `if let Some(_)` bracket returns early on `None` structurally.
11473        let s = SupervisorSpec {
11474            restart_window: None,
11475            children: vec![child.clone()],
11476            ..SupervisorSpec::default()
11477        };
11478        assert!(
11479            s.validate().is_ok(),
11480            "validate must accept restart_window: None (the never-reset \
11481             sentinel) — the `if let Some(_)` bracket returns early on \
11482             the None arm and the accessor must agree",
11483        );
11484        // Zero-floor arm.
11485        let s = SupervisorSpec {
11486            restart_window: Some(Duration::ZERO),
11487            children: vec![child.clone()],
11488            ..SupervisorSpec::default()
11489        };
11490        assert_eq!(
11491            s.validate().unwrap_err(),
11492            SupervisorError::RestartWindowZero,
11493            "validate must reject restart_window == Some(Duration::ZERO) \
11494             with RestartWindowZero — the accessor and the validate gate \
11495             must route through the same substrate-primitive typed \
11496             dispatch on the zero-floor arm",
11497        );
11498        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
11499        // byte-equal the accessor's return so a future rebrand on the
11500        // accessor lands in the diagnostic without a coordinated rewrite.
11501        let sub_ms = Duration::from_micros(1500);
11502        let s = SupervisorSpec {
11503            restart_window: Some(sub_ms),
11504            children: vec![child.clone()],
11505            ..SupervisorSpec::default()
11506        };
11507        match s.validate().unwrap_err() {
11508            SupervisorError::RestartWindowNotCanonical { window } => {
11509                assert_eq!(
11510                    Some(window),
11511                    s.restart_window(),
11512                    "RestartWindowNotCanonical.window must byte-equal \
11513                     SupervisorSpec::restart_window().unwrap() — the \
11514                     non-canonical-arm refusal reads through the lifted \
11515                     accessor",
11516                );
11517                assert_eq!(
11518                    window, sub_ms,
11519                    "RestartWindowNotCanonical.window must carry the \
11520                     author-declared :supervisor :restart-window value \
11521                     verbatim (got {window:?}, expected {sub_ms:?})",
11522                );
11523            }
11524            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
11525        }
11526        // Cap arm — the surfaced `window:` field must byte-equal the
11527        // accessor's return.
11528        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
11529        let s = SupervisorSpec {
11530            restart_window: Some(over_cap),
11531            children: vec![child.clone()],
11532            ..SupervisorSpec::default()
11533        };
11534        match s.validate().unwrap_err() {
11535            SupervisorError::RestartWindowExceedsCap { window } => {
11536                assert_eq!(
11537                    Some(window),
11538                    s.restart_window(),
11539                    "RestartWindowExceedsCap.window must byte-equal \
11540                     SupervisorSpec::restart_window().unwrap() — the \
11541                     cap-arm refusal reads through the lifted accessor",
11542                );
11543                assert_eq!(
11544                    window, over_cap,
11545                    "RestartWindowExceedsCap.window must carry the \
11546                     author-declared :supervisor :restart-window value \
11547                     verbatim (got {window:?}, expected {over_cap:?})",
11548                );
11549            }
11550            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
11551        }
11552        // Lower + upper accept-set boundaries.
11553        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
11554            let s = SupervisorSpec {
11555                restart_window: Some(restart_window),
11556                children: vec![child.clone()],
11557                ..SupervisorSpec::default()
11558            };
11559            assert!(
11560                s.validate().is_ok(),
11561                "validate must accept restart_window == Some({restart_window:?}) \
11562                 (an accept-set boundary of \
11563                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
11564            );
11565        }
11566    }
11567
11568    #[test]
11569    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
11570        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
11571        // `Option<Duration>` by copy — `Duration` is `Copy` (so
11572        // `Option<Duration>` is `Copy`) and the accessor must return by
11573        // value, not by reference. Peer of the sibling M2
11574        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
11575        // per-`:limits :wall-clock` axis and the sibling M3
11576        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
11577        // per-`:politicas :timeout` axis, extended onto the peer M2
11578        // supervisor-slot `Option<Duration>` copy-invariant shape — the
11579        // accessor's returned `Option<Duration>` must outlive `&self`
11580        // (multiple calls must return equal values from a dropped-`&self`
11581        // copy, since the returned Option carries no borrow), and calling
11582        // the accessor twice on the same SupervisorSpec must yield the
11583        // same `Option<Duration>` verbatim (idempotent, no side effects
11584        // on `&self`).
11585        //
11586        // Pins against a future silent detour that returned
11587        // `Option<&Duration>` (which would type-check but silently break
11588        // every downstream caller — the future wasm-operator's
11589        // per-supervisor restart-intensity counter consumes `Duration` by
11590        // value and `&Duration` would fold to a detached copy at the call
11591        // site), an accidental `Option::as_ref()` projection
11592        // (`self.restart_window.as_ref()` would also type-check but
11593        // return `Option<&Duration>`), or a one-arm-only accessor that
11594        // reads `Some(*w)` in the Some arm but reads a fresh
11595        // `Default::default()` (which would collapse to `Duration::ZERO`,
11596        // not `None`) in the None arm — a footgun the
11597        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
11598        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
11599        // requires `Period > 0` and `None` structurally expresses "never
11600        // reset" instead.
11601        for restart_window in [
11602            None,
11603            Some(Duration::from_millis(1)),
11604            Some(Duration::from_secs(60)),
11605            Some(SUPERVISOR_RESTART_WINDOW_MAX),
11606        ] {
11607            let s = SupervisorSpec {
11608                restart_window,
11609                ..SupervisorSpec::default()
11610            };
11611            let first = s.restart_window();
11612            let second = s.restart_window();
11613            assert_eq!(
11614                first, second,
11615                "SupervisorSpec::restart_window must be idempotent — two \
11616                 successive calls on the same &self must return the \
11617                 same Option<Duration>",
11618            );
11619            assert_eq!(
11620                first, restart_window,
11621                "SupervisorSpec::restart_window must return :supervisor \
11622                 :restart-window verbatim by copy — got {first:?}, \
11623                 expected {restart_window:?}",
11624            );
11625        }
11626    }
11627
11628    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
11629    //
11630    // The [`SupervisorSpec::children`] accessor lift is the seed of the
11631    // slice-return (`&[T]`) accessor discipline on the substrate — the four
11632    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
11633    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
11634    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
11635    // access at the time of this seed, and inherit this pin family's
11636    // discipline as future compounding runs migrate their consumers. The
11637    // three pins below cover (1) the accessor's byte-equal projection
11638    // against the raw field access across the empty / singleton / cohort
11639    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
11640    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
11641    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
11642    // consumer routing through the accessor on both arms, and (3) the
11643    // per-child validate loop's traversal reading the same slice-view the
11644    // accessor projects. Peer of the sibling M2
11645    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
11646    // two-consumer coherence pin on the per-`:supervisor`
11647    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
11648    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
11649
11650    #[test]
11651    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
11652        // The canonical per-`:supervisor` static-child-list scalar-shape
11653        // pin: [`SupervisorSpec::children`] must return the `:supervisor
11654        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
11655        // slice-view over the same backing buffer the raw
11656        // `self.children.as_slice()` field access borrows from, byte-
11657        // equal across every representative fixture in the accept-set —
11658        // the empty slice (the `SimpleOneForOne`-arm sentinel),
11659        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
11660        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
11661        // with the peer three restart-policy variants in play).
11662        //
11663        // Pins against a future silent detour that returned
11664        // `&Vec<ChildSpec>` (which would type-check but leak the
11665        // storage-side `Vec`'s grow/push/reserve surface no consumer of
11666        // the typed view reaches for), a fresh-allocated
11667        // `Vec<ChildSpec>` copy (which would type-check via a coercion
11668        // but silently break every downstream caller that relied on the
11669        // slice sharing the backing buffer's identity), or an
11670        // out-of-order or length-drifted projection (which would silently
11671        // split the per-child validate loop's traversal input from the
11672        // paired partition-dispatch `.is_empty()` probe's input).
11673        //
11674        // Peer of the sibling
11675        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
11676        // (eafb619) `Copy`-composite-enum byte-equal pin on the
11677        // per-`:supervisor` sibling-restart-strategy axis, extended onto
11678        // the per-`:supervisor` static-child-list `Vec`-carry axis.
11679        let fixtures: Vec<Vec<ChildSpec>> = vec![
11680            Vec::new(),
11681            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
11682            vec![
11683                child("worker", "^0.1", RestartPolicy::Permanent),
11684                child("cache-server", "^0.1", RestartPolicy::Transient),
11685            ],
11686            vec![
11687                child("worker", "^0.1", RestartPolicy::Permanent),
11688                child("cache-server", "^0.1", RestartPolicy::Transient),
11689                child("scratch-job", "^0.1", RestartPolicy::Temporary),
11690            ],
11691        ];
11692        for children in fixtures {
11693            let s = SupervisorSpec {
11694                children: children.clone(),
11695                ..SupervisorSpec::default()
11696            };
11697            assert_eq!(
11698                s.children(),
11699                children.as_slice(),
11700                "SupervisorSpec::children must return :supervisor \
11701                 :children verbatim (got {:?}, expected {:?})",
11702                s.children(),
11703                children.as_slice(),
11704            );
11705            assert_eq!(
11706                s.children(),
11707                s.children.as_slice(),
11708                "SupervisorSpec::children accessor and \
11709                 .children.as_slice() field access must byte-equal — \
11710                 the accessor is the substrate-primitive typed \
11711                 dispatch every downstream static-child-list consumer \
11712                 must route through",
11713            );
11714            assert_eq!(
11715                s.children().len(),
11716                s.children.len(),
11717                "SupervisorSpec::children().len() must byte-equal \
11718                 self.children.len() — a length-drift would silently \
11719                 split the paired partition-dispatch `.is_empty()` \
11720                 probe input from the per-child validate loop's \
11721                 traversal input",
11722            );
11723        }
11724    }
11725
11726    #[test]
11727    fn validate_reads_through_lifted_children_accessor() {
11728        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
11729        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
11730        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
11731        // when the accessor projects a non-empty slice under a
11732        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
11733        // `self.children().is_empty()` refusal probe (which must trip
11734        // [`SupervisorError::NoChildren`] when the accessor projects the
11735        // empty slice under any peer estrategia), and the per-child
11736        // validate loop's `for child in self.children()` traversal
11737        // (which must reach every entry in the same order the accessor
11738        // projects) must all key off the lifted accessor, so any future
11739        // rebrand on the typed slot's reader shape lands at exactly one
11740        // place. Pins the three-site coherence by exercising each
11741        // production consumer end-to-end: (1) the
11742        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
11743        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
11744        // refusal under the empty slice + non-`SimpleOneForOne`
11745        // estrategia across every peer variant, and (3) the per-child
11746        // duplicate-detection surface fires on the second entry of a
11747        // two-child cohort that shares a `:caixa` name (which requires
11748        // the loop to reach both entries — a first-entry-only projection
11749        // would silently pass since the dedup HashSet has room for the
11750        // first insert).
11751        //
11752        // Peer of the sibling M2
11753        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
11754        // two-consumer coherence pin on the per-`:supervisor`
11755        // sibling-restart-strategy axis, extended onto the
11756        // per-`:supervisor` static-child-list `Vec`-carry axis.
11757
11758        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
11759        // `SimpleOneForOne` estrategia must trip
11760        // `SimpleOneForOneWithStaticChildren`.
11761        let s = SupervisorSpec {
11762            estrategia: RestartStrategy::SimpleOneForOne,
11763            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
11764            ..SupervisorSpec::default()
11765        };
11766        assert_eq!(
11767            s.validate().unwrap_err(),
11768            SupervisorError::SimpleOneForOneWithStaticChildren,
11769            "SimpleOneForOne + non-empty children must trip \
11770             SimpleOneForOneWithStaticChildren — the accessor projects \
11771             a non-empty slice, and the SimpleOneForOne-arm refusal \
11772             probe reads through the lifted accessor",
11773        );
11774        assert!(
11775            !s.children().is_empty(),
11776            "the SimpleOneForOne-arm refusal input must be a non-empty \
11777             slice per the accessor's projection",
11778        );
11779
11780        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
11781        // under any peer estrategia must trip `NoChildren`.
11782        for estrategia in [
11783            RestartStrategy::OneForOne,
11784            RestartStrategy::OneForAll,
11785            RestartStrategy::RestForOne,
11786        ] {
11787            let s = SupervisorSpec {
11788                estrategia,
11789                children: Vec::new(),
11790                ..SupervisorSpec::default()
11791            };
11792            match s.validate().unwrap_err() {
11793                SupervisorError::NoChildren { estrategia: e } => {
11794                    assert_eq!(
11795                        e, estrategia,
11796                        "NoChildren.estrategia must carry the author-\
11797                         declared :supervisor :estrategia variant \
11798                         verbatim (got {e:?}, expected {estrategia:?})",
11799                    );
11800                }
11801                other => panic!(
11802                    "expected NoChildren, got {other:?} for \
11803                     estrategia={estrategia:?}"
11804                ),
11805            }
11806            assert!(
11807                s.children().is_empty(),
11808                "the non-SimpleOneForOne-arm refusal input must be the \
11809                 empty slice per the accessor's projection",
11810            );
11811        }
11812
11813        // (3) Per-child validate loop: a two-child cohort that shares a
11814        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
11815        // reach both entries through the accessor.
11816        let s = SupervisorSpec {
11817            estrategia: RestartStrategy::OneForOne,
11818            children: vec![
11819                child("worker", "^0.1", RestartPolicy::Permanent),
11820                child("worker", "^0.2", RestartPolicy::Transient),
11821            ],
11822            ..SupervisorSpec::default()
11823        };
11824        match s.validate().unwrap_err() {
11825            SupervisorError::DuplicateChildCaixa { caixa } => {
11826                assert_eq!(
11827                    caixa, "worker",
11828                    "DuplicateChildCaixa.caixa must carry the shared \
11829                     child `:caixa` name verbatim",
11830                );
11831            }
11832            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
11833        }
11834        assert_eq!(
11835            s.children().len(),
11836            2,
11837            "the per-child validate loop's traversal input must be a \
11838             two-element slice per the accessor's projection",
11839        );
11840    }
11841
11842    // Shared helper for the M2 per-`:children` per-slot-gate ≡
11843    // `validate` equivalence pins: builds an `OneForOne`-estrategia
11844    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
11845    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
11846    // bracket all pass cleanly so the sole failing surface is the
11847    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
11848    // pins the two-altitude equivalence on the paired probe.
11849    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
11850        let s = SupervisorSpec {
11851            estrategia: RestartStrategy::OneForOne,
11852            children,
11853            ..SupervisorSpec::default()
11854        };
11855        let via_gate = s.validate_children().unwrap_err();
11856        let via_validate = s.validate().unwrap_err();
11857        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
11858        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
11859        assert_eq!(
11860            via_gate, via_validate,
11861            "per-slot gate ≡ validate() must discriminate the same \
11862             refusal shape",
11863        );
11864    }
11865
11866    #[test]
11867    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
11868        // Fail-before-pass-after equivalence pin on the M2
11869        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
11870        // convergence — sibling of the M3 mesh-slot
11871        // `validate_membros_*` / `validate_contratos_*` /
11872        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
11873        // peer per-entry axes. Sweeps four of the five refusal shapes
11874        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
11875        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
11876        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
11877        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
11878        // duplicate-`:caixa` fan-out. Companion pin
11879        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
11880        // covers `ChildVersaoInvalid` (whose parser-owned reason string
11881        // needs pattern-matching, not equality) and the clean-pass
11882        // canonical fixture; together the two pins guarantee the
11883        // per-slot gate and `validate` discriminate the same set on
11884        // every per-child-covered input.
11885        assert_validate_children_matches_gate(
11886            vec![child("", "^0.1", RestartPolicy::Permanent)],
11887            &SupervisorError::EmptyChildName,
11888        );
11889        assert_validate_children_matches_gate(
11890            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
11891            &SupervisorError::ChildCaixaInvalid {
11892                caixa: "Worker".into(),
11893                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
11894            },
11895        );
11896        assert_validate_children_matches_gate(
11897            vec![child("worker", "", RestartPolicy::Permanent)],
11898            &SupervisorError::EmptyChildVersion {
11899                caixa: "worker".into(),
11900            },
11901        );
11902        assert_validate_children_matches_gate(
11903            vec![
11904                child("worker", "^0.1", RestartPolicy::Permanent),
11905                child("worker", "^0.2", RestartPolicy::Transient),
11906            ],
11907            &SupervisorError::DuplicateChildCaixa {
11908                caixa: "worker".into(),
11909            },
11910        );
11911    }
11912
11913    #[test]
11914    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
11915        // Second half of the two-altitude equivalence pin — covers the
11916        // one refusal shape whose reason string is parser-owned
11917        // (`ChildVersaoInvalid`, whose reason comes from the shared
11918        // [`crate::version::parse_requirement`] impl and may drift) and
11919        // the clean-pass canonical fixture. Sibling pin
11920        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
11921        // covers the four equality-comparable refusal shapes.
11922        let s_bad_versao = SupervisorSpec {
11923            estrategia: RestartStrategy::OneForOne,
11924            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
11925            ..SupervisorSpec::default()
11926        };
11927        let via_gate = s_bad_versao.validate_children().unwrap_err();
11928        let via_validate = s_bad_versao.validate().unwrap_err();
11929        match (&via_gate, &via_validate) {
11930            (
11931                SupervisorError::ChildVersaoInvalid {
11932                    caixa: cg,
11933                    versao: vg,
11934                    ..
11935                },
11936                SupervisorError::ChildVersaoInvalid {
11937                    caixa: cv,
11938                    versao: vv,
11939                    ..
11940                },
11941            ) => {
11942                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
11943                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
11944                assert_eq!(cv, "worker", "validate() :caixa carrier");
11945                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
11946            }
11947            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
11948        }
11949        assert_eq!(
11950            via_gate, via_validate,
11951            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
11952        );
11953
11954        let s_ok = SupervisorSpec {
11955            estrategia: RestartStrategy::OneForOne,
11956            children: vec![
11957                child("worker-a", "^0.1", RestartPolicy::Permanent),
11958                child("worker-b", "~0.2.3", RestartPolicy::Transient),
11959                child("collector", "*", RestartPolicy::Temporary),
11960            ],
11961            ..SupervisorSpec::default()
11962        };
11963        s_ok.validate_children()
11964            .expect("per-slot gate must accept the clean-pass fixture");
11965        s_ok.validate()
11966            .expect("validate() must accept the clean-pass fixture");
11967    }
11968
11969    #[test]
11970    fn validate_children_is_self_contained_on_children_slot() {
11971        // Self-containment pin: [`SupervisorSpec::validate_children`]
11972        // resolves the per-child cascade against `&self` alone, without
11973        // depending on the peer `:estrategia`/`:max-restarts`/
11974        // `:restart-window` gates having run first — same posture the M3
11975        // peer per-slot gates carry (`validate_membros`,
11976        // `validate_contratos`, `validate_entrada`, `validate_placement`,
11977        // routing through their own oracles rather than borrowing state
11978        // threaded down from `validate`). A future consumer that reaches
11979        // the per-slot gate directly on a spec whose peer slots would
11980        // fail `validate` still surfaces the per-child refusal, not the
11981        // peer refusal.
11982        //
11983        // Construct a spec whose `:max-restarts` is `0` (which would
11984        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
11985        // the partition-dispatch) and whose `:children` carries a
11986        // `DuplicateChildCaixa` shape: the per-slot gate called directly
11987        // must surface `DuplicateChildCaixa`, proving it does not depend
11988        // on the peer `:max-restarts` gate running first.
11989        let s = SupervisorSpec {
11990            estrategia: RestartStrategy::OneForOne,
11991            max_restarts: 0,
11992            restart_window: Some(Duration::from_secs(60)),
11993            children: vec![
11994                child("worker", "^0.1", RestartPolicy::Permanent),
11995                child("worker", "^0.2", RestartPolicy::Transient),
11996            ],
11997        };
11998        assert_eq!(
11999            s.validate_children().unwrap_err(),
12000            SupervisorError::DuplicateChildCaixa {
12001                caixa: "worker".into(),
12002            },
12003            "per-slot gate must resolve per-child refusal directly against \
12004             `&self` — a dependency on the peer `:max-restarts` gate \
12005             running first would surface ZeroMaxRestarts here instead",
12006        );
12007        // The peer gate is still the surface `validate` reaches — pin
12008        // the ordering to establish that `validate_children` truly runs
12009        // last in `validate`'s dispatch, so a direct call bypasses the
12010        // peer gates on any spec whose per-child cascade would fail.
12011        assert_eq!(
12012            s.validate().unwrap_err(),
12013            SupervisorError::ZeroMaxRestarts,
12014            "validate() must surface the peer `:max-restarts` gate before \
12015             reaching the per-child cascade — this pins the dispatch \
12016             ordering the per-slot gate's self-containment complements",
12017        );
12018    }
12019
12020    #[test]
12021    fn child_spec_restart_accessor_is_const_fn() {
12022        // The [`ChildSpec::restart`] per-`:children` restart-decision-
12023        // policy `Copy`-return scalar accessor is declared
12024        // `#[must_use] pub const fn` — matching the sibling M2
12025        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
12026        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
12027        // both converted in this commit), the sibling M2
12028        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
12029        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
12030        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
12031        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
12032        // `Copy`-return `pub const fn` scalar accessors on the sibling
12033        // M3 surface. Pin the `const`-eval posture here so a future
12034        // accidental downgrade to non-`const` (an added runtime helper
12035        // reachable only from a non-`const` context, an
12036        // `Option<RestartPolicy>`-shape migration on the per-child
12037        // restart-decision axis once heterogeneous per-cluster
12038        // restart-policy overlays land that would silently drop the
12039        // `const` qualifier, a manual hand-rolled shadow) trips at
12040        // caixa-core build time rather than surfacing as a downstream
12041        // `const`-context regression far from the declaration.
12042        //
12043        // Same shape as the sibling M3
12044        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
12045        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
12046        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
12047        // accessor axis — the load-bearing witness lives in the
12048        // module-scope `const fn` wrapper `restart_via_const_fn` below:
12049        // a body that calls [`ChildSpec::restart`] under a `const fn`
12050        // signature is well-formed only when the callee is itself
12051        // `const fn`, so any future accidental downgrade of
12052        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
12053        // build time (const-eval E0015 `cannot call non-const method`),
12054        // strictly stronger than a runtime `assert!(CONST)` and
12055        // side-stepping the destructor-in-const restriction that
12056        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
12057        // items on `ChildSpec`'s `String` carriers.
12058        //
12059        // The runtime body sweeps every closed-set [`RestartPolicy`]
12060        // arm and asserts the wrapped and direct dispatches agree.
12061        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
12062            c.restart()
12063        }
12064        for restart in [
12065            RestartPolicy::Permanent,
12066            RestartPolicy::Transient,
12067            RestartPolicy::Temporary,
12068        ] {
12069            let c = ChildSpec {
12070                caixa: "worker".into(),
12071                versao: "^0.1".into(),
12072                restart,
12073            };
12074            assert_eq!(
12075                restart_via_const_fn(&c),
12076                c.restart(),
12077                "const-fn-wrapped and direct dispatch on \
12078                 ChildSpec::restart must agree for {restart:?}",
12079            );
12080            assert_eq!(
12081                c.restart(),
12082                restart,
12083                "ChildSpec::restart must return the storage-side \
12084                 RestartPolicy verbatim for {restart:?} (a violation \
12085                 means the accessor stopped being a raw field-return \
12086                 copy)",
12087            );
12088        }
12089    }
12090
12091    #[test]
12092    fn supervisor_spec_estrategia_accessor_is_const_fn() {
12093        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
12094        // sibling-restart-strategy `Copy`-return scalar accessor is
12095        // declared `#[must_use] pub const fn` — matching the sibling M2
12096        // per-`:children` [`ChildSpec::restart`] (pinned by
12097        // [`child_spec_restart_accessor_is_const_fn`] above, both
12098        // converted in this commit), the sibling M2 per-`:supervisor`
12099        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
12100        // accessor already `pub const fn`, and mirroring the peer M3
12101        // mesh-slot per-`:placement`
12102        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
12103        // `pub const fn` scalar accessor whose method-name discipline
12104        // the [`SupervisorSpec::estrategia`] method was authored to
12105        // match. Pin the `const`-eval posture here so a future
12106        // accidental downgrade to non-`const` (an added runtime helper
12107        // reachable only from a non-`const` context, an
12108        // `Option<RestartStrategy>`-shape migration once the substrate
12109        // grows per-cluster strategy overlays that would silently drop
12110        // the `const` qualifier, a manual hand-rolled shadow) trips at
12111        // caixa-core build time rather than surfacing as a downstream
12112        // `const`-context regression far from the declaration.
12113        //
12114        // Same shape as the sibling
12115        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
12116        // load-bearing witness lives in the module-scope `const fn`
12117        // wrapper `estrategia_via_const_fn` below: a body that calls
12118        // [`SupervisorSpec::estrategia`] under a `const fn` signature
12119        // is well-formed only when the callee is itself `const fn`,
12120        // side-stepping the destructor-in-const restriction that would
12121        // otherwise block a direct
12122        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
12123        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
12124        // carriers.
12125        //
12126        // The runtime body sweeps every closed-set [`RestartStrategy`]
12127        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
12128        // direct dispatches agree.
12129        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
12130            s.estrategia()
12131        }
12132        for &estrategia in RestartStrategy::ALL {
12133            let s = SupervisorSpec {
12134                estrategia,
12135                max_restarts: 5,
12136                restart_window: Some(Duration::from_secs(60)),
12137                children: Vec::new(),
12138            };
12139            assert_eq!(
12140                estrategia_via_const_fn(&s),
12141                s.estrategia(),
12142                "const-fn-wrapped and direct dispatch on \
12143                 SupervisorSpec::estrategia must agree for {estrategia:?}",
12144            );
12145            assert_eq!(
12146                s.estrategia(),
12147                estrategia,
12148                "SupervisorSpec::estrategia must return the storage-side \
12149                 RestartStrategy verbatim for {estrategia:?} (a violation \
12150                 means the accessor stopped being a raw field-return \
12151                 copy)",
12152            );
12153        }
12154    }
12155
12156    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
12157    // macro definition (see the paired doc-block above the macro
12158    // definition) — every generated `<ctor>(caixa: &str) -> Self`
12159    // constructor folds the uniform `Self::<Variant> { caixa:
12160    // caixa.to_string() }` one-field struct-literal onto one substrate
12161    // primitive. The three per-variant equivalence pins below
12162    // (fail-before-pass-after by construction — a byte-mismatched macro
12163    // arm would trip its equivalence pin first) lock each generated
12164    // constructor to its struct-literal peer under `PartialEq`, so
12165    // every wire-up in [`SupervisorSpec::validate_children`] and
12166    // [`validate_no_self_supervision`] on that variant produces a
12167    // byte-equal `SupervisorError` to the pre-lift open-coded
12168    // struct-literal. The cross-axis pin that follows (non-default
12169    // caixa name) routes the sole constructor input axis through
12170    // `.to_string()`, so the fold does not silently collapse onto a
12171    // fixed name.
12172    //
12173    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
12174    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
12175    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
12176    // `missing_entry_ctor_matches_struct_literal_wrap` /
12177    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
12178    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
12179    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
12180    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
12181    // on the six sibling ctor families the recent trajectory closed
12182    // on the peer `LayoutError` / `AplicacaoError` envelopes.
12183
12184    #[test]
12185    fn empty_child_version_ctor_matches_struct_literal_wrap() {
12186        assert_eq!(
12187            SupervisorError::empty_child_version("worker"),
12188            SupervisorError::EmptyChildVersion {
12189                caixa: "worker".to_string(),
12190            },
12191            "generated empty_child_version ctor must produce byte-equal \
12192             SupervisorError to the open-coded struct-literal wrap on the \
12193             same &str fixture",
12194        );
12195    }
12196
12197    #[test]
12198    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
12199        assert_eq!(
12200            SupervisorError::duplicate_child_caixa("worker"),
12201            SupervisorError::DuplicateChildCaixa {
12202                caixa: "worker".to_string(),
12203            },
12204            "generated duplicate_child_caixa ctor must produce byte-equal \
12205             SupervisorError to the open-coded struct-literal wrap on the \
12206             same &str fixture",
12207        );
12208    }
12209
12210    #[test]
12211    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
12212        assert_eq!(
12213            SupervisorError::child_supervises_self("orquestra"),
12214            SupervisorError::ChildSupervisesSelf {
12215                caixa: "orquestra".to_string(),
12216            },
12217            "generated child_supervises_self ctor must produce byte-equal \
12218             SupervisorError to the open-coded struct-literal wrap on the \
12219             same &str fixture",
12220        );
12221    }
12222
12223    // Per-variant equivalence pins for the two lifted
12224    // [`SupervisorError::child_caixa_invalid`] /
12225    // [`SupervisorError::child_versao_invalid`] inherent constructors
12226    // (fail-before-pass-after by construction — a byte-mismatched ctor body
12227    // would trip its equivalence pin first). Each pins the ctor output to
12228    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
12229    // in [`SupervisorSpec::validate_children`] on the two variants
12230    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
12231    // struct-literal on the same scalar fixtures. Peers of the sibling
12232    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
12233    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
12234    // the peer `AplicacaoError` envelope's
12235    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
12236
12237    #[test]
12238    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
12239        let caixa = "Worker";
12240        let reason = "sample reason text";
12241        assert_eq!(
12242            SupervisorError::child_caixa_invalid(caixa, reason),
12243            SupervisorError::ChildCaixaInvalid {
12244                caixa: caixa.to_string(),
12245                reason: reason.to_string(),
12246            },
12247            "lifted child_caixa_invalid ctor must produce byte-equal \
12248             SupervisorError to the open-coded struct-literal wrap on the \
12249             same (&str, reason) fixture",
12250        );
12251    }
12252
12253    #[test]
12254    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
12255        let caixa = "worker";
12256        let versao = "not-a-req";
12257        let reason = "sample reason text";
12258        assert_eq!(
12259            SupervisorError::child_versao_invalid(caixa, versao, reason),
12260            SupervisorError::ChildVersaoInvalid {
12261                caixa: caixa.to_string(),
12262                versao: versao.to_string(),
12263                reason: reason.to_string(),
12264            },
12265            "lifted child_versao_invalid ctor must produce byte-equal \
12266             SupervisorError to the open-coded struct-literal wrap on the \
12267             same (&str, &str, reason) fixture",
12268        );
12269    }
12270
12271    #[test]
12272    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
12273        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
12274        // against a `&str`-literal vs. `format!(…)` reason input to pin
12275        // both constructors accept the `impl Into<String>` bound
12276        // uniformly, so neither wire-up site drifts under a per-arm
12277        // wrapper transformation on the caller-side `reason` axis. Peer
12278        // of the sibling
12279        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
12280        // sweep on the peer `AplicacaoError` envelope.
12281        let via_literal = "literal reason text";
12282        let via_format = format!("{} reason text", "literal");
12283        assert_eq!(
12284            SupervisorError::child_caixa_invalid("Worker", via_literal),
12285            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
12286        );
12287        assert_eq!(
12288            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
12289            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
12290        );
12291    }
12292
12293    #[test]
12294    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
12295        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
12296        // &str`) through a non-default fixture name against every
12297        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
12298        // so any wrapper-side lowercase / trim / truncate / re-order on
12299        // the `caixa.to_string()` sole-field construction surfaces
12300        // here rather than at a downstream diagnostic-shape mismatch.
12301        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
12302        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
12303        // through_to_string` / `contrato_target_ctors_route_edge_
12304        // triple_through_verbatim` / `contrato_empty_pair_ctors_
12305        // route_edge_pair_through_verbatim` cross-axis routing pins on
12306        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
12307        // here onto the `SupervisorError` `{ caixa: String }` envelope
12308        // so every substrate-primitive ctor family in caixa-core
12309        // guarantees the sole-field construction routes the caller's
12310        // `&str` through `.to_string()` verbatim.
12311        let name = "cache-v2";
12312        assert_eq!(
12313            SupervisorError::empty_child_version(name),
12314            SupervisorError::EmptyChildVersion {
12315                caixa: name.to_string(),
12316            },
12317        );
12318        assert_eq!(
12319            SupervisorError::duplicate_child_caixa(name),
12320            SupervisorError::DuplicateChildCaixa {
12321                caixa: name.to_string(),
12322            },
12323        );
12324        assert_eq!(
12325            SupervisorError::child_supervises_self(name),
12326            SupervisorError::ChildSupervisesSelf {
12327                caixa: name.to_string(),
12328            },
12329        );
12330    }
12331
12332    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
12333    //
12334    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
12335    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
12336    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
12337    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
12338    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
12339    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
12340    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
12341    // / silent constant-substitution on any one variant surfaces here rather
12342    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
12343    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
12344    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
12345    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
12346    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
12347    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
12348    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
12349    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
12350    #[test]
12351    fn no_children_ctor_matches_struct_literal_wrap() {
12352        let estrategia = RestartStrategy::OneForAll;
12353        assert_eq!(
12354            SupervisorError::no_children(estrategia),
12355            SupervisorError::NoChildren { estrategia },
12356            "generated no_children ctor must produce byte-equal \
12357             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
12358             on the same `Copy`-`RestartStrategy` fixture",
12359        );
12360    }
12361
12362    #[test]
12363    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
12364        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
12365        assert_eq!(
12366            SupervisorError::max_restarts_exceeds_cap(max_restarts),
12367            SupervisorError::MaxRestartsExceedsCap { max_restarts },
12368            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
12369             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
12370             struct-literal wrap on the same `Copy`-`u32` fixture",
12371        );
12372    }
12373
12374    #[test]
12375    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
12376        let window = Duration::from_micros(1_500);
12377        assert_eq!(
12378            SupervisorError::restart_window_not_canonical(window),
12379            SupervisorError::RestartWindowNotCanonical { window },
12380            "generated restart_window_not_canonical ctor must produce \
12381             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
12382             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
12383        );
12384    }
12385
12386    #[test]
12387    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
12388        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
12389        assert_eq!(
12390            SupervisorError::restart_window_exceeds_cap(window),
12391            SupervisorError::RestartWindowExceedsCap { window },
12392            "generated restart_window_exceeds_cap ctor must produce \
12393             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
12394             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
12395        );
12396    }
12397
12398    #[test]
12399    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
12400        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
12401        // constructor input axis through a non-default `Copy` fixture against
12402        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
12403        // side silent `.into()` / silent constant-substitution / silent field
12404        // re-name away from the canonical `estrategia | max_restarts | window`
12405        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
12406        // axis silently rerouted through some other `Copy` coercion, surfaces
12407        // here rather than at a downstream per-`:supervisor` diagnostic-shape
12408        // drift. Peer of the sibling
12409        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
12410        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
12411        // envelope's per-`:politicas` per-axis ctor family, extended here onto
12412        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
12413        // variant family folded onto a substrate primitive.
12414        //
12415        // Fixtures picked out of each variant's accept-set boundary rather
12416        // than the default value so a silent constant-substitution to a per-
12417        // variant sentinel surfaces here on the structural-equality assertion.
12418        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
12419        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
12420        // isn't the `SimpleOneForOne` arm the sibling
12421        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
12422        // `max_restarts` fixture picks an above-cap magnitude the cap arm
12423        // rejects; the two `Duration` fixtures pick the sub-millisecond and
12424        // above-cap ends of the `:restart-window` canonical-form + cap
12425        // bracket respectively.
12426        let estrategia = RestartStrategy::RestForOne;
12427        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
12428        let sub_ms = Duration::from_micros(1_500);
12429        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
12430        assert_eq!(
12431            SupervisorError::no_children(estrategia),
12432            SupervisorError::NoChildren { estrategia },
12433        );
12434        assert_eq!(
12435            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
12436            SupervisorError::MaxRestartsExceedsCap {
12437                max_restarts: above_cap_restarts,
12438            },
12439        );
12440        assert_eq!(
12441            SupervisorError::restart_window_not_canonical(sub_ms),
12442            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
12443        );
12444        assert_eq!(
12445            SupervisorError::restart_window_exceeds_cap(above_hour),
12446            SupervisorError::RestartWindowExceedsCap { window: above_hour },
12447        );
12448    }
12449
12450    #[test]
12451    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
12452        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
12453        // generated ctor `const fn` so a caller can pin a `SupervisorError`
12454        // at compile time — the same zero-runtime-work property the pre-lift
12455        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
12456        // its `Copy`-pass-through construction path (no `.to_string()` /
12457        // `.into()` allocation, no branching). If any future edit silently
12458        // drops the `const` qualifier from the macro body the per-arm `const`
12459        // bindings below fail to compile, which surfaces the regression at
12460        // the substrate-primitive definition rather than at some downstream
12461        // consumer that had come to rely on the `const`-constructibility.
12462        // Peer of the sibling
12463        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
12464        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
12465        // per-`:politicas` per-axis ctor family.
12466        const NO_CHILDREN: SupervisorError =
12467            SupervisorError::no_children(RestartStrategy::OneForAll);
12468        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
12469        const WINDOW_NC: SupervisorError =
12470            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
12471        const WINDOW_CAP: SupervisorError =
12472            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
12473        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
12474        assert!(matches!(
12475            MAX_RESTARTS_CAP,
12476            SupervisorError::MaxRestartsExceedsCap { .. }
12477        ));
12478        assert!(matches!(
12479            WINDOW_NC,
12480            SupervisorError::RestartWindowNotCanonical { .. }
12481        ));
12482        assert!(matches!(
12483            WINDOW_CAP,
12484            SupervisorError::RestartWindowExceedsCap { .. }
12485        ));
12486    }
12487}