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/// Per-child restart policy.
791///
792/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
793#[derive(
794    Serialize,
795    Deserialize,
796    Debug,
797    Clone,
798    Copy,
799    PartialEq,
800    Eq,
801    Hash,
802    gen_platform::TypedDispatcher,
803    gen_platform::Discriminant,
804    gen_platform::IsVariant,
805    gen_platform::FromStrKind,
806)]
807pub enum RestartPolicy {
808    /// Always restart the child, regardless of how it died. Used for
809    /// long-running services that must always be up.
810    Permanent,
811    /// Never restart. Used for one-shot work whose completion is
812    /// itself the success signal (`oneShot` triggers map here).
813    Temporary,
814    /// Restart only when the child died *abnormally* (non-zero exit
815    /// or unhandled exception). A clean exit completes the child.
816    Transient,
817}
818
819impl Default for RestartPolicy {
820    fn default() -> Self {
821        // Route the [`Default for RestartPolicy`] impl's return arm through
822        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
823        // `pub const` rather than a raw `Self::Permanent` arm — one source
824        // of truth for the Erlang/OTP-canonical `permanent` worker-child
825        // default across the two production consumers that currently
826        // dispatch on it (this impl at the [`RestartPolicy::default`] call
827        // and the serde-side `#[serde(default)]` on
828        // [`ChildSpec::restart`] that resolves an author-omitted
829        // `:children :restart` slot through `RestartPolicy::default()`).
830        // Peer of the sibling per-`:supervisor` axis
831        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
832        // route (95ffacc) — the two impls now share one substrate-primitive
833        // lift discipline, so any future coherent rebrand of the OTP-shape
834        // supervisor+child default set migrates through typed constants in
835        // lockstep instead of splitting a lifted supervisor half against
836        // an open-coded child half. Pinned by
837        // `restart_policy_default_routes_through_lifted_default` +
838        // `child_spec_serde_default_restart_routes_through_lifted_default`
839        // in the tests module.
840        SUPERVISOR_CHILD_RESTART_DEFAULT
841    }
842}
843
844impl RestartPolicy {
845    /// Exhaustive iteration surface for every consumer that walks the
846    /// closed three-arm [`RestartPolicy`] discriminator set (the future
847    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
848    /// per-child admission-webhook rejection body naming the accepted-
849    /// `:restart` list, a future `feira supervisor --restart …` CLI
850    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
851    /// over the slice, the future `feira app graph` per-child restart
852    /// column, any future round-trip fuzz harness that sweeps every
853    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
854    /// theory
855    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
856    /// might reach for once the three canonical OTP restart policies
857    /// stop covering the substrate's discovered load-shape) extends
858    /// this slice as one edit and every consumer picks up the new entry
859    /// by construction; the compiler-checked exhaustiveness on the
860    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
861    /// is the build-time guarantee that no arm forgets to grow.
862    ///
863    /// Peer of the sibling closed-set typed enums'
864    /// [`RestartStrategy::ALL`] (4eec29c) /
865    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
866    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
867    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
868    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
869    /// surfaces — the sixth (and the third and final M2 OTP-shape)
870    /// closed-set typed enum on the caixa surface to converge onto the
871    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
872    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
873    /// sibling-restart-strategy axis; this closes the per-child
874    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
875    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
876
877    /// Canonical PascalCase discriminator scalar this variant serializes
878    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
879    /// arms return the paired
880    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
881    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
882    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
883    /// constants so every substrate consumer that dispatches on the
884    /// per-child restart-decision policy (the future wasm-operator's
885    /// per-child post-exit restart-decision branch, the future M4
886    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
887    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
888    /// reconciliation scheduler's per-child-policy fan-out) reads the
889    /// same byte-string the `Serialize` derive emits — the pin test in
890    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
891    /// asserts the two paths agree, peer of the M2
892    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
893    /// sibling-restart-strategy axis and the M3
894    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
895    /// per-Aplicacao distribution-strategy axis — the third of three
896    /// OTP-shaped closed-enum discriminator axes on the caixa typed
897    /// surface to converge onto the same three-path-convergence
898    /// (`Serialize` derive → `as_str` helper → lifted constant)
899    /// drift-detection posture.
900    #[must_use]
901    pub const fn as_str(self) -> &'static str {
902        match self {
903            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
904            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
905            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
906        }
907    }
908
909    /// Substrate-canonical reverse projection on the `:children :restart`
910    /// closed-set axis — parses the `PascalCase` discriminator scalar
911    /// back to the typed variant, or `None` when `s` is outside the
912    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
913    /// the same lifted
914    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
915    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
916    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
917    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
918    /// of the round-trip migrate through one caixa-core edit on any
919    /// future arm addition.
920    ///
921    /// Prior to this lift the substrate carried only the forward
922    /// `Self → &str` projection on the OTP per-child restart-policy
923    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
924    /// impl routed through it, the `Serialize` derive that emits the
925    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
926    /// plus the kebab-case dispatcher-catalog identity via
927    /// [`Self::discriminant`] — every non-serde consumer that wanted to
928    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
929    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
930    /// "Transient" => …, _ => … }` cascade that expressed no
931    /// compile-time link back to the typed variant's canonical lifted
932    /// constant. A future variant rename or per-arm serde-attribute
933    /// drift would silently split the wire byte-string one non-serde
934    /// consumer parsed from the one the emitter wrote, with the failure
935    /// surfacing at the operator's reconcile posture (a `:temporary`
936    /// `oneShot` child being restarted on clean exit, treating the
937    /// successful-completion signal as failure and re-running the
938    /// completion-terminal one-shot indefinitely; a `:transient` child
939    /// that clean-exited being restarted, masking the clean-completion
940    /// contract) far from the rebrand commit and with no field naming
941    /// the drift.
942    ///
943    /// Distinct axis from the [`std::str::FromStr`] impl the
944    /// [`gen_platform::FromStrKind`] derive already installs on this
945    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
946    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
947    /// `"transient"` — the inverse of [`Self::discriminant`]), while
948    /// this method inverts the `PascalCase` wire byte-string
949    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
950    /// catalog identity live in kebab-case (where every peer catalog
951    /// identifier already lives) without forcing a wire-format rename
952    /// on the tatara-lisp author surface (`:restart Permanent`,
953    /// `PascalCase`) — the same two-axis distinction the sibling
954    /// [`RestartStrategy::from_wire`] (4eec29c) /
955    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
956    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
957    /// carry on their peer closed-set typed-enum wire round-trips.
958    ///
959    /// Same closed-set-reverse-projection discipline the sibling
960    /// [`RestartStrategy::from_wire`] (4eec29c) /
961    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
962    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
963    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
964    /// carry on the peer wire-side `str → Self` axes — extended onto
965    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
966    /// sixth substrate-side closed-set typed enum (and the third and
967    /// final OTP-shape closed-enum discriminator axis) to converge on
968    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
969    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
970    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
971    /// derive already installs on the sibling kebab-case axis. Returns
972    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
973    /// shapes: the caller picks the diagnostic form appropriate for
974    /// its use site.
975    #[must_use]
976    pub fn from_wire(s: &str) -> Option<Self> {
977        match s {
978            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
979            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
980            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
981            _ => None,
982        }
983    }
984}
985
986/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
987/// pretty-printed byte-string every consumer that formats the policy as
988/// user-facing text lands on (the future wasm-operator's per-child
989/// post-exit restart-decision diagnostic line, the future `feira app
990/// graph` per-child restart column, the future M4
991/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
992/// admission-webhook rejection body) reaches for the same lifted
993/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
994/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
995/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
996/// wire-format `Serialize` derive already emits under
997/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
998/// [`RestartPolicy::as_str`] helper already returns.
999///
1000/// Pre-convergence the two paths structurally disagreed — the
1001/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1002/// route (now retired here) sent [`std::fmt::Display`] through the
1003/// gen-platform discriminant catalog string, which arrives kebab-case as
1004/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1005/// (whose variant names each collapse to their own lowercase form under
1006/// the kebab-case transform), while the wire format ran as `PascalCase`
1007/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1008/// serde derive. Every consumer that formatted the policy for a
1009/// diagnostic line, a graph column, or a rejection body under
1010/// `format!("{v}")` therefore landed under a different byte-string than
1011/// the wire format the operator's per-child-policy dispatch keyed off —
1012/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1013/// diagnostic quoting `"permanent"` while the wire scalar the operator
1014/// probed was `"Permanent"`) surfaced as a confused correlate at
1015/// operator-log time far from the two-declaration site.
1016///
1017/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1018/// path: every `format!("{v}")` call reaches the same lifted
1019/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1020/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1021/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1022/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1023/// byte-string per variant. A future variant rename or
1024/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1025/// exactly one place, structurally.
1026///
1027/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1028/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1029/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1030/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1031/// registration keys the catalog off the same kebab identity. The two
1032/// naming worlds now live on separate typed methods (`Display` /
1033/// `as_str` for the wire byte-string, `discriminant` for the catalog
1034/// identity) rather than sharing one `Display` route that structurally
1035/// disagrees with the wire format.
1036///
1037/// Pin tests
1038/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1039/// and
1040/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1041/// assert the three paths agree byte-for-byte on every variant, so a
1042/// future variant rename or per-arm serde attribute drift is a build
1043/// error visible at caixa-core test time, not a silent per-consumer
1044/// dispatch miss at apply / reconcile time.
1045///
1046/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1047/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1048/// and the sibling [`RestartStrategy`] `Display` impl on the
1049/// per-supervisor sibling-restart-strategy axis — same three-path-
1050/// convergence discipline, extended to close the third and final of
1051/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1052/// surface.
1053impl std::fmt::Display for RestartPolicy {
1054    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1055        f.write_str(self.as_str())
1056    }
1057}
1058
1059/// Substrate-canonical [`AsRef<str>`] projection on the M2
1060/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1061/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1062/// scalar accessor the paired [`std::fmt::Display`] impl and the
1063/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1064/// future consumer that binds a [`RestartPolicy`] through the
1065/// standard-library `impl AsRef<str>` bound (a future
1066/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1067/// composes the emitted `PascalCase` wire scalar into a
1068/// [`std::process::Command::arg`] shell-out of the future
1069/// wasm-operator's per-child admission gate, a per-child structured-
1070/// log recorder on the future `caixa-operator`'s hierarchical
1071/// reconciliation surface that accepts `impl AsRef<str>` at the
1072/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1073/// lookup keyed on the restart-policy wire byte through
1074/// `map.get::<str>(policy.as_ref())` on a future per-policy
1075/// dispatch table) reaches the paired
1076/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1077/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1078/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1079/// lifted-const through one substrate-primitive dispatch rather
1080/// than an open-coded `.as_str()` projection at every wire-up.
1081///
1082/// Peer of the sibling [`std::fmt::Display`] impl on the same
1083/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1084/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1085/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1086/// byte-string per instance by construction. A future variant rename
1087/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1088/// enum reaches every one of the three paths (plus the wire-format
1089/// `Serialize` derive that already routes through the same lifted
1090/// const) through exactly one caixa-core edit.
1091///
1092/// Same "route the trait impl through the substrate-primitive
1093/// accessor" discipline the sibling [`crate::CaixaVersion`]
1094/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1095/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1096/// the axis onto the paired per-child-restart-decision-policy
1097/// sibling on the same M2 `:supervisor` slot (the second M2
1098/// OTP-shape closed-set typed enum to converge onto the standard-
1099/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1100/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1101/// primitive so a caller who has one has both; before this lift,
1102/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1103/// [`AsRef<str>`] impl the convention names.
1104///
1105/// Pinned load-bearing by
1106/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1107/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1108/// three-arm closed set) and
1109/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1110/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1111/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1112/// arm) — any future silent detour that routes the impl through a
1113/// divergent projection (a per-arm inline `match self { … }`
1114/// re-inlining that opens a compile-time link to the un-lifted
1115/// arm-literal, a swap onto the kebab-case
1116/// [`gen_platform::Discriminant`] catalog identity that would
1117/// collide the wire axis with the dispatcher-catalog axis) trips at
1118/// caixa-core test time under `assert_eq!` rather than at a
1119/// downstream `impl AsRef<str>`-bound consumer's silent split.
1120impl AsRef<str> for RestartPolicy {
1121    fn as_ref(&self) -> &str {
1122        self.as_str()
1123    }
1124}
1125
1126/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1127/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1128/// byte-for-byte through the paired substrate-primitive
1129/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1130/// consumer that binds a `PascalCase` `:children :restart` wire
1131/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1132/// axis (a future [`caixa-feira`] `feira supervisor --restart
1133/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1134/// `let restart: RestartPolicy = s.try_into()?`, a future
1135/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1136/// `spec.children[*].restart: String` field through
1137/// `RestartPolicy::try_from(&s)?`, a generic
1138/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1139/// set typed enums) reaches the same three-arm accept-set the sibling
1140/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1141/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1142/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1143/// … }` cascade whose arm-set has no compile-time link back to the
1144/// substrate primitive.
1145///
1146/// Complements the pre-existing forward-projection triple
1147/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1148/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1149/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1150/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1151/// caller who can project *out to* a `&str` can also project *in from*
1152/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1153/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1154/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1155/// trigger under a `FromStr` impl and to avoid colliding with the
1156/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1157/// already installs on the paired *kebab-case dispatcher-catalog* axis
1158/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1159/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1160/// idiomatic reverse axis on the *`PascalCase` wire* half without
1161/// disturbing either the method-named `from_wire` shape every sibling
1162/// closed-set typed enum on the substrate already carries or the
1163/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1164/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1165///
1166/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1167/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1168/// caller picks the diagnostic form appropriate for its use site (a
1169/// future `feira supervisor --restart` arg-parse composes its own
1170/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1171/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1172/// wraps the `Err(())` outcome with the accepted-set enumeration for
1173/// operator diagnostics, a `Result::map_err` at the call site lifts the
1174/// unit-error to a per-verb error type). Same shape the peer
1175/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1176/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1177/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1178/// their peer closed-set typed enums' reverse projections.
1179///
1180/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1181/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1182/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1183/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1184/// might reach for once the three canonical OTP restart policies stop
1185/// covering the substrate's discovered load-shape) grows the trait-
1186/// idiomatic axis by construction — one caixa-core edit on
1187/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1188/// projection every existing consumer keys off and the trait-idiomatic
1189/// reverse projection this impl exposes, without a coordinated rewrite
1190/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1191///
1192/// Extends the substrate-wide closed-set-enum reverse-projection family
1193/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1194/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1195/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1196/// closed-enum discriminator axis on the caixa surface — the paired
1197/// per-child `:children :restart` closed set the future wasm-operator's
1198/// hierarchical reconciliation scheduler's per-child post-exit
1199/// restart-decision branch keys off end-to-end.
1200///
1201/// Pinned load-bearing by
1202/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1203/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1204/// three-arm accept-set),
1205/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1206/// (rejection witness against silent accept-set widening), and
1207/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1208/// (cross-axis partition pin locking the trait and method-named
1209/// projections onto one accept-set).
1210impl TryFrom<&str> for RestartPolicy {
1211    type Error = ();
1212
1213    fn try_from(s: &str) -> Result<Self, Self::Error> {
1214        Self::from_wire(s).ok_or(())
1215    }
1216}
1217
1218/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1219/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1220/// byte-for-byte through the paired substrate-primitive
1221/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1222/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1223/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1224/// &str` with `'static` lifetime, so the trait's return-type promise is
1225/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1226/// literal.
1227///
1228/// Every future consumer that specifically needs `&'static str` lifetime
1229/// bytes on the per-child restart-decision axis (a
1230/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1231/// arm's typing demands `&'static str`, a
1232/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1233/// on the future M4 admission-webhook rejection body where the
1234/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1235/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1236/// or error formatter that requires the `'static` bound) reaches the same
1237/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1238/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1239/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1240/// primitive dispatch rather than an open-coded per-arm literal cascade
1241/// whose arm-set has no compile-time link back to the substrate primitive.
1242///
1243/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1244/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1245/// the second (and second-of-two-in-M2) closed-set typed enum on the
1246/// caixa surface to converge onto the paired trait-idiomatic forward-
1247/// projection axis. With this lift the paired per-child
1248/// `:children :restart` closed-set typed enum carries the full sibling
1249/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1250/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1251/// lift) plus the round-trip witness through both the trait-idiomatic
1252/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1253/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1254/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1255/// (an OTP-`intrinsic` fourth arm the theory
1256/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1257/// might reach for once the three canonical OTP restart policies stop
1258/// covering the substrate's discovered load-shape) grows the trait-
1259/// idiomatic forward axis by construction: one caixa-core edit on
1260/// [`RestartPolicy::as_str`] extends every one of the five sibling
1261/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1262/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1263/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1264/// bytes) without a coordinated rewrite across every future
1265/// `Into<&'static str>`-bound consumer's arm-set.
1266///
1267/// Pinned load-bearing by
1268/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1269/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1270/// three-arm emit-set, plus a `const`-context materialization witness for
1271/// the `&'static str` lifetime promise) and
1272/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1273/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1274/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1275/// round-trip witness through the paired trait-idiomatic reverse-
1276/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1277/// `policy.into::<&'static str>()` output re-parses back through
1278/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1279/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1280impl From<RestartPolicy> for &'static str {
1281    fn from(policy: RestartPolicy) -> &'static str {
1282        policy.as_str()
1283    }
1284}
1285
1286/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
1287/// *borrowed* input onto the `&'static str` axis — the borrowed-input
1288/// companion to the paired owned-input [`From<RestartPolicy> for
1289/// &'static str`] impl immediately above. Routes byte-for-byte through
1290/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
1291/// fn` accessor so every consumer that binds a `&RestartPolicy`
1292/// through the standard-library `.into()` / [`From<&Self> for &'static
1293/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
1294/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
1295/// whose iterator over `&'static [RestartPolicy]` yields
1296/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
1297/// [`From<RestartPolicy>`] axis alone forces every call site through
1298/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
1299/// rather than the direct trait-idiomatic projection; a future generic
1300/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
1301/// that walks the `iter().map(Into::into)` shape verbatim across every
1302/// substrate-wide closed-set typed enum; the future wasm-operator's
1303/// per-child post-exit restart-decision diagnostic line that composes
1304/// the accepted-set enumeration from an iterated
1305/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1306/// per-arm `match p { … }` cascade; a future
1307/// `HashMap::<&'static str, RestartPolicy>::from_iter(
1308///     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
1309/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
1310/// cannot compose without this borrowed-input axis in place) reaches
1311/// the same three-arm lifted
1312/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1313/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1314/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1315/// paired owned-input [`From<RestartPolicy> for &'static str`], the
1316/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
1317/// [`RestartPolicy::as_str`] surfaces already return.
1318///
1319/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
1320/// forward-projection family opened on [`crate::dep::DepList`]
1321/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
1322/// [`crate::CaixaDialeto`] (807b0b5), and the paired
1323/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
1324/// (e941836). Rust's `From` trait does not auto-derive the
1325/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
1326/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
1327/// exist in `core`), so every closed-set typed enum that carries the
1328/// owned-input axis but not the borrowed-input axis forces every
1329/// borrowed-input call site through a `.copied()` /
1330/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
1331/// type bounds have no compile-time link to the substrate primitive.
1332/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
1333/// OTP-shape peer to converge onto this campaign — sibling of the
1334/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
1335/// with this lift both closed-set typed enums on the M2 `:supervisor`
1336/// slot now carry the full sibling quintet ([`std::fmt::Display`],
1337/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
1338/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
1339/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
1340/// forward-projection axis on the M2 OTP-shape slot as a unit.
1341///
1342/// Same three-path convergence discipline as the paired owned-input
1343/// impl (this borrowed-input axis, the paired owned-input
1344/// [`From<RestartPolicy> for &'static str`], and
1345/// [`RestartPolicy::as_str`] all route through the same lifted
1346/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
1347/// variant rename or per-arm serde-attribute drift reaches every one
1348/// of the six sibling forward-projection paths
1349/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1350/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
1351/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
1352/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
1353/// edit.
1354///
1355/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
1356/// parse share the same `PascalCase` vocabulary by construction, so
1357/// the borrowed-input forward axis and the reverse axis compose
1358/// directly — the round-trip witness pin below locks this direct
1359/// composition without the intermediate wire-vocab hop the peer
1360/// [`crate::CaixaKind`] axis pair requires.
1361///
1362/// Pinned load-bearing by
1363/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
1364/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1365/// three-arm emit-set via a borrowed input, plus a `const`-context
1366/// materialization witness for the `&'static str` lifetime promise,
1367/// plus a blanket `.into()` shape) and
1368/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
1369/// (cross-axis partition pin against the paired owned-input
1370/// [`From<RestartPolicy> for &'static str`] impl, plus a
1371/// `.iter().map(Into::into)` pipe witness over
1372/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1373/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
1374/// Self` round-trip without the wire-vocab intermediate the peer
1375/// [`crate::CaixaKind`] axis pair requires).
1376impl From<&RestartPolicy> for &'static str {
1377    fn from(policy: &RestartPolicy) -> &'static str {
1378        policy.as_str()
1379    }
1380}
1381
1382/// Trait-idiomatic *owned-`String`* forward projection on the second
1383/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
1384/// owned-heap-string companion to the paired `&'static str`-returning
1385/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
1386/// for &'static str`] impls immediately above. Routes byte-for-byte
1387/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
1388/// const fn` accessor (via [`str::to_owned`]) so every consumer that
1389/// binds a [`RestartPolicy`] through the standard-library `.into()` /
1390/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
1391/// future `serde_json::Value::String(policy.into())` structured-payload
1392/// composer where the `Value::String` arm typing demands an owned
1393/// [`String`] and the sibling [`&'static str`]-returning axis forces
1394/// an explicit `.to_owned()` / `String::from` restatement at every
1395/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
1396/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
1397/// lookup where the map's key type is owned [`String`] rather than
1398/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
1399/// composer on the future M4 admission-webhook rejection body's
1400/// owned-arm, the future wasm-operator's per-child post-exit
1401/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
1402/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
1403/// — reaches the same three-arm lifted
1404/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1405/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1406/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1407/// paired [`std::fmt::Display`], [`AsRef<str>`],
1408/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
1409/// forward-projection impls already return.
1410///
1411/// Extends the trait-idiomatic *owned-`String`* forward-projection
1412/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
1413/// the caixa surface — mirror of the first-mover
1414/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
1415/// axis on the sibling supervisor-level strategy enum. Rust's standard
1416/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
1417/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
1418/// every closed-set typed enum that carries the paired `AsRef<str>` /
1419/// `Display` / `From<Self> for &'static str` triple but not the
1420/// owned-[`String`] axis forces every owned-string call site through a
1421/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
1422/// detour whose type bounds have no compile-time link to the
1423/// substrate primitive.
1424///
1425/// Deliberately routes through the human-readable
1426/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1427/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1428/// the diagnostic byte-string share the same vocabulary by
1429/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1430/// two axes diverge), so the owned-[`String`] projection lands
1431/// byte-identically on both the wire vocabulary the paired
1432/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
1433/// [`RestartPolicy::as_str`] helper returns, and — because the paired
1434/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
1435/// axis parses the same `PascalCase` vocabulary — the direct two-way
1436/// `Self → String → Self` round-trip composes without the wire-vocab
1437/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
1438/// axis pair requires.
1439///
1440/// Pinned load-bearing by
1441/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
1442/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1443/// three-arm emit-set, plus a blanket `.into::<String>()` shape
1444/// witness) and
1445/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
1446/// (cross-axis partition pin against the paired owned-input
1447/// [`From<RestartPolicy> for &'static str`] impl and the sibling
1448/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
1449/// plus a `.iter().copied().map(String::from)` pipe witness over
1450/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1451/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
1452/// borrow that closes the two-way `Self → String → Self` round-trip
1453/// on the trait-idiomatic owned-[`String`] forward + reverse axis
1454/// pair).
1455impl From<RestartPolicy> for String {
1456    fn from(policy: RestartPolicy) -> String {
1457        policy.as_str().to_owned()
1458    }
1459}
1460
1461// Fleet-wide dispatcher-catalog registrations for caixa's OTP
1462// supervisor surface — two more typed shadows over Erlang/OTP
1463// primitives the substrate now mechanically tracks (see
1464// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
1465// theory/TYPED-ABSORPTION.md for the absorption arc).
1466gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
1467gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
1468
1469/// One child entry in the supervisor's `:children` list.
1470///
1471/// Every child references another caixa by `:caixa <nome>` + version
1472/// constraint. The supervisor materializes one ComputeUnit per entry.
1473#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1474#[serde(rename_all = "camelCase")]
1475pub struct ChildSpec {
1476    /// The child caixa's `:nome`. Must resolve via the same dependency
1477    /// resolution path as `:deps` (caixa-resolver).
1478    pub caixa: String,
1479
1480    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
1481    /// [`crate::dep::Dep::versao`].
1482    pub versao: String,
1483
1484    /// Restart policy — an author-omitted slot degrades onto the
1485    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
1486    /// (`permanent`, the Erlang/OTP worker-child default) through the
1487    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
1488    /// to.
1489    #[serde(default)]
1490    pub restart: RestartPolicy,
1491}
1492
1493impl ChildSpec {
1494    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
1495    /// accessor every consumer that reads the OTP-shape supervised
1496    /// child's identity keys off — returns the author-declared
1497    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
1498    /// from the typed slot's own [`String`] storage.
1499    ///
1500    /// The `:children :caixa` slot carries the DNS-1123 label — the
1501    /// child caixa's `:nome` — that every emitted cluster artifact
1502    /// derives its `metadata.name` from verbatim: the rendered
1503    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
1504    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
1505    /// identity, and the per-child K8s Service `metadata.name` the
1506    /// future wasm-operator (M3) provisions for inter-child supervision-
1507    /// tree wiring. Every downstream consumer that fans on the child's
1508    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
1509    /// per-child DNS-1123 gate at
1510    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
1511    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
1512    /// [`validate_no_self_supervision`] cross-slot equality check
1513    /// against the parent's `:nome`, every `SupervisorError` variant
1514    /// carrying the offending child caixa verbatim for `feira lint`
1515    /// rendering, the future wasm-operator's hierarchical reconciliation
1516    /// scheduler's per-child ComputeUnit-name projection, the future M4
1517    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1518    /// admission webhook).
1519    ///
1520    /// Prior to this lift the `.caixa` byte-string was accessed inline
1521    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
1522    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
1523    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
1524    /// carriers' `child.caixa.clone()`, the dedup key's
1525    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
1526    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
1527    /// field-accesses that expressed no compile-time link back to the
1528    /// typed slot. A future extension of the `:children :caixa` axis to
1529    /// a richer author surface (a per-cluster alias table the operator
1530    /// pins through a future `:placement`-scoped slot on the supervisor
1531    /// tree, a namespace-qualified rewrite the M4 CR materializer
1532    /// applies per-CR, a per-child overlay from the future `:children
1533    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1534    /// acknowledges) would have had to be threaded through every
1535    /// open-coded copy in lockstep or one consumer would silently
1536    /// disagree with the peers on which caixa a given child resolves to
1537    /// — a child-set lookup that treated the name as `"cart-worker"`
1538    /// while the peer duplicate-detector treated it as
1539    /// `"tenant-a/cart-worker"` would silently split the
1540    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
1541    /// self-supervision detector's parent-equality check, a two-consumer
1542    /// split at the validator far from the source `caixa.lisp` with no
1543    /// field naming the identity-drift root cause. Lifting the resolution
1544    /// rule to a typed method on the substrate primitive means every
1545    /// downstream consumer of the Supervisor's per-`:children` identity
1546    /// surface reaches for exactly one typed dispatch — the resolver's
1547    /// accept-set migrates as a unit on any future axis addition.
1548    ///
1549    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
1550    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
1551    /// mesh-slot surface — same "one typed dispatch on the substrate
1552    /// primitive, thin projections at each consumer" discipline extended
1553    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
1554    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
1555    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
1556    /// accessor discipline for the shared substrate concept "another
1557    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
1558    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
1559    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
1560    /// slot family's typed-accessor discipline now spans both the
1561    /// upgrade axis (`:upgrade-from`) and the supervision axis
1562    /// (`:children`), matching the closed M3 mesh-slot accessor family's
1563    /// shape. Named `nome()` to match the tatara-lisp author-surface
1564    /// term the field's docstring already reaches for ("The child
1565    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
1566    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
1567    /// discipline the substrate already carries — the accessor's name
1568    /// maps directly onto the canonical caixa-identity vocabulary rather
1569    /// than shadowing the field's storage-side `caixa` label.
1570    #[must_use]
1571    pub const fn nome(&self) -> &str {
1572        self.caixa.as_str()
1573    }
1574
1575    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
1576    /// requirement scalar accessor every consumer that reads the OTP-shape
1577    /// supervised child's version pin keys off — returns the author-declared
1578    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
1579    /// the typed slot's own [`String`] storage.
1580    ///
1581    /// The `:children :versao` slot carries the Cargo-shaped semver
1582    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
1583    /// which release of the supervised child caixa the OTP-shape supervisor
1584    /// tree materializes against — the same requirement grammar the peer
1585    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
1586    /// shared [`crate::render::require_valid_versao_requirement`] cascade
1587    /// and the shared [`crate::version::parse_requirement`] parser. Every
1588    /// downstream consumer that fans on the child's version pin keys off
1589    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
1590    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
1591    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
1592    /// for `feira lint` rendering, every future per-cluster version-lock
1593    /// overlay the caixa-operator's hierarchical reconciliation scheduler
1594    /// pins through a future `:placement`-scoped supervisor-tree slot, the
1595    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1596    /// per-child version resolver, the future wasm-operator's per-child
1597    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
1598    ///
1599    /// Prior to this lift the `.versao` byte-string was accessed inline at
1600    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
1601    /// [`SupervisorSpec::validate`] requirement-gate call
1602    /// `require_valid_versao_requirement(&child.versao, …)` and the
1603    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
1604    /// `versao: child.versao.clone()` — two open-coded field-accesses that
1605    /// expressed no compile-time link back to the typed slot. A future
1606    /// extension of the `:children :versao` axis to a richer author surface
1607    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1608    /// flow, a lacre-projected concrete-version rewrite the operator
1609    /// materializes at CR-admission time, a future `:children :versao-lock`
1610    /// per-cluster override slot the wasm-operator's hierarchical
1611    /// reconciliation scheduler authors per-CR) would have had to be
1612    /// threaded through both open-coded copies in lockstep or one consumer
1613    /// would silently disagree with the peer on which release constraint a
1614    /// given child resolves to — the requirement-gate call reading
1615    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
1616    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
1617    /// the actual gate rejection input, a two-consumer split at the
1618    /// validator far from the source `caixa.lisp` with no field naming the
1619    /// version-pin drift root cause. Lifting the resolution rule to a typed
1620    /// method on the substrate primitive means every downstream
1621    /// requirement-facing consumer of the Supervisor's per-`:children`
1622    /// version-pin surface reaches for exactly one typed dispatch — the
1623    /// resolver's accept-set migrates as a unit on any future axis addition.
1624    ///
1625    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
1626    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
1627    /// surface — same "one typed dispatch on the substrate primitive, thin
1628    /// projections at each consumer" discipline extended onto the M2
1629    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
1630    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
1631    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
1632    /// one accessor discipline for the shared substrate concept "another
1633    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
1634    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
1635    /// `:nome` scalar accessor — the pair
1636    /// `(nome(), versao_requirement())` jointly projects the
1637    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
1638    /// that fans on per-child identity + version pin keys off, closing the
1639    /// last unlifted per-`:children` `String`-carry axis so every downstream
1640    /// per-`:children` reader now routes through a typed dispatch on the
1641    /// substrate primitive. Named `versao_requirement()` rather than
1642    /// `versao()` because the field's storage-side `.versao` label is
1643    /// already the author-surface term (`:versao`); the accessor's name
1644    /// carries the semantic role — the semver *requirement* string the
1645    /// shared [`crate::version::parse_requirement`] entry-point consumes —
1646    /// so a raw field access and a typed dispatch read differently at every
1647    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
1648    /// naming discipline verbatim.
1649    #[must_use]
1650    pub const fn versao_requirement(&self) -> &str {
1651        self.versao.as_str()
1652    }
1653
1654    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
1655    /// per-child post-exit restart-decision policy scalar accessor every
1656    /// consumer that dispatches on the supervised child's post-exit
1657    /// reconcile posture keys off — returns the author-declared
1658    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
1659    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
1660    /// storage.
1661    ///
1662    /// The `:children :restart` slot carries the closed-set OTP-shaped
1663    /// per-child restart-decision policy discriminator
1664    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
1665    /// worker-child default; [`RestartPolicy::Transient`] — restart only
1666    /// on abnormal exit, the OTP `transient` clean-completion-aware
1667    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
1668    /// `temporary` one-shot default) that every downstream consumer of
1669    /// the Supervisor's per-child post-exit reconcile branch keys off.
1670    /// Every future downstream consumer that fans on the per-child
1671    /// restart-decision keys off this scalar (the future `feira app
1672    /// graph` per-child restart column, the future wasm-operator's
1673    /// per-child post-exit restart-decision branch, the future M4
1674    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1675    /// admission webhook, the `caixa-operator`'s hierarchical
1676    /// reconciliation scheduler's per-child post-exit reconcile branch,
1677    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
1678    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1679    /// pin threads through).
1680    ///
1681    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
1682    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
1683    /// scalar accessor and the M3 mesh-slot
1684    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
1685    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
1686    /// — same "one typed dispatch on the substrate primitive,
1687    /// `Copy`-projected closed-set enum-arm discriminator that partitions
1688    /// the downstream renderer's per-arm fan-out" discipline extended
1689    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
1690    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
1691    /// [`ChildSpec`] type — companion to the sibling per-`:children`
1692    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
1693    /// and the per-`:children` [`ChildSpec::versao_requirement`]
1694    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
1695    /// on the sibling `String`-carry axes. The triple
1696    /// `(nome(), versao_requirement(), restart())` jointly projects the
1697    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
1698    /// tree consumer that fans on per-child identity + version pin +
1699    /// restart-decision keys off, closing the last unlifted per-`:children`
1700    /// axis so every downstream per-`:children` reader now routes through
1701    /// a typed dispatch on the substrate primitive. Named `restart()` to
1702    /// match the storage field's name and the author-surface
1703    /// `:children :restart` slot term verbatim; the accessor's identity
1704    /// name maps onto the canonical OTP-shape per-child restart-decision-
1705    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
1706    /// carries.
1707    ///
1708    /// Declared `pub const fn` to close the last non-`const`
1709    /// `Copy`-return raw-field-getter posture on the M2
1710    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
1711    /// of the sibling M2 per-`:supervisor`
1712    /// [`SupervisorSpec::estrategia`] (converted in this commit)
1713    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
1714    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1715    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
1716    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
1717    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
1718    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
1719    /// downstream substrate-side `const`-context consumer of the
1720    /// per-`:children` restart-decision-policy scalar (a future
1721    /// module-scope `const _:() = assert!(matches!(child.restart(),
1722    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
1723    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1724    /// admission-webhook `const fn` per-child restart-decision floor
1725    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
1726    /// composer over the substrate primitive that fans on the per-child
1727    /// restart-decision policy at compile time) now reaches through the
1728    /// same typed dispatch on the substrate primitive at const-eval
1729    /// time as at runtime. A future non-`Copy`-return promotion of the
1730    /// scalar (an `Option<RestartPolicy>`-shape migration on the
1731    /// per-child restart-decision axis once heterogeneous per-cluster
1732    /// restart-policy overlays land, a per-tenant restart-policy-alias
1733    /// table the M4 CR materializer resolves per-CR) that would drop
1734    /// the `const` qualifier fails the fail-before-pass-after pin
1735    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
1736    /// build time rather than surfacing as a downstream consumer
1737    /// regression.
1738    #[must_use]
1739    pub const fn restart(&self) -> RestartPolicy {
1740        self.restart
1741    }
1742}
1743
1744/// Supervisor-typed slots that live alongside the standard Caixa
1745/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
1746/// the manifest stays a single typed form; this struct exists for
1747/// validation + conversion.
1748#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1749#[serde(rename_all = "camelCase")]
1750pub struct SupervisorSpec {
1751    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
1752    #[serde(default)]
1753    pub estrategia: RestartStrategy,
1754
1755    /// Max restarts within [`Self::restart_window`] before the
1756    /// supervisor itself terminates (and its parent supervisor decides
1757    /// what to do). Default 5.
1758    #[serde(default = "default_max_restarts")]
1759    pub max_restarts: u32,
1760
1761    /// Sliding window for `max_restarts`. Authored as a duration
1762    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
1763    /// is rejected by [`Self::validate`] — Erlang/OTP's
1764    /// `MaxIntensity / Period` invariant requires a positive window
1765    /// (a zero-period supervisor either trips on the first failure or
1766    /// never trips, depending on operator interpretation, neither of
1767    /// which is the author's intent). Omit the slot to express "no
1768    /// reset"; carry a positive duration to express the sliding window.
1769    #[serde(
1770        default,
1771        skip_serializing_if = "Option::is_none",
1772        with = "duration_codec"
1773    )]
1774    pub restart_window: Option<Duration>,
1775
1776    /// Static children. Empty for `SimpleOneForOne` (children added
1777    /// dynamically); required for the other three strategies.
1778    #[serde(default)]
1779    pub children: Vec<ChildSpec>,
1780}
1781
1782const fn default_max_restarts() -> u32 {
1783    // Route the private serde-`#[serde(default = "…")]` helper through
1784    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
1785    // `pub const` rather than the raw `5` literal — one source of truth
1786    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
1787    // default across the two production consumers that currently
1788    // dispatch on it (this helper via `#[serde(default = "…")]` on
1789    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
1790    // impl at line 962). Pinned by
1791    // `default_max_restarts_helper_routes_through_lifted_default` +
1792    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
1793    // in the tests module; peer of the sibling caixa-core
1794    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
1795    // that now routes its author-omitted `:max-restarts` arm through
1796    // the same lifted constant.
1797    SUPERVISOR_MAX_RESTARTS_DEFAULT
1798}
1799
1800/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
1801/// count default for the `:supervisor :max-restarts` axis — the
1802/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
1803/// Erlang's worker-supervisor default, extracted as a typed `pub const`
1804/// so every substrate-side consumer that resolves "what
1805/// [`SupervisorSpec::max_restarts`] value does an author-omitted
1806/// `:max-restarts` slot degrade onto?" reaches for exactly one
1807/// substrate-primitive `u32`.
1808///
1809/// The `:max-restarts` default axis has two production consumers on the
1810/// substrate side today (both prior to this lift folded onto raw `5`
1811/// literals with no compile-time link back to a shared truth): the
1812/// serde-`#[serde(default = "default_max_restarts")]` helper on
1813/// [`SupervisorSpec::max_restarts`] that every author-omitted
1814/// `:supervisor :max-restarts` slot lands in past the derive-macro's
1815/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
1816/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
1817/// the composed [`SupervisorSpec`] altitude reaches through
1818/// (`feira app graph`, the future wasm-operator's per-supervisor
1819/// restart-intensity counter, the future M4
1820/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1821/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
1822/// A pair of open-coded `5`s across two files that expressed no
1823/// compile-time link back to the shared OTP-canonical default — a
1824/// future rebrand of the default (a tightening to Elixir's
1825/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
1826/// the operator pins through a future
1827/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
1828/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1829/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
1830/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
1831/// per-child-cohort roadmap lands) would have had to be threaded
1832/// through both open-coded copies in lockstep or the wire-format
1833/// author-omitted arm and the view-construction author-omitted arm
1834/// would silently disagree on which restart-budget an omitted
1835/// `:max-restarts` resolves to (an author writing `:supervisor
1836/// (:max-restarts ())` would round-trip through serde with the new
1837/// default while `supervisor_view` silently continued to compose the
1838/// stale `5`, or vice versa), a two-consumer split at the composition
1839/// boundary far from the source `caixa.lisp` with no field naming the
1840/// default-drift root cause. Lifting the resolution rule to a typed
1841/// `pub const` on the substrate primitive means every downstream
1842/// consumer of the per-Supervisor default-restart-budget-count surface
1843/// reaches for exactly one substrate-primitive `u32` — the resolver's
1844/// accepted value migrates as a unit on any future axis change.
1845///
1846/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1847/// worker-supervisor default (the closest canonical OTP-shape
1848/// production reference the substrate carries, matching the sibling
1849/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
1850/// this constant with on the paired sliding-window axis). Two orders of
1851/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
1852/// (the upper bracket on the same axis, sibling of this lower default;
1853/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
1854/// axis and now share one accessor discipline on the substrate) and
1855/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
1856/// restart floor — the "one restart, then escalate" default is
1857/// deliberately loose enough to absorb a short burst of transient
1858/// child failures without escalating past the supervisor's parent
1859/// while remaining tight enough to trip the `MaxIntensity / Period`
1860/// ratio's escalation on a genuinely-stuck child within the sibling
1861/// `60s` sliding window.
1862///
1863/// Lifted as a typed `pub const` so the bound has exactly one source
1864/// of truth — the serde-side wire-format author-omitted arm at
1865/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
1866/// struct-literal default field, and the caixa-core
1867/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
1868/// arm all read from one place. Same shape every other typed default
1869/// in this crate carries (the sibling
1870/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
1871/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
1872/// sibling `:restart-window` axis, and the peer
1873/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1874/// per-renderer defaults on the caixa-flux / caixa-helm rendering
1875/// axes).
1876pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
1877
1878/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
1879/// validated [`SupervisorSpec::max_restarts`] past
1880/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
1881///
1882/// The typed field is `u32` (the zero-floor arm
1883/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
1884/// so a programmatic struct literal
1885/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
1886/// author-surface form (`:max-restarts 4294967295` or any
1887/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
1888/// cleanly through serde — a structurally unbounded `u32` ceiling. The
1889/// runtime substrate consuming the value (Erlang/OTP's
1890/// `MaxIntensity / Period` ratio, the future wasm-operator's
1891/// per-supervisor restart-intensity counter, the M4
1892/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
1893/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
1894/// escalation threshold is structurally so high that no realistic
1895/// restarts-per-`:restart-window` traffic shape can reach it, the
1896/// supervisor never escalates to its parent, and a bad child can loop
1897/// inside the window indefinitely with the parent supervisor structurally
1898/// never receiving the "this subtree has exceeded its restart budget"
1899/// signal the typed slot is meant to express — the canonical
1900/// "supervisor intensity declared, no escalation" footgun, exactly the
1901/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
1902/// on the `:politicas :circuit-breaker :max-failures` axis (both are
1903/// "trip the next-higher protection layer after N events in a rolling
1904/// window" counters with identical degenerate-at-the-high-end shape).
1905///
1906/// The `1000` ceiling matches the sibling
1907/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
1908/// peer — same "events-per-window trip threshold" semantics, same `u32`
1909/// type, same no-op-at-the-high-end failure mode) so the M4
1910/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
1911/// and the future wasm-operator's per-supervisor restart-intensity
1912/// counter reach for either field knowing the value is in `1..=1000`
1913/// without re-validating at the reconciler layer. The cap sits two
1914/// orders of magnitude above every documented Erlang/OTP production
1915/// playbook recommendation (Learn You Some Erlang's
1916/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
1917/// `max_restarts: 3` default, OTP's `supervisor` callback module
1918/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
1919/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
1920/// default) and below the clearly-pathological "effectively no
1921/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
1922/// author can plausibly want at hyperscale (a long-running supervisor
1923/// over a very-flaky pool tolerating thousands of transient restarts
1924/// before escalating), but a hard wall above which the typed policy is
1925/// structurally a no-op carried verbatim on every emitted child-restart
1926/// reconciliation contract.
1927///
1928/// Lifted as a typed `pub const` so the bound has exactly one source of
1929/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1930/// materializer's admission webhook and the wasm-operator-side
1931/// per-supervisor restart-intensity reconciler read from one place. Same
1932/// shape every other typed upper bound in this crate carries
1933/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1934/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1935/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1936/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1937/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1938/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1939pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
1940
1941/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
1942/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
1943/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
1944/// (inclusive on both ends, integer-millisecond magnitudes by the
1945/// canonical-form gate immediately preceding).
1946///
1947/// The typed field is `Option<Duration>` (the zero-floor arm
1948/// [`SupervisorError::RestartWindowZero`] already rejects
1949/// `Some(Duration::ZERO)`, and the canonical-form arm
1950/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
1951/// sub-millisecond residue), so a programmatic struct literal
1952/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
1953/// .. }` — 24h) and the equivalent author-surface form
1954/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
1955/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
1956/// cleanly through serde — a structurally unbounded `Duration` ceiling.
1957/// A `:restart-window` value far above the documented Erlang/OTP
1958/// `MaxIntensity / Period` production-playbook band (Learn You Some
1959/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
1960/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
1961/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
1962/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
1963/// degenerates the supervisor's restart-intensity counter into a
1964/// lifetime counter: the rolling failure-counting window is structurally
1965/// so long that transient restarts are never forgotten, so the
1966/// `MaxIntensity / Period` ratio degenerates from "trip the parent
1967/// supervisor when the child has exceeded its restart budget *within
1968/// the recent window*" to "trip the parent when the child has exceeded
1969/// its restart budget *over its lifetime*" — every transient restart
1970/// counts against the budget forever, the supervisor's reset semantic
1971/// never reaches the child, and the typed `:restart-window` slot
1972/// becomes a no-op rolling window carried on every emitted hierarchical
1973/// reconciliation contract. The canonical
1974/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
1975/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
1976/// `:politicas :circuit-breaker :window` axis with identical shape (both
1977/// are "rolling failure-counting window with a per-`Period` reset" Duration
1978/// axes whose lifetime-counter degenerate at the high end is the same
1979/// "the reset semantic never fires" CSE invariant violation).
1980///
1981/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
1982/// the shared duration codec emits (`"<n>h"` for any integer-hour
1983/// magnitude) — every value in the canonical authoring form's
1984/// `<integer><unit>` grammar at or below this cap renders to a clean
1985/// canonical string — and matches the three sibling typed-`Duration`
1986/// caps already lifted to this surface
1987/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1988/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
1989/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
1990/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
1991/// per-supervisor `:supervisor :restart-window` — now share a single
1992/// uniform top edge at the codec's largest emitted unit so the next
1993/// typed-slot wiring (the future wasm-operator's per-supervisor
1994/// `MaxIntensity / Period` reconciler, the M4
1995/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1996/// webhook, the `caixa-operator`'s hierarchical reconciliation
1997/// scheduler) reaches for any of the four knowing the value is in
1998/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
1999/// two orders of magnitude above every documented Erlang/OTP / Elixir /
2000/// Riak Core / RabbitMQ production-playbook recommendation band
2001/// (`5s..=300s`) and below the clearly-pathological "rolling window
2002/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
2003/// a value the author can plausibly want for a very-low-traffic
2004/// long-tail failure-restart window over a hyperscale-flaky child pool,
2005/// but a hard wall above which the rolling-window contract is
2006/// structurally a lifetime-counter contract.
2007///
2008/// Lifted as a typed `pub const` so the bound has exactly one source
2009/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2010/// materializer's admission webhook, the wasm-operator-side
2011/// per-supervisor `MaxIntensity / Period` reconciler, and the
2012/// `caixa-operator`'s hierarchical reconciliation scheduler all read
2013/// from one place. Same shape every other typed upper bound in this
2014/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
2015/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2016/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2017/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2018/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2019/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2020/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
2021/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2022/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2023pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
2024
2025/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
2026/// default for the `:supervisor :restart-window` axis — the canonical
2027/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
2028/// worker-supervisor default, extracted as a typed `pub const` so every
2029/// substrate-side consumer that resolves "what
2030/// [`SupervisorSpec::restart_window`] value does an author-omitted
2031/// `:restart-window` slot degrade onto?" reaches for exactly one
2032/// substrate-primitive [`Duration`].
2033///
2034/// The `:restart-window` default axis has one production consumer on the
2035/// substrate side today: the [`Default for SupervisorSpec`] impl's
2036/// struct-literal `restart_window` field, which prior to this lift folded
2037/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
2038/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
2039/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
2040/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
2041/// *not* fall back to this default on the sibling `:restart-window` axis
2042/// — an author-omitted `:supervisor :restart-window` composes to
2043/// `restart_window: None` (the shared codec's soft-swallow shape),
2044/// keeping author-declared intent ("no reset — never escalate on rolling
2045/// window") distinct from the [`Default for SupervisorSpec`] "canonical
2046/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
2047/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
2048/// default was split across two files with no compile-time link between
2049/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
2050/// `MaxIntensity` half at the substrate primitive while the `Period`
2051/// half rode as an open-coded literal at the composition site, so a
2052/// future coherent rebrand of the paired canonical (a tightening to
2053/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
2054/// per-cluster overlay the operator pins through a future
2055/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
2056/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2057/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
2058/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
2059/// roadmap lands) would have had to migrate the `MaxIntensity` half
2060/// through the lifted constant and the `Period` half through a raw
2061/// literal in lockstep or the two halves of the same OTP-canonical
2062/// default would silently drift out of pairing. Lifting the resolution
2063/// rule to a typed `pub const` on the substrate primitive means the
2064/// paired OTP-canonical default migrates as one unit on any future
2065/// axis change.
2066///
2067/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2068/// worker-supervisor default (the closest canonical OTP-shape
2069/// production reference the substrate carries, matching the paired
2070/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
2071/// constant is the `Period` denominator of on the same
2072/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
2073/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
2074/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
2075/// this lower default; both are typed [`Duration`] const bounds on the
2076/// `:supervisor :restart-window` axis and now share one accessor
2077/// discipline on the substrate) and above the OTP-`supervisor`
2078/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
2079/// rolling window" default is deliberately loose enough to absorb a
2080/// short burst of transient child failures without escalating past the
2081/// supervisor's parent while remaining tight enough for the paired
2082/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
2083/// stuck child within a human-scale observation window.
2084///
2085/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2086/// exactly one source of truth on each half — the sibling
2087/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
2088/// `Period` `60s` half now share the same substrate-primitive lift
2089/// discipline. Same shape every other typed default in this crate
2090/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
2091/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
2092/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
2093/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
2094/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
2095/// caixa-flux / caixa-helm rendering axes).
2096pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
2097
2098/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
2099/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
2100/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
2101/// worker-supervisor default, extracted as a typed `pub const` so every
2102/// substrate-side consumer that resolves "what
2103/// [`SupervisorSpec::estrategia`] variant does an author-omitted
2104/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
2105/// primitive [`RestartStrategy`].
2106///
2107/// The `:estrategia` default axis has three production consumers on the
2108/// substrate side today: the [`Default for RestartStrategy`] impl's
2109/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
2110/// `estrategia` field, and the
2111/// [`crate::manifest::Caixa::supervisor_view`] fold's
2112/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
2113/// collapse arm — three entry points onto the same OTP-canonical
2114/// `one_for_one` value that prior to this lift folded onto a raw
2115/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
2116/// implicit `RestartStrategy::default()` routes at the sibling consumers,
2117/// with no compile-time link back to the paired
2118/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
2119/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
2120/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
2121/// triple was split across three altitudes with no compile-time link
2122/// between the halves: the `MaxIntensity` half rode through the lifted
2123/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
2124/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2125/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
2126/// discriminator at the [`Default for RestartStrategy`] impl, so a future
2127/// coherent rebrand of the triple (Elixir's `{:one_for_one,
2128/// max_restarts: 3, max_seconds: 5}` — same strategy, different
2129/// intensity/period; an OTP `rest_for_one` widening once the substrate
2130/// discovers startup-order-coupled child cohorts as the more common
2131/// worker-supervisor default; a per-cluster overlay the operator pins
2132/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
2133/// §III.2 supervision-canary roadmap acknowledges) would have had to
2134/// migrate the `MaxIntensity` + `Period` halves through the lifted
2135/// constants and the `one_for_one` half through an open-coded arm in
2136/// lockstep or the three halves of the same OTP-canonical default would
2137/// silently drift out of pairing. Lifting the resolution rule to a typed
2138/// `pub const` on the substrate primitive means the paired OTP-canonical
2139/// worker-supervisor default migrates as one unit on any future axis
2140/// change.
2141///
2142/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
2143/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
2144/// closest canonical OTP-shape production reference the substrate
2145/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
2146/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2147/// `60s` `Period` half). The `one_for_one` strategy — restart only the
2148/// failed child, leaving siblings untouched — is the default for tree-of-
2149/// independent-workers use cases the substrate's [`RestartStrategy`]
2150/// discriminator's own docstring already carries as the default arm; it
2151/// composes with the `{5, 60}` restart-intensity ratio to name the same
2152/// substrate-canonical "canonical worker-supervisor" shape the paired
2153/// halves close on their respective axes.
2154///
2155/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2156/// exactly one source of truth on each of its three halves — the sibling
2157/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
2158/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
2159/// this `one_for_one` strategy half now share the same substrate-
2160/// primitive lift discipline. Same shape every other typed default in
2161/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
2162/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
2163/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
2164/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
2165/// upper caps on the paired sibling axes, and the peer
2166/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2167/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
2168pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
2169
2170/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
2171/// default for the `:children :restart` axis — the OTP `permanent`
2172/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
2173/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
2174/// `pub const` so every substrate-side consumer that resolves "what
2175/// [`ChildSpec::restart`] variant does an author-omitted `:children
2176/// :restart` slot degrade onto?" reaches for exactly one substrate-
2177/// primitive [`RestartPolicy`].
2178///
2179/// Completes the OTP-shape supervisor-tree default set at the substrate
2180/// primitive. The per-`:supervisor` axis already carries all three of its
2181/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2182/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
2183/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2184/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
2185/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
2186/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
2187/// the M2 `:supervisor` slot family. The split mattered because the two
2188/// axes resolve *together* on every author-omitted supervisor: a
2189/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
2190/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
2191/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
2192/// `permanent` through an open-coded enum arm, so a future coherent
2193/// rebrand of the OTP-shape default set (an Elixir-shaped
2194/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
2195/// per-cluster overlay the operator pins through the MESH-COMPOSITION
2196/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
2197/// once the substrate discovers clean-completion-aware children as the
2198/// more common child shape) would have had to migrate three halves
2199/// through typed constants and the fourth through a raw enum arm in
2200/// lockstep or the supervisor-level and child-level defaults would
2201/// silently drift apart.
2202///
2203/// The `:children :restart` default axis has two production consumers on
2204/// the substrate side today: the [`Default for RestartPolicy`] impl's
2205/// return arm, and the serde-side `#[serde(default)]` on
2206/// [`ChildSpec::restart`] that resolves an author-omitted `:children
2207/// :restart` slot through that same impl. Both now key off this one
2208/// substrate primitive, so the future wasm-operator's per-child post-exit
2209/// restart-decision branch, the future M4
2210/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2211/// admission webhook, and the `caixa-operator`'s hierarchical
2212/// reconciliation scheduler's per-child fan-out all reach for one typed
2213/// identifier when they resolve an omitted per-child restart posture.
2214///
2215/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
2216/// worker-child restart type — always restart the child regardless of how
2217/// it died, the canonical posture for long-running services that must
2218/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2219/// `one_for_one` tree-of-independent-workers strategy this constant pairs
2220/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
2221/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
2222/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
2223/// [`RestartPolicy::Temporary`] — never restart) express deliberate
2224/// one-shot / clean-completion-aware postures an author declares
2225/// explicitly, never a posture an omitted slot should silently assume.
2226pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
2227
2228/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
2229/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
2230/// `pub const fn` constructor rather than a struct-literal cascade over
2231/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
2232/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2233/// lifted consts — one source of truth for the Erlang/OTP-canonical
2234/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
2235/// paths every downstream consumer already reaches through (the
2236/// hand-authored-until-now [`Default::default`] the
2237/// `..SupervisorSpec::default()` struct-update-syntax on every
2238/// one-axis-under-test fixture in this crate's test module rests on,
2239/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
2240/// every `const`-context consumer reaches through).
2241///
2242/// Extends the [`Default`]-through-const-ctor fold discipline the
2243/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
2244/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
2245/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
2246/// and [`crate::BehaviorSpec`]
2247/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
2248/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
2249/// typed-slot spec family — extended here onto the M2 supervisor-slot
2250/// [`SupervisorSpec`] whose canonical baseline is not "everything
2251/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
2252/// supervisor triple. The `empty()` peer's naming did not fit
2253/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
2254/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
2255/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
2256/// the sibling `Option`-only slots fold to), so this peer is named
2257/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
2258/// existing per-arm pin tests
2259/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
2260/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
2261/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2262/// already reach for. Pinned load-bearing by
2263/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
2264/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
2265/// [`PartialEq`], sharpening the sibling
2266/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
2267/// pins from a per-field lift into a whole-struct one-source-of-truth
2268/// pin — the derived-until-now [`Default::default`] and the
2269/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
2270/// construction, not by coincidence).
2271impl Default for SupervisorSpec {
2272    #[inline]
2273    fn default() -> Self {
2274        Self::otp_canonical()
2275    }
2276}
2277
2278impl SupervisorSpec {
2279    /// `const`-context peer of the [`Default for SupervisorSpec`]
2280    /// impl (which routes through this constructor) — returns the
2281    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
2282    /// baseline this crate reaches for in every fixture-builder
2283    /// `..SupervisorSpec::default()` struct-update expression and
2284    /// every downstream `SupervisorSpec::default()` seed.
2285    ///
2286    /// Each field routes through the same substrate-canonical
2287    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
2288    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
2289    /// per-arm pin tests
2290    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
2291    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
2292    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2293    /// already assert, so a future coherent rebrand of the OTP-canonical
2294    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
2295    /// cluster overlay via a future `:restart-window-overrides` slot, a
2296    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
2297    /// absorption roadmap acknowledges) migrates through three typed
2298    /// constants in lockstep, and the paired [`Default`] impl inherits
2299    /// every future extension by construction.
2300    ///
2301    /// `pub const fn` rather than the derived-style `Default::default`
2302    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
2303    /// [`Default::default`] is not `const` on stable Rust, and
2304    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
2305    /// every consumer through a [`Clone::clone`]. The `pub const fn`
2306    /// discipline lets `const`-context callers construct the OTP-
2307    /// canonical baseline at compile time without runtime dispatch on
2308    /// the derived [`Default::default`], the same posture the sibling
2309    /// [`crate::LimitsSpec::empty`] (9739971) /
2310    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
2311    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
2312    /// spec `pub const fn` constructors carry on the sibling
2313    /// "everything `None`" baseline axis.
2314    ///
2315    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
2316    /// of the derived-style [`Default`]" family — sibling of the
2317    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
2318    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
2319    /// baseline" trio, extended here onto the M2 supervisor-slot
2320    /// [`SupervisorSpec`] whose canonical baseline is not "everything
2321    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
2322    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
2323    /// than `empty()` to name the actual invariant the return value
2324    /// pins — the same phrasing already used in the per-arm pin tests
2325    /// on this file. Pinned load-bearing by
2326    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
2327    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
2328    #[must_use]
2329    pub const fn otp_canonical() -> Self {
2330        Self {
2331            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
2332            max_restarts: default_max_restarts(),
2333            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2334            children: Vec::new(),
2335        }
2336    }
2337
2338    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
2339    /// sibling-restart-strategy scalar accessor every consumer that
2340    /// dispatches on the supervisor's per-sibling restart-decision shape
2341    /// keys off — returns the author-declared `:supervisor :estrategia`
2342    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
2343    /// the typed slot's own [`RestartStrategy`] storage.
2344    ///
2345    /// The `:supervisor :estrategia` slot carries the closed-set
2346    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
2347    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
2348    /// [`RestartStrategy::OneForAll`] — restart every child on any child
2349    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
2350    /// [`RestartStrategy::RestForOne`] — restart the failed child and
2351    /// every child started after it, the Erlang/OTP `rest_for_one`
2352    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
2353    /// dynamic children of the same shape, the Erlang/OTP
2354    /// `simple_one_for_one` per-session default) that every downstream
2355    /// consumer of the Supervisor's per-sibling restart-decision fan-out
2356    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
2357    /// paired coherently with the sibling `:children` axis
2358    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
2359    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
2360    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
2361    /// downstream consumer that reads the strategy keys off this scalar
2362    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2363    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
2364    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
2365    /// `estrategia:` field, the future `feira app graph` per-Supervisor
2366    /// strategy print line, the future wasm-operator's per-supervisor
2367    /// sibling-restart-strategy branch, the future M4
2368    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
2369    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
2370    /// reconciliation scheduler's per-strategy fan-out).
2371    ///
2372    /// Prior to this lift the `.estrategia` field was accessed inline at
2373    /// two production sites in `caixa-core/src/supervisor.rs` — the
2374    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2375    /// `match self.estrategia { … }` partition dispatch, and the
2376    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
2377    /// carrier at `estrategia: self.estrategia` — two open-coded
2378    /// field-accesses that expressed no compile-time link back to the
2379    /// typed slot. A future extension of the `:supervisor :estrategia`
2380    /// axis to a richer author surface (a per-cluster strategy override
2381    /// the operator pins through a future `:supervisor :estrategia-overrides`
2382    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2383    /// acknowledges, a per-tenant strategy-alias table the M4 CR
2384    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
2385    /// derivation the future adaptive-supervision engine computes from
2386    /// child-failure-history topology, a per-child-cohort strategy split
2387    /// the future `RestForCohort` extension acknowledged by the
2388    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
2389    /// would have had to be threaded through every open-coded copy in
2390    /// lockstep — one consumer reading the raw variant while a peer read
2391    /// the operator-resolved variant would silently split the
2392    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
2393    /// the actual partition-dispatch input the empty-children refusal
2394    /// arm reached under, a two-consumer split at the validator far from
2395    /// the source `caixa.lisp` with no field naming the strategy-drift
2396    /// root cause. Lifting the resolution rule to a typed method on the
2397    /// substrate primitive means every downstream consumer of the
2398    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
2399    /// reaches for exactly one typed dispatch — the resolver's accept-set
2400    /// migrates as a unit on any future axis addition.
2401    ///
2402    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
2403    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
2404    /// per-`:placement` distribution-strategy axis — same "one typed
2405    /// dispatch on the substrate primitive, thin projections at each
2406    /// consumer" discipline extended onto the M2 supervisor-slot
2407    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
2408    /// scalar axis. The two typed axes (`Placement::estrategia` on the
2409    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
2410    /// Supervisor side) now share one accessor discipline for the shared
2411    /// substrate concept "a `Copy`-projected closed-set enum-arm
2412    /// discriminator that partitions the downstream renderer's per-arm
2413    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
2414    /// `SupervisorSpec` type — companion to the sibling per-`:children`
2415    /// [`crate::ChildSpec::nome`] (57c61d0) /
2416    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2417    /// scalar accessors on the sibling per-`:children` `String`-carry
2418    /// axes. Named `estrategia()` to match the storage field's name and
2419    /// the peer [`crate::Placement::estrategia`] method-name discipline
2420    /// verbatim; the accessor's identity name maps onto the canonical
2421    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
2422    /// docstring already carries.
2423    ///
2424    /// Declared `pub const fn` to close the M2 supervisor-slot
2425    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
2426    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
2427    /// (converted in this commit) `Copy`-composite-enum accessor, peer
2428    /// of the sibling M2 per-`:supervisor`
2429    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2430    /// already lifted, and mirror of the peer M3 mesh-slot
2431    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
2432    /// `Copy`-return `pub const fn` scalar accessor whose method-name
2433    /// discipline this accessor was authored to match. Every downstream
2434    /// substrate-side `const`-context consumer of the per-`:supervisor`
2435    /// sibling-restart-strategy scalar (a future module-scope `const
2436    /// _:() = assert!(matches!(sup.estrategia(),
2437    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
2438    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2439    /// admission-webhook `const fn` per-supervisor strategy-arm floor
2440    /// over a typed [`SupervisorSpec`], any future `const fn`
2441    /// supervisor-tree composer over the substrate primitive that fans
2442    /// on the sibling-restart-strategy at compile time) now reaches
2443    /// through the same typed dispatch on the substrate primitive at
2444    /// const-eval time as at runtime. A future non-`Copy`-return
2445    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
2446    /// migration once the substrate grows per-cluster strategy overlays
2447    /// the [`SupervisorSpec`] docstring already anticipates, a
2448    /// per-tenant strategy-alias table the M4 CR materializer resolves
2449    /// per-CR) that would drop the `const` qualifier fails the
2450    /// fail-before-pass-after pin
2451    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
2452    /// caixa-core build time rather than surfacing as a downstream
2453    /// consumer regression.
2454    #[must_use]
2455    pub const fn estrategia(&self) -> RestartStrategy {
2456        self.estrategia
2457    }
2458
2459    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
2460    /// `MaxIntensity` restart-budget scalar accessor every consumer that
2461    /// reads the supervisor's per-`:restart-window` restart-budget count
2462    /// keys off — returns the author-declared `:supervisor :max-restarts`
2463    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
2464    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
2465    /// borrow of `&self` past the call). Non-optional (the `u32` field
2466    /// carries the restart-budget count as a required axis with a
2467    /// [`default_max_restarts`]-supplied default; the zero-floor arm
2468    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
2469    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
2470    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
2471    ///
2472    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
2473    /// `MaxIntensity` restart-budget count that pairs with the sibling
2474    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
2475    /// restart-intensity ratio the supervisor trips its own escalation on
2476    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
2477    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
2478    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
2479    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
2480    /// upper-cap bracket at
2481    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
2482    /// wasm-operator's per-supervisor restart-intensity counter's
2483    /// budget-vs-count comparator, the future M4
2484    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2485    /// webhook, the `caixa-operator`'s hierarchical reconciliation
2486    /// scheduler's per-supervisor escalation-decision branch, every
2487    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
2488    /// offending count verbatim for `feira lint` rendering).
2489    ///
2490    /// Prior to this lift the `.max_restarts` field was accessed inline at
2491    /// one production site in `caixa-core/src/supervisor.rs` — the
2492    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
2493    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
2494    /// that expressed no compile-time link back to the typed slot. A
2495    /// future extension of the `:max-restarts` axis to a richer author
2496    /// surface (a per-cluster restart-budget override the operator pins
2497    /// through a future `:supervisor :max-restarts-overrides` slot the
2498    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
2499    /// a per-tenant restart-budget-alias table the M4 CR materializer
2500    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
2501    /// the future adaptive-supervision engine computes from child-failure-
2502    /// history topology, a promotion of the plain `u32` count to a richer
2503    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
2504    /// budget-partition slot comes into scope) would have had to be
2505    /// threaded through every open-coded copy in lockstep or the validate
2506    /// gate and the future M4 emit path would silently disagree on which
2507    /// restart-budget count a given supervisor resolves to — an author's
2508    /// `:max-restarts 5` would satisfy validate while the emit path
2509    /// silently read a drifted other value (a `:max-restarts 10000`
2510    /// no-op supervisor at the emit boundary would carry the author's
2511    /// declared `5` verbatim in `feira lint` output while the future
2512    /// wasm-operator's restart-intensity counter operated under the
2513    /// drifted count), a two-consumer split at the validator far from the
2514    /// source `caixa.lisp` with no field naming the restart-budget-drift
2515    /// root cause. Lifting the resolution rule to a typed method on the
2516    /// substrate primitive means every downstream consumer of the
2517    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
2518    /// for exactly one typed dispatch — the resolver's accept-set migrates
2519    /// as a unit on any future axis addition.
2520    ///
2521    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
2522    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
2523    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
2524    /// outlier-detection trip-threshold axis — same "one typed dispatch on
2525    /// the substrate primitive, thin projections at each consumer"
2526    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
2527    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
2528    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
2529    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
2530    /// one accessor discipline for the shared substrate concept "a
2531    /// `Copy`-projected required `u32` count that trips the next-higher
2532    /// protection layer after N events in a rolling window" — both are
2533    /// counters with identical degenerate-at-the-high-end shape and share
2534    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
2535    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
2536    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
2537    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
2538    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
2539    /// the storage field's name verbatim and the peer
2540    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
2541    /// accessor's identity maps onto the canonical OTP-shape supervision
2542    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
2543    /// already carries.
2544    #[must_use]
2545    pub const fn max_restarts(&self) -> u32 {
2546        self.max_restarts
2547    }
2548
2549    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
2550    /// `Period` sliding-window scalar accessor every consumer of the
2551    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
2552    /// keys off — returns the author-declared `:supervisor :restart-window`
2553    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
2554    /// the typed slot's own `Option<Duration>` storage (`Duration` is
2555    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
2556    /// value; no borrow of `&self` past the call). `None` when the slot is
2557    /// absent (the canonical "never reset — every restart across the
2558    /// supervisor's lifetime counts against the sibling `:max-restarts`
2559    /// budget" sentinel the field's own docstring names and the peer
2560    /// `validate_accepts_none_restart_window` pin locks in on the
2561    /// [`SupervisorSpec::validate`] entry-side).
2562    ///
2563    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
2564    /// `Period` sliding-observation-interval that pairs with the sibling
2565    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
2566    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
2567    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
2568    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
2569    /// default). The typed slot's `Option<Duration>` accept-set —
2570    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
2571    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
2572    /// `Period > 0`; a zero period either trips on the first failure or
2573    /// never trips depending on operator interpretation, neither of which
2574    /// is the author's intent — omit the slot to express "no reset";
2575    /// carry a positive duration to express the sliding window),
2576    /// integer-millisecond canonical form enforced through
2577    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
2578    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
2579    /// future wasm-operator's per-supervisor restart-intensity counter
2580    /// quantizes at milliseconds), upper-bounded by
2581    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
2582    /// supervisor rolling window any operationally-reachable supervisor
2583    /// can honor without spanning multiple scheduler epochs the
2584    /// hierarchical-reconciliation scheduler treats as independent) —
2585    /// maps onto the future wasm-operator (M3) per-supervisor
2586    /// restart-intensity counter's rolling-observation-interval, the
2587    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2588    /// per-`spec.restartWindow` admission webhook, and the sibling
2589    /// `duration_codec`-serialized wire scalar every downstream consumer
2590    /// of the supervisor's per-`:supervisor` restart-intensity denominator
2591    /// keys off.
2592    ///
2593    /// Prior to this lift the `.restart_window` field was accessed inline
2594    /// at one production site in `caixa-core/src/supervisor.rs` — the
2595    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
2596    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
2597    /// open-coded field-access that expressed no compile-time link back to
2598    /// the typed slot. A future extension of the `:restart-window` axis to
2599    /// a richer author surface (a per-cluster restart-window override the
2600    /// operator pins through a future `:supervisor :restart-window-overrides`
2601    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2602    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
2603    /// materializer resolves per-CR, a per-supervisor dynamic
2604    /// restart-window derivation the future adaptive-supervision engine
2605    /// computes from child-failure-history topology, a promotion of the
2606    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
2607    /// pair once Erlang/OTP's per-child-cohort observation-interval-
2608    /// partition slot comes into scope) would have had to be threaded
2609    /// through every open-coded copy in lockstep or the validate gate and
2610    /// the future M4 emit path would silently disagree on which
2611    /// restart-window a given supervisor resolves to — an author's
2612    /// `:restart-window "60s"` would satisfy validate while the emit path
2613    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
2614    /// authored slot at the emit boundary would carry the author's
2615    /// declared window verbatim in `feira lint` output while the future
2616    /// wasm-operator's restart-intensity counter operated under a
2617    /// drifted window, or vice versa: an author's `:restart-window ()`
2618    /// would carry the "never reset" sentinel through validate while the
2619    /// emit path silently substituted a default sliding window), a
2620    /// two-consumer split at the validator far from the source
2621    /// `caixa.lisp` with no field naming the restart-window-drift root
2622    /// cause. Lifting the resolution rule to a typed method on the
2623    /// substrate primitive means every downstream consumer of the
2624    /// Supervisor's per-`:supervisor` restart-intensity-denominator
2625    /// surface reaches for exactly one typed dispatch — the resolver's
2626    /// accept-set migrates as a unit on any future axis addition.
2627    ///
2628    /// Third `Copy`-return accessor on the M2 supervisor-slot
2629    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
2630    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
2631    /// payload rather than a `Copy`-scalar, and the per-`:children`
2632    /// [`crate::ChildSpec::nome`] (57c61d0) /
2633    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2634    /// scalar accessors already close the per-element `String`-carry
2635    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
2636    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
2637    /// per-outermost-call wall-clock-deadline axis and the peer M3
2638    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
2639    /// accessor on the `:politicas` slot's per-call-deadline axis — all
2640    /// three share the shared substrate concept "a `Copy`-projected
2641    /// optional `Duration` that carries a positive integer-millisecond
2642    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
2643    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
2644    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
2645    /// bracket-helper the three axes each route through. Named
2646    /// `restart_window()` to match the storage field's name verbatim and
2647    /// the peer [`crate::LimitsSpec::wall_clock`] /
2648    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
2649    /// accessor's identity maps onto the canonical OTP-shape supervision
2650    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
2651    /// already carries.
2652    #[must_use]
2653    pub const fn restart_window(&self) -> Option<Duration> {
2654        self.restart_window
2655    }
2656
2657    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
2658    /// static-child-list slice accessor every consumer that walks the
2659    /// supervisor's declared child set keys off — returns the author-
2660    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
2661    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
2662    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
2663    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
2664    /// through). Non-optional: an empty slice is the load-bearing
2665    /// "author declared `:children ()`" sentinel every consumer of the
2666    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
2667    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
2668    /// three strategies require a non-empty slice — the paired
2669    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
2670    /// [`SupervisorError::NoChildren`] refusal cascade pins the
2671    /// partition on both arms).
2672    ///
2673    /// The `:supervisor :children` slot carries the OTP-shaped static
2674    /// child list the supervisor materializes one ComputeUnit per
2675    /// entry from — the Erlang/OTP `supervisor:init/1`'s
2676    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
2677    /// through the tatara-lisp `:children` author surface onto a typed
2678    /// `Vec<ChildSpec>` whose per-element `(nome(),
2679    /// versao_requirement(), restart)` triple the per-child
2680    /// [`SupervisorSpec::validate`] loop already gates through the
2681    /// lifted [`ChildSpec::nome`] (57c61d0) /
2682    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
2683    /// Every downstream consumer that fans on the static child list
2684    /// keys off this slice (the [`SupervisorSpec::validate`]
2685    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
2686    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
2687    /// per-child DNS-1123 / semver-requirement / duplicate-detection
2688    /// fan-out loop, every future wasm-operator (M3) per-supervisor
2689    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
2690    /// materialization loop, the future M4
2691    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2692    /// admission-webhook fan-out, the future `feira app graph`
2693    /// per-supervisor tree-print traversal).
2694    ///
2695    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
2696    /// inline at three production sites in `caixa-core/src/supervisor.rs`
2697    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
2698    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
2699    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
2700    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
2701    /// validate loop's `for child in &self.children` traversal head —
2702    /// three open-coded field-accesses that expressed no compile-time
2703    /// link back to the typed slot. A future extension of the
2704    /// `:supervisor :children` axis to a richer author surface (a
2705    /// per-cluster child-set overlay the operator pins through a future
2706    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
2707    /// supervision-canary roadmap acknowledges, a per-tenant
2708    /// child-set-alias table the M4 CR materializer resolves per-CR,
2709    /// a per-supervisor dynamic-child derivation the future adaptive-
2710    /// supervision engine computes from child-failure-history topology,
2711    /// a promotion of the plain `Vec<ChildSpec>` to a richer
2712    /// `{static, dynamic}` partition once Erlang/OTP's
2713    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
2714    /// would have had to be threaded through all three open-coded copies
2715    /// in lockstep or one consumer would silently disagree with the
2716    /// peers on which child-set a given supervisor resolves to — the
2717    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
2718    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
2719    /// would silently split the partition-dispatch's two-arm coherence
2720    /// (a supervisor that satisfies neither arm's precondition, or that
2721    /// satisfies both, at the cost of the paired
2722    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
2723    /// silently drifting from the per-child validate loop's actual
2724    /// traversal input), a three-consumer split at the validator far
2725    /// from the source `caixa.lisp` with no field naming the
2726    /// child-set-drift root cause. Lifting the resolution rule to a
2727    /// typed method on the substrate primitive means every downstream
2728    /// consumer of the Supervisor's per-`:supervisor` static-child-list
2729    /// surface reaches for exactly one typed dispatch — the resolver's
2730    /// accept-set migrates as a unit on any future axis addition.
2731    ///
2732    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
2733    /// — the seed for the same "one typed dispatch on the substrate
2734    /// primitive, thin projections at each consumer" discipline the
2735    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
2736    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
2737    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
2738    /// onto the first `Vec`-carry axis on the substrate. The four peer
2739    /// `Vec`-carry axes still unlifted at the time of this seed —
2740    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
2741    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
2742    /// (`Vec<Membro>` per-Aplicacao member list),
2743    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
2744    /// per-Aplicacao WIT-typed edge list),
2745    /// [`crate::UpgradeFromEntry::instructions`]
2746    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
2747    /// — inherit this accessor's discipline as future compounding runs
2748    /// migrate their consumers onto the shared slice-return shape.
2749    /// Fourth (and final) accessor on the M2 supervisor-slot
2750    /// `SupervisorSpec` type, sibling to the three `Copy`-return
2751    /// [`SupervisorSpec::estrategia`] (eafb619) /
2752    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
2753    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
2754    /// the last unlifted per-`:supervisor` field axis (the
2755    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
2756    /// per-`:supervisor` reader now routes through a typed dispatch on
2757    /// the substrate primitive. Named `children()` to match the storage
2758    /// field's name verbatim and the tatara-lisp author-surface term
2759    /// (`:children`) the field's own docstring already carries; the
2760    /// accessor's identity maps onto the canonical OTP-shape
2761    /// supervision vocabulary the [`SupervisorSpec::children`] field's
2762    /// docstring already reaches for ("Static children ..."). Returns
2763    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
2764    /// consumer of the child list treats it as a read-only sequence —
2765    /// the slice-view is the narrowest borrow that supports every
2766    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
2767    /// index, `.len()`) without leaking the backing `Vec`'s
2768    /// grow/push/reserve surface that no consumer of the typed view
2769    /// reaches for (the storage-side `Vec` remains reachable through
2770    /// the `pub children` field for the mutation-carrying
2771    /// `Caixa::supervisor_view` fold-in path in
2772    /// `manifest.rs:supervisor_view`).
2773    #[must_use]
2774    pub const fn children(&self) -> &[ChildSpec] {
2775        self.children.as_slice()
2776    }
2777
2778    /// Validate the supervisor's typed shape — strategy ↔ children
2779    /// invariants, max_restarts > 0, restart_window > 0 when set,
2780    /// per-child non-empty + duplicate-free names.
2781    ///
2782    /// Mirrors the value-shape discipline applied to every other
2783    /// typed slot:
2784    ///
2785    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
2786    ///     same "0 means the opposite of what you think" footgun
2787    ///     closed for `:politicas :timeout` (Envoy interprets a zero
2788    ///     timeout as `infinite`), `:politicas :circuit-breaker
2789    ///     :window`, and `:limits :wall-clock`. The
2790    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
2791    ///     `supervisor` requires `Period > 0`; a zero period either
2792    ///     trips on the first failure or never trips depending on
2793    ///     operator interpretation, neither of which is the
2794    ///     author's intent. Omit `:restart-window` to express "no
2795    ///     reset"; carry a positive duration to express the window.
2796    ///   - duplicate `:children` `:caixa` names are the same
2797    ///     graph-node-set / multiset distinction closed for
2798    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
2799    ///     and `:entrada :paths` (eb3456d). Two children with the
2800    ///     same `:caixa` materialize as two ComputeUnits with the
2801    ///     same name in the cluster's HelmRelease values, one
2802    ///     silently overwriting the other. Erlang/OTP's
2803    ///     `child_spec.id` is required-unique per supervisor;
2804    ///     pleme-io enforces the same set-not-multiset shape on
2805    ///     `:caixa` (the load-bearing identity in our renderer).
2806    pub fn validate(&self) -> Result<(), SupervisorError> {
2807        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
2808        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2809        // error carrier's `estrategia:` field through the lifted
2810        // [`SupervisorSpec::estrategia`] accessor rather than the raw
2811        // `self.estrategia` field access — the two production consumers
2812        // of the per-`:supervisor` sibling-restart-strategy scalar now
2813        // key off exactly one typed dispatch on the substrate primitive,
2814        // so any future rebrand on the axis (a per-cluster strategy
2815        // override the operator pins through a future `:supervisor
2816        // :estrategia-overrides` slot, a per-tenant strategy-alias table
2817        // the M4 CR materializer resolves per-CR) migrates as a single
2818        // caixa-core edit rather than a coordinated rewrite of the two
2819        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
2820        // (921fe1b) four-consumer migration on the per-`:placement`
2821        // distribution-strategy axis.
2822        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
2823        // dispatch's paired `.is_empty()` cross-slot refusal probes
2824        // (the `SimpleOneForOne`-arm
2825        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
2826        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2827        // refusal) through the lifted [`SupervisorSpec::children`]
2828        // slice-return accessor rather than the raw `self.children`
2829        // field access — the two paired production consumers of the
2830        // per-`:supervisor` static-child-list scalar-shape now key off
2831        // exactly one typed dispatch on the substrate primitive, so any
2832        // future rebrand on the axis (a per-cluster child-set overlay
2833        // the operator pins through a future `:supervisor
2834        // :children-overrides` slot, a per-tenant child-set-alias table
2835        // the M4 CR materializer resolves per-CR) migrates as a single
2836        // caixa-core edit rather than a coordinated rewrite of the
2837        // paired arms — first slice-return migration on any typed slot,
2838        // seed for the peer per-`:placement :clusters`,
2839        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
2840        // :instructions` `Vec`-carry axes.
2841        match self.estrategia() {
2842            RestartStrategy::SimpleOneForOne => {
2843                // SimpleOneForOne: children added at runtime. Static
2844                // list must be empty (one shape declared elsewhere).
2845                if !self.children().is_empty() {
2846                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
2847                }
2848            }
2849            _ => {
2850                if self.children().is_empty() {
2851                    return Err(SupervisorError::no_children(self.estrategia()));
2852                }
2853            }
2854        }
2855        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
2856        // axis. See [`crate::render::require_positive_bounded_u32`] for
2857        // the ordering discipline (zero-floor arm strictly precedes cap
2858        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
2859        // diagnostic with its counter-axis remediation directly named,
2860        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
2861        // cap-arm miss). Until this bracket landed the top edge ran all
2862        // the way to `u32::MAX` and a struct-literal
2863        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
2864        // equivalent author-surface `:max-restarts 100000` /
2865        // `:max-restarts 4294967295` typo landing in the slot) silently
2866        // passed validate. The runtime substrate consuming the value
2867        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
2868        // wasm-operator's per-supervisor restart-intensity counter, the
2869        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2870        // admission webhook) then turned a typed `:max-restarts`
2871        // policy into a no-op supervisor: the escalation threshold is
2872        // structurally so high that no realistic
2873        // restarts-per-`:restart-window` traffic shape can reach it,
2874        // the supervisor never escalates to its parent, and a bad
2875        // child can loop inside the window indefinitely with the
2876        // parent supervisor structurally never receiving the "this
2877        // subtree has exceeded its restart budget" signal the typed
2878        // slot is meant to express. The bracket set is
2879        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
2880        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
2881        // the sibling `:politicas :circuit-breaker :max-failures` axis:
2882        // both are "trip the next-higher protection layer after N
2883        // events in a rolling window" counters with identical
2884        // degenerate-at-the-high-end shape and now share one canonical
2885        // bracket helper. The bracket precedes the sibling
2886        // `:restart-window` zero-floor / canonical-millisecond arms so
2887        // an over-cap `max_restarts` paired with a structurally invalid
2888        // window surfaces the bracket diagnostic first, mirroring the
2889        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
2890        // ordering on the peer `:politicas :circuit-breaker` slot.
2891        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
2892        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
2893        // accessor rather than the raw `self.max_restarts` field access —
2894        // the one production consumer of the per-`:supervisor`
2895        // restart-budget-count scalar now keys off exactly one typed
2896        // dispatch on the substrate primitive, so any future rebrand on
2897        // the axis (a per-cluster restart-budget override the operator
2898        // pins through a future `:supervisor :max-restarts-overrides`
2899        // slot, a per-tenant restart-budget-alias table the M4 CR
2900        // materializer resolves per-CR) migrates as a single caixa-core
2901        // edit rather than a coordinated rewrite — sibling of the peer M3
2902        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
2903        // the per-`:politicas :circuit-breaker :max-failures` axis.
2904        crate::render::require_positive_bounded_u32(
2905            self.max_restarts(),
2906            SUPERVISOR_MAX_RESTARTS_MAX,
2907            || SupervisorError::ZeroMaxRestarts,
2908            SupervisorError::max_restarts_exceeds_cap,
2909        )?;
2910        // Route the [`SupervisorSpec::validate`] `:restart-window`
2911        // zero-floor + integer-millisecond canonical-form + upper-cap
2912        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
2913        // accessor rather than the raw `self.restart_window` field access —
2914        // the one production consumer of the per-`:supervisor`
2915        // restart-intensity-denominator scalar now keys off exactly one
2916        // typed dispatch on the substrate primitive, so any future rebrand
2917        // on the axis (a per-cluster restart-window override the operator
2918        // pins through a future `:supervisor :restart-window-overrides`
2919        // slot, a per-tenant restart-window-alias table the M4 CR
2920        // materializer resolves per-CR) migrates as a single caixa-core
2921        // edit rather than a coordinated rewrite — sibling of the peer M2
2922        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
2923        // on the per-`:limits :wall-clock` axis and the peer M3
2924        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
2925        // per-`:politicas :timeout` axis.
2926        if let Some(w) = self.restart_window() {
2927            // Zero-floor + integer-millisecond canonical-form +
2928            // upper-cap bracket on the typed `:restart-window` axis.
2929            // See
2930            // [`crate::render::require_positive_canonical_bounded_duration`]
2931            // for the full three-arm ordering discipline (zero-floor
2932            // strictly precedes canonical-form so `Duration::ZERO`
2933            // surfaces the self-locating `RestartWindowZero`
2934            // diagnostic; canonical-form strictly precedes the cap arm
2935            // so a sub-millisecond above-cap value surfaces the more
2936            // fundamental round-trip-shape diagnostic first) and the
2937            // three peer typed-`Duration` sites that share this
2938            // canonical bracket ([`crate::MeshPolicy::timeout`],
2939            // [`crate::CircuitBreaker::window`],
2940            // [`crate::LimitsSpec::wall_clock`]). Every validated
2941            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2942            // (1ms..=1h), integer-millisecond granularity.
2943            crate::render::require_positive_canonical_bounded_duration(
2944                w,
2945                SUPERVISOR_RESTART_WINDOW_MAX,
2946                || SupervisorError::RestartWindowZero,
2947                SupervisorError::restart_window_not_canonical,
2948                SupervisorError::restart_window_exceeds_cap,
2949            )?;
2950        }
2951        // Route the per-child DNS-1123 / semver-requirement / duplicate-
2952        // detection fan-out loop through the lifted named per-slot gate
2953        // [`SupervisorSpec::validate_children`] rather than an inline
2954        // three-per-child cascade — every future consumer that wants to
2955        // re-check only the `:children` slot's per-entry axes (the M4
2956        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2957        // admission webhook re-validating one added/renamed child, the
2958        // future wasm-operator's per-child dynamic-add re-validator on
2959        // the `SimpleOneForOne` runtime-add path once dynamic-children
2960        // graduate to a typed slot, a future partial re-validator on a
2961        // per-`:children`-entry patch) reaches every per-entry axis
2962        // through one dispatch rather than re-inlining the three-arm
2963        // cascade in lockstep with `validate` or paying the peer
2964        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
2965        // reach one entry check. Sibling of the peer M3 mesh-slot
2966        // per-slot gate family (`validate_membros` — the exact peer on
2967        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
2968        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
2969        // `validate_placement`; `validate_politicas` routing through
2970        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
2971        // per-slot gate discipline now spans both the M3 mesh-slot
2972        // family and the M2 `:children` per-child-cascade axis on one
2973        // shape: one named per-slot gate per typed per-entry loop.
2974        self.validate_children()?;
2975        Ok(())
2976    }
2977
2978    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
2979    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
2980    /// gate, and duplicate-`:caixa` dedup arm into one call every
2981    /// consumer that wants to re-validate one `:children` entry (or the
2982    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
2983    /// admits reaches through.
2984    ///
2985    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
2986    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
2987    /// three-per-entry shape (DNS-1123 name + semver-requirement +
2988    /// duplicate-`:caixa` dedup), lifted to one named substrate
2989    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2990    /// materializer's admission webhook re-checking one added or renamed
2991    /// child, the future wasm-operator's per-child dynamic-add
2992    /// re-validator on the `SimpleOneForOne` runtime-add path once
2993    /// dynamic-children graduate to a typed slot, a future partial
2994    /// re-validator on a per-`:children`-entry patch — each reaches the
2995    /// three per-entry axes through this one dispatch rather than
2996    /// re-inlining the three-arm cascade in lockstep with `validate`
2997    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
2998    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
2999    /// reach one entry check.
3000    ///
3001    /// Self-contained on `&self` — resolves its own dedup `HashSet`
3002    /// through [`SupervisorSpec::children`] rather than borrowing one
3003    /// threaded down from `validate`, the same posture the peer M3
3004    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
3005    /// [`crate::AplicacaoSpec::validate_contratos`],
3006    /// [`crate::AplicacaoSpec::validate_entrada`],
3007    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
3008    /// consumer that reaches this gate directly (without first calling
3009    /// `validate`) still runs the full per-child cascade — pinned by
3010    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3011    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3012    /// + `validate_children_is_self_contained_on_children_slot`.
3013    ///
3014    /// The three per-entry arms run in the same canonical order the
3015    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
3016    /// the diagnostic every author-declared per-`:children` entry surfaces
3017    /// through `validate` is byte-equal to the diagnostic this gate
3018    /// surfaces when called directly — the equivalence-pin pair
3019    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3020    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3021    /// asserts the two altitudes discriminate the same set on every
3022    /// per-entry-covered input.
3023    pub fn validate_children(&self) -> Result<(), SupervisorError> {
3024        let mut seen = std::collections::HashSet::new();
3025        for child in self.children() {
3026            // Every emitted cluster artifact's `metadata.name` for a
3027            // supervised child derives from this `:children :caixa` value
3028            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
3029            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
3030            // label value on every child's pod identity, and the per-
3031            // child K8s [`Service`][svc] `metadata.name` the future
3032            // wasm-operator (M3) provisions for inter-child supervision
3033            // tree wiring. Each apiserver-side schema on each landing
3034            // site enforces the DNS-1123 label rule on admission; a
3035            // structurally invalid child name (`"Worker"`, `"my_worker"`,
3036            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
3037            // UUID-shaped mistaken-identity slug) silently passes the
3038            // prior empty-/duplicate-only gate and the failure surfaces
3039            // at `kubectl apply` time as a `metadata.name: Invalid value`
3040            // rejection, far from the source caixa.lisp, with no field
3041            // naming the offending `:children` entry. Lifting the gate
3042            // to caixa-build time mirrors the `:membros :caixa` value-
3043            // shape trajectory (3f9d7a0) and the `:placement :clusters`
3044            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
3045            // identifier axis — the supervisor tree's child names —
3046            // through the lifted
3047            // [`crate::render::require_valid_dns_1123_label`] gate the
3048            // seven peer name axes (`:membros :caixa`, `:placement
3049            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
3050            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
3051            // route through, so drift between the eight axes' accepted
3052            // DNS-1123-label sets is structurally impossible.
3053            //
3054            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
3055            crate::render::require_valid_dns_1123_label(
3056                child.nome(),
3057                || SupervisorError::EmptyChildName,
3058                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
3059            )?;
3060            // The author surface for `:children :versao` is the same
3061            // Cargo-shaped semver requirement string `:deps :versao` and
3062            // `:membros :versao` carry — and the lacre pipeline resolves
3063            // all three axes through the same
3064            // [`crate::version::parse_requirement`] entry-point. The
3065            // shared [`crate::render::require_valid_versao_requirement`]
3066            // helper brackets the empty-first + parse cascade both peer
3067            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
3068            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
3069            // :versao`) route through, so drift between the three axes'
3070            // accepted requirement sets is structurally impossible and
3071            // the parse-side no-op the empty-first arm closes (semver's
3072            // empty parse yields an implicit `*`) lives in exactly one
3073            // predicate. Every `ChildSpec::versao` past validate is
3074            // round-trippable through [`crate::parse_requirement`]
3075            // without re-checking at the resolver layer, and the three
3076            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
3077            // are now structurally equivalent by construction.
3078            crate::render::require_valid_versao_requirement(
3079                child.versao_requirement(),
3080                || SupervisorError::empty_child_version(child.nome()),
3081                |reason| {
3082                    SupervisorError::child_versao_invalid(
3083                        child.nome(),
3084                        child.versao_requirement(),
3085                        reason,
3086                    )
3087                },
3088            )?;
3089            crate::render::insert_first_seen(&mut seen, child.nome(), || {
3090                SupervisorError::duplicate_child_caixa(child.nome())
3091            })?;
3092        }
3093        Ok(())
3094    }
3095}
3096
3097/// Cross-slot coherence gate on the supervision tree: no
3098/// `:children :caixa` entry may name the supervisor's own `:nome`.
3099///
3100/// A supervisor that lists itself as a child is a degenerate self-parent
3101/// — the supervision tree is a DAG rooted at the supervisor (OTP child
3102/// specs reference *distinct* child processes; a supervisor is never its
3103/// own child), and the wasm-operator's hierarchical reconciliation would
3104/// otherwise be handed a node that is its own parent: a one-node cycle it
3105/// either rejects far from the source `caixa.lisp` or recurses on. Because
3106/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
3107/// lacre closure root), a child whose `:caixa` equals the supervisor's
3108/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
3109///
3110/// Lives outside [`SupervisorSpec::validate`] because the typed view
3111/// carries the children but not the parent `:nome`; mirrors the
3112/// cross-slot precedence gate `validate_upgrade_from_against_versao`
3113/// (which likewise reads one slot against another at the
3114/// [`crate::layout`] wire-up site) and the mesh self-edge gate
3115/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
3116/// node to itself is structurally not a tree/mesh edge" discipline, here
3117/// on the supervision-tree axis.
3118pub fn validate_no_self_supervision(
3119    children: &[ChildSpec],
3120    parent_nome: &str,
3121) -> Result<(), SupervisorError> {
3122    for child in children {
3123        if child.nome() == parent_nome {
3124            return Err(SupervisorError::child_supervises_self(parent_nome));
3125        }
3126    }
3127    Ok(())
3128}
3129
3130#[derive(Debug, Error, PartialEq, Eq)]
3131pub enum SupervisorError {
3132    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
3133    NoChildren { estrategia: RestartStrategy },
3134    #[error(
3135        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
3136    )]
3137    SimpleOneForOneWithStaticChildren,
3138    #[error(":max-restarts must be > 0")]
3139    ZeroMaxRestarts,
3140    #[error(
3141        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
3142         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
3143         restart-intensity policy into a no-op supervisor: the escalation threshold is \
3144         structurally so high that no realistic restarts-per-:restart-window traffic shape \
3145         can reach it, so the supervisor never escalates to its parent and a bad child can \
3146         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
3147         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
3148         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3149         materializer's admission webhook) emits a `:max-restarts` declaration that is \
3150         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
3151         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
3152         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
3153         band) or restructure the supervision tree (split the flaky child into its own \
3154         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
3155    )]
3156    MaxRestartsExceedsCap { max_restarts: u32 },
3157    #[error(
3158        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
3159         requires Period > 0; a zero window either trips on the first failure or \
3160         never trips depending on operator interpretation. Omit :restart-window to \
3161         express `never reset`; carry a positive duration to express the window."
3162    )]
3163    RestartWindowZero,
3164    #[error(
3165        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
3166         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
3167         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
3168         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
3169         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
3170    )]
3171    RestartWindowNotCanonical { window: Duration },
3172    #[error(
3173        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
3174         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
3175         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
3176         failure-counting window is structurally so long that transient restarts are never \
3177         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
3178         when the child has exceeded its restart budget within the recent window` to `trip the \
3179         parent when the child has exceeded its restart budget over its lifetime`, and the \
3180         supervisor's reset semantic never reaches the child — every typed-slot consumer \
3181         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
3182         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3183         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
3184         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
3185         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
3186         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
3187         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
3188         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
3189         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
3190         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
3191         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
3192         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
3193         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
3194         hiding it behind a rolling-window declaration the cap arm rejects)"
3195    )]
3196    RestartWindowExceedsCap { window: Duration },
3197    #[error("child entry has empty :caixa name")]
3198    EmptyChildName,
3199    #[error(
3200        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
3201         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
3202         name / label value the child name lands in — the per-child \
3203         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
3204         label value, and the future wasm-operator per-child Service `metadata.name` \
3205         — each apiserver-side schema rejects names that don't match; use a \
3206         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
3207    )]
3208    ChildCaixaInvalid { caixa: String, reason: String },
3209    #[error("child {caixa:?} has empty :versao constraint")]
3210    EmptyChildVersion { caixa: String },
3211    #[error(
3212        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
3213         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
3214         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
3215         `:membros :versao` carry; the lacre pipeline resolves all three \
3216         through the same parser)"
3217    )]
3218    ChildVersaoInvalid {
3219        caixa: String,
3220        versao: String,
3221        reason: String,
3222    },
3223    #[error(
3224        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
3225         child_spec.id per supervisor; duplicate children materialize as duplicate \
3226         ComputeUnits in the rendered chart, one silently overwriting the other)"
3227    )]
3228    DuplicateChildCaixa { caixa: String },
3229    #[error(
3230        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
3231         never its own child (the supervision tree is a DAG rooted at the supervisor; \
3232         OTP child specs reference distinct child processes). Since every :nome is a \
3233         globally-unique substrate identity, a child naming the supervisor's own :nome \
3234         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
3235         self-referential :children entry or rename it to the actual child caixa."
3236    )]
3237    ChildSupervisesSelf { caixa: String },
3238}
3239
3240// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
3241// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
3242// and [`validate_no_self_supervision`] onto one substrate primitive per
3243// typed variant — the sibling on `SupervisorError` of the four uniform-shape
3244// `LayoutError`-envelope constructor families the peer
3245// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
3246// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
3247// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
3248// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
3249// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
3250// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
3251// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
3252// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
3253// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
3254// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
3255// variants on `{ de, para }`) already at that discipline on the peer
3256// `AplicacaoError` envelopes.
3257//
3258// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
3259// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
3260// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
3261// self-supervision arm) opened the identical
3262// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
3263// the exact "same block re-inlined at every consumer" shape the PRIME
3264// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
3265// `AplicacaoError` families each closed on their sibling envelopes. The
3266// three variants share one `{ caixa: String }` shape, so the fold routes
3267// each wire-up site through one dispatch per typed variant.
3268//
3269// The macro below generates one static constructor per variant of shape
3270// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
3271// collapses onto one dispatch:
3272// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
3273// struct-literal on the same `&str` fixture. The uniform one-field
3274// construction (`caixa: caixa.to_string()`) is spelled once — inside the
3275// macro — rather than at every wire-up site. Every constructor is
3276// `#[must_use]` so a caller who mistakenly discards the constructed error
3277// trips a compile warning at the wire-up site.
3278//
3279// Every future consumer that wants to construct one of these three
3280// variants outside `SupervisorSpec::validate_children` /
3281// `validate_no_self_supervision` — a deferred
3282// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3283// webhook re-checking one added/renamed child, a future
3284// `feira validate --supervisor` per-caixa admission verb, a per-child
3285// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
3286// once dynamic-children graduate to a typed slot, a per-Supervisor
3287// overlay resolver rejecting a duplicate/self-supervising child against
3288// a cluster-local snapshot — now reaches each variant through one call
3289// rather than re-inlining the three-line struct-literal in lockstep
3290// with the three in-crate wire-up sites.
3291macro_rules! supervisor_caixa_only_ctors {
3292    ($($ctor:ident => $variant:ident),* $(,)?) => {
3293        impl SupervisorError {
3294            $(
3295                #[doc = concat!(
3296                    "Construct a [`SupervisorError::",
3297                    stringify!($variant),
3298                    "`] naming the offending `:children :caixa` (or ",
3299                    "supervisor `:nome`, on the self-supervision arm). ",
3300                    "Folds the uniform `Self::",
3301                    stringify!($variant),
3302                    " { caixa: caixa.to_string() }` one-field ",
3303                    "struct-literal onto one substrate primitive so ",
3304                    "every [`SupervisorSpec::validate_children`] / ",
3305                    "[`validate_no_self_supervision`] wire-up on this ",
3306                    "variant reads through one dispatch rather than the ",
3307                    "pre-lift open-coded struct-literal block."
3308                )]
3309                #[must_use]
3310                pub fn $ctor(caixa: &str) -> Self {
3311                    Self::$variant { caixa: caixa.to_string() }
3312                }
3313            )*
3314        }
3315    };
3316}
3317
3318supervisor_caixa_only_ctors! {
3319    empty_child_version => EmptyChildVersion,
3320    duplicate_child_caixa => DuplicateChildCaixa,
3321    child_supervises_self => ChildSupervisesSelf,
3322}
3323
3324// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
3325// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
3326// one substrate primitive per typed variant — the M2 supervisor-side siblings
3327// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
3328// already lifted through the sibling
3329// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
3330// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
3331// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
3332// String }` two-slot shape the peer seven-variant
3333// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
3334// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
3335// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
3336// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
3337// variant carries the `{ caixa: String, versao: String, reason: String }`
3338// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
3339// carries on the same `:versao` value-shape.
3340//
3341// Each of the two wire-up sites opened the same closure-shaped
3342// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
3343// [versao: child.versao_requirement().to_string(),] reason }` block inside
3344// the paired [`crate::render::require_valid_dns_1123_label`] and
3345// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
3346// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
3347// as a bug, on the same altitude the peer `AplicacaoError` /
3348// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
3349// families already closed on their sibling envelopes.
3350//
3351// The two `#[must_use]` inherent constructors below fold each wire-up onto
3352// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
3353// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
3354// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
3355// The uniform per-field `.to_string()` / `.into()` construction is spelled
3356// once — inside each ctor body — rather than at every wire-up site. The
3357// `reason: impl Into<String>` bound accepts both `&str` literals and
3358// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
3359// diagnostic shape at the lift, matching the peer
3360// [`aplicacao_field_reason_ctors!`] and
3361// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
3362// sibling envelopes.
3363//
3364// Every future consumer that wants to construct one of these two variants
3365// outside `SupervisorSpec::validate_children` — a deferred
3366// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
3367// re-checking one added/renamed child's `:caixa` or `:versao`, a future
3368// `feira validate --supervisor` per-caixa admission verb, a per-child
3369// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
3370// dynamic-children graduate to a typed slot, a per-Supervisor overlay
3371// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
3372// cluster-local snapshot — now reaches each variant through one call rather
3373// than re-inlining the per-shape struct-literal block in lockstep with the
3374// two in-crate wire-up sites.
3375impl SupervisorError {
3376    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
3377    /// offending `:children :caixa` value under the given `reason`. Folds
3378    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
3379    /// reason: reason.into() }` two-slot struct-literal onto one substrate
3380    /// primitive so every wire-up on this variant reads through one
3381    /// dispatch, matching the peer
3382    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
3383    /// sibling `AplicacaoError { caixa: String, reason: String }`
3384    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
3385    /// outputs through the `impl Into<String>` bound.
3386    #[must_use]
3387    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
3388        Self::ChildCaixaInvalid {
3389            caixa: caixa.to_string(),
3390            reason: reason.into(),
3391        }
3392    }
3393
3394    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
3395    /// offending `:children :caixa` and its `:versao` requirement under
3396    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
3397    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
3398    /// reason.into() }` three-slot struct-literal onto one substrate
3399    /// primitive so every wire-up on this variant reads through one
3400    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
3401    /// { caixa, versao, reason }` three-slot axis on the peer
3402    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
3403    /// and `format!(…)` outputs through the `impl Into<String>` bound.
3404    #[must_use]
3405    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
3406        Self::ChildVersaoInvalid {
3407            caixa: caixa.to_string(),
3408            versao: versao.to_string(),
3409            reason: reason.into(),
3410        }
3411    }
3412}
3413
3414// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
3415// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
3416// three bracket-arms — one struct-literal at the `:children`-empty
3417// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
3418// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
3419// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
3420// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
3421// [`crate::render::require_positive_canonical_bounded_duration`]
3422// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
3423// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
3424// primitive per typed variant, matching the sibling
3425// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
3426// variants on the same `{ <field>: Duration | u32 }` shape) at that
3427// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
3428// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
3429// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
3430// wire-up site through one dispatch per typed variant without a runtime-
3431// work delta.
3432//
3433// Each of the four wire-up sites opened the identical
3434// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
3435// exact "same block re-inlined at every consumer" shape the PRIME
3436// DIRECTIVE names as a bug, on the same altitude the peer
3437// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
3438// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
3439// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
3440// the fold routes each wire-up site through one dispatch per typed
3441// variant.
3442//
3443// The macro below generates one static constructor per variant of shape
3444// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
3445// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
3446// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
3447// fixture — as a direct call at the [`SupervisorSpec::validate`]
3448// `:children`-empty refusal, or as a bare function pointer in the
3449// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
3450// [`crate::render::require_positive_bounded_u32`] /
3451// [`crate::render::require_positive_canonical_bounded_duration`] gate
3452// carries — rather than the pre-lift open-coded one-line closure over
3453// the same one-field struct-literal. `const fn` preserves the `Copy`-
3454// pass-through's zero-runtime-work property verbatim. Every constructor
3455// is `#[must_use]` so a caller who mistakenly discards the constructed
3456// error trips a compile warning at the wire-up site.
3457//
3458// Every future consumer that wants to construct one of these four
3459// variants outside `SupervisorSpec::validate` — a deferred
3460// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3461// webhook re-checking one edited `:estrategia` / `:max-restarts` /
3462// `:restart-window` slot against the cap + canonical-form cascade, a
3463// future `feira validate --supervisor` per-caixa admission verb re-
3464// running the shape gates on demand, a per-Supervisor overlay resolver
3465// rejecting an author-supplied slot against a cluster-local snapshot —
3466// now reaches each variant through one call rather than re-inlining the
3467// per-shape struct-literal block in lockstep with the four in-crate
3468// wire-up sites.
3469macro_rules! supervisor_scalar_ctors {
3470    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
3471        impl SupervisorError {
3472            $(
3473                #[doc = concat!(
3474                    "Construct a [`SupervisorError::",
3475                    stringify!($variant),
3476                    "`] naming the offending per-`:supervisor` `",
3477                    stringify!($field),
3478                    "` scalar. Folds the uniform `Self::",
3479                    stringify!($variant),
3480                    " { ",
3481                    stringify!($field),
3482                    " }` one-field `Copy`-pass-through struct-literal onto ",
3483                    "one substrate primitive so every per-axis wire-up on ",
3484                    "this variant reads through one dispatch — as a direct ",
3485                    "call (`SupervisorError::",
3486                    stringify!($ctor),
3487                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
3488                    "the same `Copy`-`",
3489                    stringify!($ty),
3490                    "` fixture) or as a bare function pointer in the ",
3491                    "`impl FnOnce(",
3492                    stringify!($ty),
3493                    ") -> SupervisorError` bracket-closure slot every ",
3494                    "`crate::render::require_positive_bounded_*` / ",
3495                    "`crate::render::require_positive_canonical_bounded_*` ",
3496                    "gate carries — rather than the pre-lift open-coded ",
3497                    "one-line closure over the same one-field struct-",
3498                    "literal. `const fn` preserves the `Copy`-pass-through's ",
3499                    "zero-runtime-work property verbatim."
3500                )]
3501                #[must_use]
3502                pub const fn $ctor($field: $ty) -> Self {
3503                    Self::$variant { $field }
3504                }
3505            )*
3506        }
3507    };
3508}
3509
3510supervisor_scalar_ctors! {
3511    no_children => NoChildren { estrategia: RestartStrategy },
3512    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
3513    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
3514    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
3515}
3516
3517/// Shared duration string codec for the typed slots that take a
3518/// duration (`restart_window`, `MeshPolicy::timeout`,
3519/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
3520/// reuse it without duplicating the parser.
3521pub mod duration_codec {
3522    use super::Duration;
3523    use serde::{Deserializer, Serializer};
3524
3525    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
3526        // Route through the canonical [`crate::render::serialize_option_via_str`]
3527        // — the substrate-side single-owner primitive for the forward
3528        // arm of the typed-magnitude codec family. See its docstring
3529        // for the full sibling roster.
3530        crate::render::serialize_option_via_str(v, s, render)
3531    }
3532
3533    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
3534        // Route through the canonical [`crate::render::deserialize_option_via_str`]
3535        // — the substrate-side single-owner primitive for the reverse
3536        // arm of the typed-magnitude codec family. See its docstring
3537        // for the full sibling roster.
3538        crate::render::deserialize_option_via_str(d, parse)
3539    }
3540
3541    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
3542        // Paired whitespace-rejection arm — same canonical-form
3543        // render-determinism discipline as the peer
3544        // `limits::parse_byte_size` / `limits::parse_duration` /
3545        // `limits::parse_millicores` /
3546        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
3547        // byte-scan closes the WhatWG-conformant whitespace bytes
3548        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
3549        // `char::is_whitespace` scan closes the strictly-complementary
3550        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
3551        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
3552        // codepoints) that `str::trim` at parse entry silently strips.
3553        // Either drift class would round-trip through `render` to a
3554        // *different* canonical form on next emit — breaking the
3555        // THEORY.md Part V render-determinism contract on three typed-
3556        // duration slots at once (`:supervisor :restart-window`,
3557        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
3558        // via the shared codec.
3559        //
3560        // Routed through the lifted [`crate::render::reject_whitespace`]
3561        // primitive — the substrate-side single-owner paired-arm gate
3562        // every typed-magnitude codec in caixa-core shares.
3563        crate::render::reject_whitespace::<String, _, _>(
3564            s,
3565            |b| {
3566                format!(
3567                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
3568                 authoring form for the typed duration slots routed through this shared codec \
3569                 (`:supervisor :restart-window`, `:politicas :timeout`, \
3570                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3571                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
3572                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
3573                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
3574                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
3575                 Part V render-determinism contract every typed slot carries. Strip every \
3576                 whitespace byte (write `\"30s\"` verbatim)"
3577                )
3578            },
3579            |ch| {
3580                format!(
3581                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
3582                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
3583                 duration slots routed through this shared codec (`:supervisor \
3584                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
3585                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
3586                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
3587                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
3588                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
3589                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
3590                 `White_Space` property, strictly wider than the ASCII byte set) silently \
3591                 strips it at parse entry, and the value round-trips through `render` to \
3592                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
3593                 the THEORY.md Part V render-determinism contract every typed slot \
3594                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
3595                 verbatim with only ASCII bytes)",
3596                    cp = ch as u32
3597                )
3598            },
3599        )?;
3600        let s = s.trim();
3601        // Routed through the lifted
3602        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
3603        // the single-owner split every ASCII-alphabetic-unit typed-
3604        // magnitude codec in caixa-core (`limits::parse_byte_size` /
3605        // `limits::parse_duration` / this shared duration codec) shares.
3606        // See its docstring for the full sibling roster on the same
3607        // primitive altitude.
3608        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
3609        let num_trim = num_part.trim();
3610        // The canonical authoring form for every typed slot routed
3611        // through this shared codec — `:supervisor :restart-window`,
3612        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
3613        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
3614        // non-negative integer with no decimal point and no leading
3615        // sign, so the parser's accepted set must match for
3616        // serialize/deserialize to round-trip without canonical-form
3617        // drift. Until this gate landed the parser accepted any
3618        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
3619        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
3620        // tripped the value to a *different* canonical string on the
3621        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
3622        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
3623        // — breaking the THEORY.md Part V render-determinism contract
3624        // on three typed slots at once. Same canonical-form discipline
3625        // `crate::limits::parse_duration` (818dd38, the immediate
3626        // predecessor on the peer `:limits :wall-clock` codec) applies;
3627        // this gate lifts the discipline onto the shared codec that
3628        // backs the remaining three typed-duration slots in caixa-core.
3629        //
3630        // Strict canonical form: every byte of the magnitude is an
3631        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
3632        // inputs the gate distinguishes "non-canonical-but-numeric"
3633        // (parses as f64 or i64 — surfaced with a self-locating
3634        // diagnostic naming the canonical authoring form, the
3635        // round-trip drift each rejected shape would produce on first
3636        // serialize, and the canonical-form remediation) from
3637        // "garbage" (parses as neither — surfaced with the existing
3638        // narrower "bad duration magnitude" wording so its diagnostic
3639        // shape remains stable for the parser-shape footgun case).
3640        // The pre-existing `num < 0.0` arm is now unreachable — the
3641        // digit-only gate strictly precedes magnitude parsing, and a
3642        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
3643        // non-canonical-but-numeric branch with the `-30` named
3644        // verbatim in the diagnostic rather than the prior
3645        // value-laundered "negative duration in \"-30s\"" wording.
3646        //
3647        // Routed through the lifted
3648        // [`crate::render::is_digit_only_magnitude`] predicate — the
3649        // same source of truth the four peer typed-magnitude codec
3650        // sites share.
3651        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
3652        if !digit_only {
3653            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
3654            if numeric {
3655                return Err(format!(
3656                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
3657                     canonical authoring form for the typed duration slots routed through \
3658                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3659                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3660                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
3661                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
3662                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
3663                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
3664                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
3665                     THEORY.md Part V render-determinism contract every typed slot carries. \
3666                     Pick an integer magnitude in the unit that divides cleanly (write \
3667                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
3668                ));
3669            }
3670            return Err(format!("bad duration magnitude in {s:?}"));
3671        }
3672        // Leading-zero arm — peer with the `rate_limit_codec` leading-
3673        // zero arm (4f46830) on the same canonical-form render-
3674        // determinism axis. The digit-only gate accepts `"030s"`,
3675        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
3676        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
3677        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
3678        // *different* canonical string on the next emit, breaking the
3679        // THEORY.md Part V render-determinism contract the same way
3680        // `"+30s"` did before the leading-`+` arm landed. The single-
3681        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
3682        // losslessly through `render` (`render(Duration::ZERO)` emits
3683        // `"0s"`) — the downstream semantic-zero gates (e.g.
3684        // `SupervisorError::ZeroRestartWindow` on
3685        // `:supervisor :restart-window`,
3686        // `AplicacaoError::PolicyTimeoutZero` /
3687        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
3688        // duration slots) refuse zero-magnitude authoring at the typed-
3689        // validate layer above, so the single-byte `"0"` stays in the
3690        // accepted set at this codec layer and the diagnostic
3691        // partitioning between canonical-form drift (this arm) and
3692        // semantic-zero (the downstream gates) remains stable.
3693        // Peer with the future leading-zero arms on the two remaining
3694        // typed-magnitude codecs the trajectory acknowledges:
3695        // `limits::parse_duration` backing `:limits :wall-clock`,
3696        // `limits::parse_byte_size` backing `:limits :memory` — each
3697        // carries the same canonical-form-drift class today; this
3698        // gate lands the discipline on the shared duration codec
3699        // first because the `rate_limit_codec` predecessor on the
3700        // same canonical-form-drift axis is the closest peer on the
3701        // trajectory.
3702        //
3703        // Routed through the lifted
3704        // [`crate::render::is_leading_zero_padded_magnitude`]
3705        // predicate — the same source of truth the four peer
3706        // typed-magnitude codec sites share.
3707        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
3708            return Err(format!(
3709                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
3710                 canonical authoring form for the typed duration slots routed through \
3711                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3712                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3713                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
3714                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
3715                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
3716                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
3717                 serialize — breaking the THEORY.md Part V render-determinism contract \
3718                 every typed slot carries. Strip the leading zeros (write \
3719                 `\"30s\"` instead of `\"030s\"`)"
3720            ));
3721        }
3722        // The digit-only gate guarantees every byte is `[0-9]`, and
3723        // the leading-zero arm above guarantees the magnitude is
3724        // either the single byte `"0"` or starts with `[1-9]`, so
3725        // the only way `u64::from_str` can fail here is overflow (the
3726        // magnitude exceeds `u64::MAX`). Surface that with an
3727        // overflow-shaped wording so the diagnostic names the offending
3728        // magnitude verbatim rather than collapsing onto the
3729        // non-canonical arm. The codec now operates on `u64` end-to-end
3730        // — every accepted magnitude is integer-exact; no f64 mantissa
3731        // drift between author-supplied magnitude and the consumer's
3732        // `Duration` value. Same shape `crate::limits::parse_duration`
3733        // (818dd38) carries on the peer `:limits :wall-clock` axis.
3734        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
3735            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
3736        })?;
3737        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
3738        // unit-arm dispatch through the canonical
3739        // [`crate::render::duration_from_integer_magnitude_and_unit`]
3740        // primitive — the substrate-side single-owner unit-dispatch
3741        // table every typed-duration codec in caixa-core routes
3742        // through (peer: `crate::limits::parse_duration` backing
3743        // `:limits :wall-clock`). Every unit conversion is integer-
3744        // exact for an integer magnitude; overflow surfaces via the
3745        // typed `DurationUnitError::Overflow { multiplier }`
3746        // discriminant so this arm reconstructs the pre-lift
3747        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
3748        // wording verbatim from `num` / `unit_trim` / the returned
3749        // `multiplier`, and the unknown-unit arm reconstructs the
3750        // pre-lift `"unknown duration unit \"<other>\""` wording from
3751        // the caller-scoped `unit_trim`. Load-bearing pinned by
3752        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
3753        let unit_trim = unit.trim();
3754        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
3755            |e| match e {
3756                crate::render::DurationUnitError::Overflow { multiplier } => format!(
3757                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
3758                ),
3759                crate::render::DurationUnitError::UnknownUnit => {
3760                    format!("unknown duration unit {unit_trim:?}")
3761                }
3762            },
3763        )?;
3764        Ok(dur)
3765    }
3766
3767    /// Render a [`Duration`] in the canonical pleme-io duration string
3768    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
3769    /// caixa typed-duration slot serializes to and the same form K8s
3770    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
3771    /// EnvoyConfig per-route timeouts both expect (an integer
3772    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
3773    /// `+`). Lifted to `pub` so caixa-side renderers
3774    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
3775    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
3776    /// emitter, the future caixa-otel collector pipeline emitter) can
3777    /// consume the same canonical formatter without re-inlining the
3778    /// magnitude/unit decision tree (and inheriting the same drift
3779    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
3780    /// downstream apply-time parsing in non-obvious ways).
3781    pub fn render(d: Duration) -> String {
3782        let total_ms = d.as_millis();
3783        if total_ms == 0 {
3784            return "0s".into();
3785        }
3786        if total_ms.is_multiple_of(3600 * 1000) {
3787            return format!("{}h", total_ms / (3600 * 1000));
3788        }
3789        if total_ms.is_multiple_of(60 * 1000) {
3790            return format!("{}m", total_ms / (60 * 1000));
3791        }
3792        if total_ms.is_multiple_of(1000) {
3793            return format!("{}s", total_ms / 1000);
3794        }
3795        format!("{total_ms}ms")
3796    }
3797
3798    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
3799    ///
3800    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
3801    /// largest divisor unit, so any sub-millisecond residue
3802    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
3803    /// §V.2.7 render-determinism contract:
3804    ///
3805    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
3806    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
3807    ///     `1_000_000` ns ≠ original `1_500_000` ns;
3808    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
3809    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
3810    ///     on every typed-`Duration` slot then rejects on re-validate.
3811    ///
3812    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
3813    /// the codec's round-trippable accepted set lives in exactly one place —
3814    /// every typed-`Duration` slot that routes through this shared codec
3815    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
3816    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
3817    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
3818    /// every typed-`Duration` slot whose own codec shares the same
3819    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
3820    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
3821    /// pair) calls this predicate from its `validate()` to bracket the
3822    /// accepted set against the codec's accepted set, structurally. Drift
3823    /// between the codec's granularity and any typed slot's accepted set is
3824    /// then a single-source-of-truth edit at this predicate rather than a
3825    /// silent round-trip break the next consumer discovers at apply time.
3826    ///
3827    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
3828    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
3829    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
3830    /// family — same "typed-slot's valid set matches its codec's accepted
3831    /// set, structurally" discipline carried at the codec layer.
3832    #[must_use]
3833    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
3834        d.subsec_nanos().is_multiple_of(1_000_000)
3835    }
3836}
3837
3838/// Required-Duration variant for fields that aren't Option<Duration>.
3839pub mod duration_codec_required {
3840    use super::Duration;
3841    use serde::{Deserialize, Deserializer, Serializer};
3842
3843    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
3844        s.serialize_str(&super::duration_codec::render(*v))
3845    }
3846
3847    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
3848        let s = String::deserialize(d)?;
3849        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
3850    }
3851}
3852
3853#[cfg(test)]
3854mod tests {
3855    use super::*;
3856
3857    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
3858        ChildSpec {
3859            caixa: name.into(),
3860            versao: ver.into(),
3861            restart,
3862        }
3863    }
3864
3865    #[test]
3866    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
3867        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
3868        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
3869        // posture. Each accessor projects the per-`:children :caixa`
3870        // / per-`:children :versao` [`String`] storage through the
3871        // `pub const fn` [`String::as_str`] (const-stable since Rust
3872        // 1.87, well within the workspace MSRV) — any future
3873        // accidental downgrade to non-`const` fails the corresponding
3874        // `<name>_via_const_fn` wrapper at caixa-core build time with
3875        // E0015 (`cannot call non-const method`), strictly stronger
3876        // than a runtime `assert!`. Sibling of the peer
3877        // per-M2/M3/universal-axis `String → &str` scalar-accessor
3878        // family pins on the sibling `const`-eval-surface passes
3879        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
3880        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
3881        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
3882        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
3883        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
3884        // [`crate::aplicacao::Entrada::destination`] at the M3
3885        // ingress axis,
3886        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
3887        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
3888        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
3889        // axis, and the per-`:contratos`
3890        // [`crate::aplicacao::WitContract::source`] /
3891        // [`crate::aplicacao::WitContract::destination`] /
3892        // [`crate::aplicacao::WitContract::world_ref`] trio the
3893        // sibling pin at 279823b already anchors).
3894        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
3895            c.nome()
3896        }
3897        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
3898            c.versao_requirement()
3899        }
3900        for (caixa, versao) in [
3901            ("worker-a", "^0.1"),
3902            ("worker-b", "~0.2.3"),
3903            ("collector", "*"),
3904        ] {
3905            let c = child(caixa, versao, RestartPolicy::Permanent);
3906            assert_eq!(nome_via_const_fn(&c), c.nome());
3907            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
3908            assert_eq!(c.nome(), caixa);
3909            assert_eq!(c.versao_requirement(), versao);
3910        }
3911    }
3912
3913    #[test]
3914    fn supervisor_children_slice_return_accessor_is_const_fn() {
3915        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
3916        // `const`-eval-surface posture. The accessor destructures the
3917        // per-`:children` `Vec<ChildSpec>` storage through the
3918        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
3919        // 1.66, well within the workspace MSRV) — any future
3920        // accidental downgrade to non-`const` fails
3921        // `children_via_const_fn` at caixa-core build time with E0015
3922        // (`cannot call non-const method`), strictly stronger than a
3923        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
3924        // `Vec → &[T]` slice-return accessor family pin
3925        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
3926        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
3927        // per-`:membros` / per-`:contratos` slice-return axes, and of
3928        // the peer M2 upgrade-appup axis pin
3929        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
3930        // on the per-`:upgrade-from :instructions` slice-return axis.
3931        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
3932            s.children()
3933        }
3934        // Sweep both the empty-children (leaf-supervisor with no
3935        // static children — the `SimpleOneForOne` dynamic-child
3936        // arm's canonical shape) and the populated-children
3937        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
3938        // arm's canonical shape) axes so the accessor carries a
3939        // const-dispatch pin on both arms.
3940        let s_empty = SupervisorSpec {
3941            estrategia: RestartStrategy::SimpleOneForOne,
3942            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3943            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3944            children: vec![],
3945        };
3946        assert!(children_via_const_fn(&s_empty).is_empty());
3947        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
3948        let s_full = SupervisorSpec {
3949            estrategia: RestartStrategy::OneForOne,
3950            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3951            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3952            children: vec![
3953                child("worker-a", "^0.1", RestartPolicy::Permanent),
3954                child("worker-b", "~0.2.3", RestartPolicy::Transient),
3955                child("collector", "*", RestartPolicy::Temporary),
3956            ],
3957        };
3958        assert_eq!(children_via_const_fn(&s_full).len(), 3);
3959        assert_eq!(children_via_const_fn(&s_full), s_full.children());
3960    }
3961
3962    #[test]
3963    fn default_has_one_for_one_and_5_restarts_in_60s() {
3964        let s = SupervisorSpec::default();
3965        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
3966        assert_eq!(s.max_restarts, 5);
3967        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
3968        assert!(s.children.is_empty());
3969    }
3970
3971    #[test]
3972    fn validate_one_for_one_requires_children() {
3973        let mut s = SupervisorSpec::default();
3974        s.children = vec![];
3975        assert!(matches!(
3976            s.validate().unwrap_err(),
3977            SupervisorError::NoChildren { .. }
3978        ));
3979        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
3980        s.validate().unwrap();
3981    }
3982
3983    #[test]
3984    fn validate_simple_one_for_one_forbids_static_children() {
3985        let mut s = SupervisorSpec {
3986            estrategia: RestartStrategy::SimpleOneForOne,
3987            ..SupervisorSpec::default()
3988        };
3989        s.children
3990            .push(child("w", "^0.1", RestartPolicy::Permanent));
3991        assert_eq!(
3992            s.validate().unwrap_err(),
3993            SupervisorError::SimpleOneForOneWithStaticChildren
3994        );
3995        s.children.clear();
3996        s.validate().unwrap();
3997    }
3998
3999    #[test]
4000    fn validate_rejects_zero_max_restarts() {
4001        let s = SupervisorSpec {
4002            max_restarts: 0,
4003            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4004            ..SupervisorSpec::default()
4005        };
4006        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
4007    }
4008
4009    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
4010    //
4011    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
4012    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
4013    // `:supervisor :max-restarts` axis — both fields are "trip the
4014    // next-higher protection layer after N events in a rolling window"
4015    // counters with identical degenerate-at-the-high-end shape, so the
4016    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
4017    // exactly as it lies in `1..=1000` on the breaker side.
4018
4019    #[test]
4020    fn validate_rejects_max_restarts_above_cap() {
4021        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
4022        // 1` is structurally one past the cap and silently passed
4023        // validate on every pre-gate codebase because the typed slot's
4024        // only check was the zero-floor arm. The no-op-supervisor vector
4025        // only surfaced at the runtime substrate (Erlang/OTP
4026        // MaxIntensity/Period ratio, the future wasm-operator's
4027        // per-supervisor restart-intensity counter) far from the source
4028        // caixa.lisp with no field naming the offending supervisor.
4029        let s = SupervisorSpec {
4030            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4031            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4032            ..SupervisorSpec::default()
4033        };
4034        assert_eq!(
4035            s.validate().unwrap_err(),
4036            SupervisorError::MaxRestartsExceedsCap {
4037                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4038            }
4039        );
4040    }
4041
4042    #[test]
4043    fn validate_rejects_max_restarts_far_above_cap() {
4044        // The `u32::MAX` worst case — the four-billion-restart
4045        // threshold a typo (`:max-restarts 4294967295`) or a
4046        // struct-literal copy-paste lands in the slot. Pin the cap
4047        // arm's coverage explicitly across the full `u32` overflow so
4048        // a future relaxation that drops the upper bound surfaces
4049        // here. Same shape every other typed-cap arm on this surface
4050        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
4051        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
4052        let s = SupervisorSpec {
4053            max_restarts: u32::MAX,
4054            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4055            ..SupervisorSpec::default()
4056        };
4057        assert_eq!(
4058            s.validate().unwrap_err(),
4059            SupervisorError::MaxRestartsExceedsCap {
4060                max_restarts: u32::MAX,
4061            }
4062        );
4063    }
4064
4065    #[test]
4066    fn validate_accepts_max_restarts_at_cap() {
4067        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
4068        // must validate. The cap is inclusive on the top edge,
4069        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
4070        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
4071        // discipline on the sibling capped axes. Pin the boundary
4072        // explicitly so a future off-by-one tightening
4073        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
4074        // here as a test failure rather than a silent contract
4075        // narrowing.
4076        let s = SupervisorSpec {
4077            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
4078            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4079            ..SupervisorSpec::default()
4080        };
4081        s.validate()
4082            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
4083    }
4084
4085    #[test]
4086    fn validate_accepts_max_restarts_typical_values() {
4087        // The documented production-playbook band positive-control
4088        // sweep — every value Erlang/OTP / Elixir / Riak Core /
4089        // RabbitMQ recommend (1..=100) must pass, plus a sweep
4090        // through the hyperscale band (200, 500, 1000) the cap
4091        // accepts. Pin the inclusive validated set explicitly so a
4092        // future tightening of the ceiling surfaces here.
4093        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
4094            let s = SupervisorSpec {
4095                max_restarts: n,
4096                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4097                ..SupervisorSpec::default()
4098            };
4099            s.validate()
4100                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
4101        }
4102    }
4103
4104    #[test]
4105    fn zero_max_restarts_takes_precedence_over_cap() {
4106        // The cross-arm ordering pin: `0` is structurally outside
4107        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
4108        // (cap), but the zero-floor diagnostic is the more
4109        // self-locating one (it directly names the counter-axis
4110        // remediation), so the validate gate must fire on zero first.
4111        // Same shape every other zero-then-shape ordering on this
4112        // surface uses (PolicyRetriesZero then
4113        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
4114        // PolicyBreakerMaxFailuresExceedsCap).
4115        let s = SupervisorSpec {
4116            max_restarts: 0,
4117            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4118            ..SupervisorSpec::default()
4119        };
4120        assert_eq!(
4121            s.validate().unwrap_err(),
4122            SupervisorError::ZeroMaxRestarts,
4123            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
4124        );
4125    }
4126
4127    #[test]
4128    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
4129        // The cross-arm ordering pin between the cap and the sibling
4130        // `:restart-window` gates (zero-window, canonical-window). A
4131        // supervisor carrying both an over-cap `max_restarts` AND a
4132        // structurally invalid window (zero, sub-ms) must surface the
4133        // cap diagnostic first — the cap arm is wired immediately
4134        // after the zero-restart arm and strictly before the window
4135        // arms, so the offending value the diagnostic names matches
4136        // the order the author would discover the gates by reading
4137        // top-to-bottom through `SupervisorSpec::validate`. Pin the
4138        // order so a future refactor that reorders the arms surfaces
4139        // here as a test failure rather than a silent diagnostic
4140        // regression. Peer of
4141        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
4142        // on the sibling `:politicas :circuit-breaker` slot.
4143        let s = SupervisorSpec {
4144            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4145            restart_window: Some(Duration::ZERO),
4146            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4147            ..SupervisorSpec::default()
4148        };
4149        assert_eq!(
4150            s.validate().unwrap_err(),
4151            SupervisorError::MaxRestartsExceedsCap {
4152                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4153            },
4154            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4155        );
4156    }
4157
4158    #[test]
4159    fn max_restarts_cap_diagnostic_carries_offending_value() {
4160        // The diagnostic-shape pin: the offending `u32` is carried
4161        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
4162        // variant so the surfaced error message names the value the
4163        // author wrote (`":supervisor :max-restarts (50000) exceeds the
4164        // supervisor-policy ceiling …"`), not just the cap. Same
4165        // self-locating diagnostic shape every other typed-cap arm on
4166        // this surface carries
4167        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
4168        // the offending failure count verbatim,
4169        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
4170        // retries count verbatim).
4171        let s = SupervisorSpec {
4172            max_restarts: 50_000,
4173            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4174            ..SupervisorSpec::default()
4175        };
4176        let err = s.validate().unwrap_err();
4177        assert!(
4178            matches!(
4179                err,
4180                SupervisorError::MaxRestartsExceedsCap {
4181                    max_restarts: 50_000
4182                }
4183            ),
4184            "got {err:?}"
4185        );
4186        let msg = err.to_string();
4187        assert!(
4188            msg.contains("50000"),
4189            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
4190        );
4191    }
4192
4193    #[test]
4194    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
4195        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
4196        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
4197        // half of Learn You Some Erlang's worker-supervisor default,
4198        // sibling of the `60s` `Period` half that the paired
4199        // [`Default for SupervisorSpec`] impl already pins on the
4200        // sibling `restart_window` axis. Pinning the literal here
4201        // surfaces a future rebrand (a tightening to Elixir's `3`,
4202        // a widening to a per-cluster overlay the operator pins
4203        // through a future `:max-restarts-overrides` slot) as a
4204        // deliberate test edit, not a silent contract migration.
4205        // Peer of the sibling
4206        // [`supervisor_max_restarts_cap_pins_canonical_value`]
4207        // upper-bracket pin on the same axis.
4208        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
4209    }
4210
4211    #[test]
4212    fn default_max_restarts_helper_routes_through_lifted_default() {
4213        // Composition pin: the private `default_max_restarts()`
4214        // serde-`#[serde(default = "…")]` helper on
4215        // [`SupervisorSpec::max_restarts`] must route through the
4216        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4217        // typed `pub const` rather than a raw `5` literal. Prior to
4218        // the lift the helper carried an inline `5` with no compile-
4219        // time link back to the shared default, so the wire-format
4220        // author-omitted arm and the caixa-core
4221        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
4222        // arm could silently split on any future default rebrand.
4223        // Byte-parity against the lifted constant closes the split.
4224        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
4225    }
4226
4227    #[test]
4228    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
4229        // Composition pin: the [`Default for SupervisorSpec`] impl's
4230        // struct-literal `max_restarts` field must route through the
4231        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4232        // typed `pub const` (via the private helper this test's
4233        // sibling `default_max_restarts_helper_routes_through_lifted_default`
4234        // already pins onto the constant). Structurally: every
4235        // `SupervisorSpec::default()` call must yield a
4236        // `max_restarts` field byte-equal to the lifted constant
4237        // (the two paired defaults — the serde-side wire-format arm
4238        // and the struct-literal default arm — cannot silently split
4239        // on any future default rebrand). Peer of the sibling
4240        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
4241        // — this pin closes the byte-parity arm on the two paired
4242        // altitude entry points onto the shared substrate constant.
4243        assert_eq!(
4244            SupervisorSpec::default().max_restarts(),
4245            SUPERVISOR_MAX_RESTARTS_DEFAULT,
4246        );
4247    }
4248
4249    #[test]
4250    fn supervisor_restart_window_default_pins_otp_canonical_value() {
4251        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
4252        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
4253        // Learn You Some Erlang's worker-supervisor default, paired
4254        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
4255        // `MaxIntensity` half this constant is the sliding-window
4256        // denominator of on the same `MaxIntensity / Period`
4257        // restart-intensity ratio. Pinning the literal here surfaces a
4258        // future coherent rebrand of the paired default (Elixir's
4259        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
4260        // the operator pins through a future
4261        // `:restart-window-overrides` slot) as a deliberate test edit,
4262        // not a silent contract migration. Peer of the sibling
4263        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
4264        // paired-half pin on the same OTP-canonical default and the
4265        // [`supervisor_restart_window_cap_pins_canonical_value`]
4266        // upper-bracket pin on the same axis.
4267        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
4268    }
4269
4270    #[test]
4271    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
4272        // Composition pin: the [`Default for SupervisorSpec`] impl's
4273        // struct-literal `restart_window` field must route through the
4274        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4275        // typed `pub const` rather than a raw
4276        // `Duration::from_secs(60)` literal. Prior to this lift the
4277        // paired `{intensity, 5, 60}` OTP-canonical default was split
4278        // across two altitudes with no compile-time link between the
4279        // halves — the `MaxIntensity` half rode through the lifted
4280        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
4281        // `Period` half rode as an open-coded literal at the
4282        // composition site, so a future coherent rebrand of the paired
4283        // canonical would have had to migrate one half through the
4284        // constant and the other through a raw literal in lockstep.
4285        // Byte-parity against the lifted constant on the `Period` half
4286        // closes the split — the paired OTP-canonical default now
4287        // migrates as one unit on any future axis change. Peer of the
4288        // sibling
4289        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4290        // byte-parity pin on the paired `MaxIntensity` half.
4291        assert_eq!(
4292            SupervisorSpec::default().restart_window(),
4293            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4294        );
4295    }
4296
4297    #[test]
4298    fn supervisor_estrategia_default_pins_otp_canonical_value() {
4299        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
4300        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
4301        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
4302        // canonical default, paired with the sibling
4303        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
4304        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
4305        // this constant is the strategy discriminator of on the same
4306        // OTP-canonical worker-supervisor default. Pinning the arm here
4307        // surfaces a future coherent rebrand of the paired triple (Elixir's
4308        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
4309        // intensity/period axes leaving this strategy arm untouched, an OTP
4310        // `rest_for_one` widening once the substrate discovers startup-
4311        // order-coupled child cohorts as the more common worker-supervisor
4312        // shape, a per-cluster overlay the operator pins through a future
4313        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
4314        // supervision-canary roadmap acknowledges) as a deliberate test
4315        // edit, not a silent contract migration. Peer of the sibling
4316        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
4317        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4318        // paired-half pins on the same OTP-canonical default.
4319        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
4320    }
4321
4322    #[test]
4323    fn restart_strategy_default_routes_through_lifted_default() {
4324        // Composition pin: the [`Default for RestartStrategy`] impl's
4325        // return arm must route through the substrate-canonical
4326        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
4327        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
4328        // an inline `Self::OneForOne` with no compile-time link back to
4329        // the shared OTP-canonical `one_for_one` strategy the paired
4330        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
4331        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
4332        // `.unwrap_or_default()` (now
4333        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
4334        // so a future rebrand of the OTP-canonical strategy default (an
4335        // OTP `rest_for_one` widening once the substrate discovers
4336        // startup-order-coupled child cohorts as the more common worker-
4337        // supervisor shape, a per-cluster overlay the operator pins
4338        // through a future `:estrategia-overrides` slot) would have had to
4339        // be threaded through the `Default` impl and the two peer routes
4340        // in lockstep or the three consumers would silently split. Byte-
4341        // parity against the lifted constant closes the split. Peer of
4342        // the sibling
4343        // [`default_max_restarts_helper_routes_through_lifted_default`] +
4344        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4345        // composition pins on the paired `MaxIntensity` + `Period` halves.
4346        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
4347    }
4348
4349    #[test]
4350    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
4351        // Composition pin: the [`Default for SupervisorSpec`] impl's
4352        // struct-literal `estrategia` field must route through the
4353        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
4354        // `pub const` (either directly, or via the
4355        // [`RestartStrategy::default`] impl that the sibling
4356        // `restart_strategy_default_routes_through_lifted_default` pin
4357        // already routes onto the constant). Structurally: every
4358        // `SupervisorSpec::default()` call must yield an `estrategia`
4359        // field byte-equal to the lifted constant (the three paired
4360        // defaults — the [`Default for RestartStrategy`] impl arm, the
4361        // struct-literal default arm here, and the
4362        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
4363        // silently split on any future default rebrand). Peer of the
4364        // sibling
4365        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4366        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4367        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
4368        // of the same `SupervisorSpec::default()` composed altitude.
4369        assert_eq!(
4370            SupervisorSpec::default().estrategia(),
4371            SUPERVISOR_ESTRATEGIA_DEFAULT,
4372        );
4373    }
4374
4375    #[test]
4376    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
4377        // Composition pin: the [`Default for SupervisorSpec`] impl must
4378        // route through the substrate-canonical
4379        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
4380        // rather than a re-hand-authored struct-literal cascade. Sharpens
4381        // the sibling per-arm
4382        // `supervisor_spec_default_*_routes_through_lifted_default` pins
4383        // from a per-field lift into a whole-struct one-source-of-truth
4384        // pin — the derived-until-now [`Default::default`] and the
4385        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
4386        // construction, not by coincidence.
4387        //
4388        // A future extension of the OTP-canonical baseline (a fifth
4389        // `restart_intensity` field the Erlang/OTP `#supervisor` record
4390        // grows, a per-child-cohort split of the `restart_window` /
4391        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
4392        // CR materializer's admission-time overlay pass) reaches both
4393        // paths through exactly one edit on
4394        // [`SupervisorSpec::otp_canonical`] — the derived path could
4395        // silently disagree with the constructor's shape on any new
4396        // field whose [`Default::default`] resolves to a different arm
4397        // than the OTP-canonical baseline the constructor names, while
4398        // this delegated impl reaches the constructor directly and
4399        // picks up every future extension by construction.
4400        //
4401        // Fourth peer on the M2 / M3 typed-slot-spec
4402        // [`Default`]-through-const-ctor fold family — sibling of the
4403        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
4404        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
4405        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
4406        // (91641a4), and [`crate::BehaviorSpec`]
4407        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
4408        // per-`Option`-only-typed-slot folds — extended here onto the
4409        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
4410        // is not "everything `None`" but the Erlang/OTP-canonical
4411        // `{one_for_one, 5, 60}` worker-supervisor triple.
4412        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
4413    }
4414
4415    #[test]
4416    fn supervisor_spec_otp_canonical_byte_equals_default() {
4417        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
4418        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
4419        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
4420        // pin already asserts against the [`Default::default`] path.
4421        // Sharpens the pair-invariant into a per-constructor pin so a
4422        // future extension of [`SupervisorSpec`] with a fifth field
4423        // whose OTP-canonical shape is non-`Default::default`-equivalent
4424        // trips at caixa-core test time rather than at a downstream
4425        // consumer that composed [`SupervisorSpec::otp_canonical`] with
4426        // [`SupervisorSpec::validate`] as its "canonical baseline
4427        // seed".
4428        let canonical = SupervisorSpec::otp_canonical();
4429        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
4430        assert_eq!(canonical.max_restarts, 5);
4431        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
4432        assert!(canonical.children.is_empty());
4433    }
4434
4435    #[test]
4436    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
4437        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
4438        // remain callable from a `const`-bound position so downstream
4439        // `const`-context callers wanting a canonical OTP-baseline seed
4440        // can construct one at compile time without runtime dispatch on
4441        // the derived [`Default::default`]. Peer of the sibling
4442        // `pub const fn` [`crate::LimitsSpec::empty`] /
4443        // [`crate::aplicacao::MeshPolicy::empty`] /
4444        // [`crate::BehaviorSpec::empty`] constructors on the sibling
4445        // typed-slot-spec `pub const fn` axis. If a future edit breaks
4446        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
4447        // (a non-`const` field-default helper, a non-`const`-stable
4448        // container type promotion), this evaluation fails at
4449        // build time on this file rather than at a downstream
4450        // `const`-context call site.
4451        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
4452        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
4453        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
4454        assert_eq!(
4455            CANONICAL.restart_window,
4456            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4457        );
4458        assert!(CANONICAL.children.is_empty());
4459    }
4460
4461    #[test]
4462    fn supervisor_child_restart_default_pins_otp_canonical_value() {
4463        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
4464        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
4465        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
4466        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
4467        // half of the same OTP-shape supervisor-tree default set whose
4468        // per-`:supervisor` halves the sibling
4469        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
4470        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
4471        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
4472        // arm here surfaces a future rebrand of the per-child default (an
4473        // OTP-`transient` widening once the substrate discovers clean-
4474        // completion-aware children as the more common child shape, a
4475        // per-cluster overlay the operator pins through a future
4476        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
4477        // supervision-canary roadmap acknowledges) as a deliberate test
4478        // edit, not a silent contract migration. Peer of the sibling
4479        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
4480        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
4481        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4482        // value pins on the per-`:supervisor` halves.
4483        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
4484    }
4485
4486    #[test]
4487    fn restart_policy_default_routes_through_lifted_default() {
4488        // Composition pin: the [`Default for RestartPolicy`] impl's return
4489        // arm must route through the substrate-canonical
4490        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
4491        // than a raw `Self::Permanent` arm. Prior to the lift the impl
4492        // carried an inline `Self::Permanent` with no compile-time link
4493        // back to the OTP-shape supervisor-tree default set whose three
4494        // per-`:supervisor` halves already rode through lifted constants
4495        // — so a future coherent rebrand of the set would have had to
4496        // migrate three halves through typed constants and this fourth
4497        // through a raw enum arm in lockstep or the supervisor-level and
4498        // child-level defaults would silently drift apart. Byte-parity
4499        // against the lifted constant closes the split. Peer of the
4500        // sibling
4501        // [`restart_strategy_default_routes_through_lifted_default`]
4502        // composition pin on the per-`:supervisor` `:estrategia` axis.
4503        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
4504    }
4505
4506    #[test]
4507    fn child_spec_serde_default_restart_routes_through_lifted_default() {
4508        // Composition pin: the serde-side `#[serde(default)]` on
4509        // [`ChildSpec::restart`] — the wire-format author-omitted
4510        // `:children :restart` arm — must resolve onto the substrate-
4511        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
4512        // (via the [`Default for RestartPolicy`] impl the sibling
4513        // `restart_policy_default_routes_through_lifted_default` pin
4514        // already routes onto the constant). Structurally: a `ChildSpec`
4515        // deserialized from a payload that omits the `restart` key must
4516        // yield a `restart` field byte-equal to the lifted constant, so
4517        // the wire-format author-omitted arm and the
4518        // [`RestartPolicy::default`] impl arm cannot silently split on any
4519        // future default rebrand. Peer of the sibling
4520        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
4521        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4522        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4523        // byte-parity pins on the per-`:supervisor` halves of the same
4524        // author-omitted-slot resolution surface.
4525        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
4526            .expect("ChildSpec must deserialize with the restart key omitted");
4527        assert_eq!(
4528            omitted.restart(),
4529            SUPERVISOR_CHILD_RESTART_DEFAULT,
4530            "an author-omitted :children :restart slot must degrade onto \
4531             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
4532             {:?}, expected {:?})",
4533            omitted.restart(),
4534            SUPERVISOR_CHILD_RESTART_DEFAULT,
4535        );
4536    }
4537
4538    #[test]
4539    fn supervisor_max_restarts_cap_pins_canonical_value() {
4540        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
4541        // 1000 — the same ceiling the peer
4542        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
4543        // `:politicas :circuit-breaker :max-failures` axis (both are
4544        // "trip the next-higher protection layer after N events in a
4545        // rolling window" counters with identical
4546        // degenerate-at-the-high-end shape; uniform top edge so the
4547        // M4 CR materializers and the wasm-operator reconciler reach
4548        // for either field knowing the value is in `1..=1000`). Two
4549        // orders of magnitude above every documented Erlang/OTP /
4550        // Elixir / Riak Core / RabbitMQ production-playbook
4551        // recommendation band and below the clearly-pathological
4552        // "effectively no escalation" floor (10_000, 100_000,
4553        // u32::MAX). Pinning the literal value here surfaces a future
4554        // drift (a relaxation to 10_000, a tightening to 100) as a
4555        // deliberate test edit, not a silent contract narrowing.
4556        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
4557    }
4558
4559    #[test]
4560    fn validate_rejects_empty_child_name() {
4561        let s = SupervisorSpec {
4562            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4563            ..SupervisorSpec::default()
4564        };
4565        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
4566    }
4567
4568    #[test]
4569    fn validate_rejects_empty_child_version() {
4570        let s = SupervisorSpec {
4571            children: vec![child("w", "", RestartPolicy::Permanent)],
4572            ..SupervisorSpec::default()
4573        };
4574        assert!(matches!(
4575            s.validate().unwrap_err(),
4576            SupervisorError::EmptyChildVersion { .. }
4577        ));
4578    }
4579
4580    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
4581
4582    #[test]
4583    fn validate_rejects_invalid_child_versao_requirement() {
4584        // The fail-before-pass-after pin: a non-empty but malformed
4585        // semver requirement (`"^bad-version"`) silently passed
4586        // `validate()` on every pre-gate codebase because the prior
4587        // shape only refused the empty string. The parse failure
4588        // surfaced far downstream at lacre-resolve time with a
4589        // `semver::Error` that didn't name which `:children` entry
4590        // carried the typo. The new gate moves the check to caixa-build
4591        // time at the source caixa.lisp — the third `:versao` typed
4592        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
4593        // structural parity.
4594        let s = SupervisorSpec {
4595            children: vec![
4596                child("worker", "^0.1", RestartPolicy::Permanent),
4597                child("cache", "^bad-version", RestartPolicy::Transient),
4598            ],
4599            ..SupervisorSpec::default()
4600        };
4601        let err = s.validate().unwrap_err();
4602        assert!(
4603            matches!(
4604                err,
4605                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4606                    if caixa == "cache" && versao == "^bad-version"
4607            ),
4608            "got {err:?}"
4609        );
4610    }
4611
4612    #[test]
4613    fn validate_rejects_child_versao_with_double_caret_typo() {
4614        // `"^^0.1"` is the canonical doubled-caret typo — looks
4615        // Cargo-shaped on first glance but fails the parser because
4616        // semver doesn't accept stacked operators. Pin this
4617        // adjacent-shape footgun explicitly so a future relaxation that
4618        // accepts "looks-canonical-but-isn't" forms surfaces here.
4619        let s = SupervisorSpec {
4620            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
4621            ..SupervisorSpec::default()
4622        };
4623        let err = s.validate().unwrap_err();
4624        assert!(
4625            matches!(
4626                err,
4627                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4628                    if caixa == "worker" && versao == "^^0.1"
4629            ),
4630            "got {err:?}"
4631        );
4632    }
4633
4634    #[test]
4635    fn validate_rejects_child_versao_with_v_prefixed_tag() {
4636        // `"v0.1"` is the canonical "git-tag-shape leaking into the
4637        // semver requirement slot" typo — an author copies the
4638        // publish-side git-tag string verbatim into `:versao`, but
4639        // Cargo's semver parser rejects the leading `v`. Same
4640        // adjacent-shape footgun pinned for `:membros :versao`
4641        // (9888b13).
4642        let s = SupervisorSpec {
4643            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
4644            ..SupervisorSpec::default()
4645        };
4646        let err = s.validate().unwrap_err();
4647        assert!(
4648            matches!(
4649                err,
4650                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4651                    if caixa == "worker" && versao == "v0.1"
4652            ),
4653            "got {err:?}"
4654        );
4655    }
4656
4657    #[test]
4658    fn validate_accepts_canonical_child_versao_forms() {
4659        // The Cargo-shaped requirement forms `:deps :versao` and
4660        // `:membros :versao` already accept via
4661        // `crate::parse_requirement` must pass the children gate
4662        // without re-validating at the resolver layer. Pin every leg so
4663        // a future tightening of the canonical set surfaces here as a
4664        // test failure.
4665        for form in [
4666            "^0.1",      // caret — minor-range pin (the most common shape)
4667            "~0.1.2",    // tilde — patch-range pin
4668            "0.1.0",     // exact — single-version pin
4669            "*",         // wildcard — any version (semver::VersionReq::STAR)
4670            ">=0.1, <2", // multi-range — comma-separated comparators
4671        ] {
4672            let s = SupervisorSpec {
4673                children: vec![child("worker", form, RestartPolicy::Permanent)],
4674                ..SupervisorSpec::default()
4675            };
4676            s.validate()
4677                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4678        }
4679    }
4680
4681    #[test]
4682    fn child_versao_empty_takes_precedence_over_invalid() {
4683        // Order pin: the existing `EmptyChildVersion` diagnostic (which
4684        // doesn't try to parse) fires before the new
4685        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
4686        // `:versao` keeps its narrower error message —
4687        // `parse_requirement` would also reject `""`, but the
4688        // empty-string arm is the more self-locating diagnostic for the
4689        // author. Same ordering discipline as
4690        // `membro_versao_empty_takes_precedence_over_invalid` in
4691        // aplicacao.rs.
4692        let s = SupervisorSpec {
4693            children: vec![child("worker", "", RestartPolicy::Permanent)],
4694            ..SupervisorSpec::default()
4695        };
4696        let err = s.validate().unwrap_err();
4697        assert!(
4698            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
4699            "got {err:?}"
4700        );
4701    }
4702
4703    #[test]
4704    fn child_versao_invalid_fires_before_duplicate_check() {
4705        // Order pin: a malformed requirement on a non-duplicate entry
4706        // surfaces *its own* diagnostic (which names the offending
4707        // `:versao` string), even when a later entry would otherwise
4708        // collapse onto an earlier name. The per-entry shape gate runs
4709        // inline before the duplicate-key insert — parallel to
4710        // `membro_versao_invalid_fires_before_duplicate_check` in
4711        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
4712        let s = SupervisorSpec {
4713            children: vec![
4714                child("worker", "^bad", RestartPolicy::Permanent),
4715                child("cache", "^0.1", RestartPolicy::Transient),
4716                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4717            ],
4718            ..SupervisorSpec::default()
4719        };
4720        let err = s.validate().unwrap_err();
4721        assert!(
4722            matches!(
4723                err,
4724                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
4725            ),
4726            "got {err:?}"
4727        );
4728    }
4729
4730    #[test]
4731    fn child_versao_invalid_diagnostic_carries_offending_versao() {
4732        // The diagnostic-shape pin: the error names the offending
4733        // `:versao` value verbatim so the author can grep their
4734        // caixa.lisp without re-running the build, and carries a
4735        // non-empty `reason` from `semver::VersionReq::parse` so the
4736        // parser's own wording flows through to the diagnostic.
4737        let s = SupervisorSpec {
4738            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
4739            ..SupervisorSpec::default()
4740        };
4741        let err = s.validate().unwrap_err();
4742        let SupervisorError::ChildVersaoInvalid {
4743            caixa,
4744            versao,
4745            reason,
4746        } = err
4747        else {
4748            panic!("expected ChildVersaoInvalid, got other variant");
4749        };
4750        assert_eq!(caixa, "worker");
4751        assert_eq!(versao, "not-a-req");
4752        assert!(
4753            !reason.is_empty(),
4754            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
4755        );
4756    }
4757
4758    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
4759
4760    #[test]
4761    fn validate_rejects_child_caixa_with_uppercase() {
4762        // The canonical "I copied the Servico's display name verbatim"
4763        // typo — child caixa names are lowercase per K8s DNS-1123 label
4764        // rule. The diagnostic names the offending name and suggests the
4765        // lower-cased fix in one edit, mirroring the
4766        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
4767        let s = SupervisorSpec {
4768            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
4769            ..SupervisorSpec::default()
4770        };
4771        let err = s.validate().unwrap_err();
4772        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4773            panic!("expected ChildCaixaInvalid, got other variant");
4774        };
4775        assert_eq!(caixa, "Worker");
4776        assert!(
4777            reason.contains("uppercase"),
4778            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
4779        );
4780        assert!(
4781            reason.contains("\"worker\""),
4782            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
4783        );
4784    }
4785
4786    #[test]
4787    fn validate_rejects_child_caixa_with_underscore() {
4788        // The canonical "I'm thinking of a Python module / Postgres
4789        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
4790        // label schema. K8s rejects `metadata.name: my_worker` at
4791        // admission time with an opaque `field is invalid` (no source-
4792        // citing diagnostic). The gate moves it to caixa-build time.
4793        let s = SupervisorSpec {
4794            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
4795            ..SupervisorSpec::default()
4796        };
4797        let err = s.validate().unwrap_err();
4798        assert!(
4799            matches!(
4800                err,
4801                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4802                    if caixa == "my_worker" && reason.contains('_')
4803            ),
4804            "got {err:?}"
4805        );
4806    }
4807
4808    #[test]
4809    fn validate_rejects_child_caixa_with_dot() {
4810        // A `:children :caixa` entry is a single DNS-1123 label, not a
4811        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
4812        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
4813        // (3f9d7a0) on the peer name axis.
4814        let s = SupervisorSpec {
4815            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
4816            ..SupervisorSpec::default()
4817        };
4818        let err = s.validate().unwrap_err();
4819        assert!(
4820            matches!(
4821                err,
4822                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4823                    if caixa == "team.worker" && reason.contains('.')
4824            ),
4825            "got {err:?}"
4826        );
4827    }
4828
4829    #[test]
4830    fn validate_rejects_child_caixa_with_leading_hyphen() {
4831        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
4832        // with an alphanumeric. The K8s apiserver rejects `-worker`
4833        // outright; the renderer would emit a `metadata.name: "-worker"`
4834        // that fails admission far from the source caixa.lisp.
4835        let s = SupervisorSpec {
4836            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
4837            ..SupervisorSpec::default()
4838        };
4839        let err = s.validate().unwrap_err();
4840        assert!(
4841            matches!(
4842                err,
4843                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4844                    if caixa == "-worker" && reason.contains("start and end")
4845            ),
4846            "got {err:?}"
4847        );
4848    }
4849
4850    #[test]
4851    fn validate_rejects_child_caixa_with_trailing_hyphen() {
4852        // The symmetric arm of the boundary rule. Pin separately so
4853        // both ends of the label are covered against a future relaxation
4854        // that only checks one boundary.
4855        let s = SupervisorSpec {
4856            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
4857            ..SupervisorSpec::default()
4858        };
4859        let err = s.validate().unwrap_err();
4860        assert!(
4861            matches!(
4862                err,
4863                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4864                    if caixa == "worker-"
4865            ),
4866            "got {err:?}"
4867        );
4868    }
4869
4870    #[test]
4871    fn validate_rejects_child_caixa_with_unicode() {
4872        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
4873        // (`xn--…`) by the author before it reaches K8s. The byte-by-
4874        // byte ASCII validity check rejects multi-byte UTF-8 sequences
4875        // by the first byte that fails the `[a-z0-9-]` predicate.
4876        let s = SupervisorSpec {
4877            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
4878            ..SupervisorSpec::default()
4879        };
4880        let err = s.validate().unwrap_err();
4881        assert!(
4882            matches!(
4883                err,
4884                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4885                    if caixa == "café"
4886            ),
4887            "got {err:?}"
4888        );
4889    }
4890
4891    #[test]
4892    fn validate_rejects_child_caixa_with_whitespace() {
4893        // Whitespace is the canonical "I pasted from a sketch / doc"
4894        // footgun. The apiserver rejects every `metadata.name` value
4895        // carrying whitespace; pin the gate fires at the right boundary.
4896        let s = SupervisorSpec {
4897            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
4898            ..SupervisorSpec::default()
4899        };
4900        let err = s.validate().unwrap_err();
4901        assert!(
4902            matches!(
4903                err,
4904                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4905                    if caixa == "my worker"
4906            ),
4907            "got {err:?}"
4908        );
4909    }
4910
4911    #[test]
4912    fn validate_rejects_child_caixa_too_long() {
4913        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
4914        // 63 bytes; the K8s apiserver rejects every `metadata.name`
4915        // axis over the limit at admission time. The diagnostic names
4916        // both the cap and the actual length so the author can shorten
4917        // in one edit, mirroring `rejects_membro_caixa_too_long`
4918        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
4919        let too_long = "a".repeat(64);
4920        let s = SupervisorSpec {
4921            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
4922            ..SupervisorSpec::default()
4923        };
4924        let err = s.validate().unwrap_err();
4925        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4926            panic!("expected ChildCaixaInvalid, got other variant");
4927        };
4928        assert_eq!(caixa, too_long);
4929        assert!(
4930            reason.contains("63"),
4931            "diagnostic must name the 63-byte cap (got: {reason:?})"
4932        );
4933        assert!(
4934            reason.contains("64"),
4935            "diagnostic must name the actual length (got: {reason:?})"
4936        );
4937    }
4938
4939    #[test]
4940    fn child_caixa_max_length_validates() {
4941        // The 63-byte boundary control pin — exactly-at-the-cap is
4942        // accepted, mirroring `membro_caixa_max_length_validates`
4943        // (3f9d7a0) and `placement_cluster_max_length_validates`
4944        // (6cbb900). Pinned separately so a future off-by-one tightening
4945        // surfaces here.
4946        let max_label = "a".repeat(63);
4947        let s = SupervisorSpec {
4948            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
4949            ..SupervisorSpec::default()
4950        };
4951        s.validate().unwrap();
4952    }
4953
4954    #[test]
4955    fn validate_accepts_canonical_child_caixa_forms() {
4956        // The realistic shapes a supervised child's `:caixa` carries —
4957        // single-word `worker`, version-suffixed `cache-v2`, single-char
4958        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
4959        // `payment-retry`, all-digit `0`. Pin every leg so a future
4960        // tightening (e.g. requiring a leading lowercase letter) surfaces
4961        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
4962        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
4963        // (6cbb900).
4964        for form in [
4965            "worker",
4966            "cache-v2",
4967            "a",
4968            "db",
4969            "2-pool",
4970            "payment-retry",
4971            "0",
4972        ] {
4973            let s = SupervisorSpec {
4974                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
4975                ..SupervisorSpec::default()
4976            };
4977            s.validate()
4978                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4979        }
4980    }
4981
4982    #[test]
4983    fn child_caixa_empty_takes_precedence_over_invalid() {
4984        // Order pin: the existing `EmptyChildName` diagnostic (which
4985        // doesn't try to parse the DNS-1123 shape) fires before the new
4986        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
4987        // its narrower error message — `is_dns_1123_label` would reject
4988        // the empty string too (boundary check on the first byte), but
4989        // the empty-string arm is the more self-locating diagnostic for
4990        // the author. Same ordering discipline as
4991        // `membro_caixa_empty_takes_precedence_over_invalid` in
4992        // aplicacao.rs.
4993        let s = SupervisorSpec {
4994            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4995            ..SupervisorSpec::default()
4996        };
4997        let err = s.validate().unwrap_err();
4998        assert_eq!(err, SupervisorError::EmptyChildName);
4999    }
5000
5001    #[test]
5002    fn child_caixa_invalid_fires_before_versao_check() {
5003        // Order pin: the per-axis shape gate runs inline before the
5004        // per-entry versao check, so a malformed `:caixa` on an entry
5005        // whose `:versao` would also fail surfaces the more self-
5006        // locating name-axis diagnostic first. Parallel to
5007        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
5008        // and `placement_cluster_invalid_fires_before_duplicate_check`
5009        // (6cbb900).
5010        let s = SupervisorSpec {
5011            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
5012            ..SupervisorSpec::default()
5013        };
5014        let err = s.validate().unwrap_err();
5015        assert!(
5016            matches!(
5017                err,
5018                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
5019            ),
5020            "got {err:?}"
5021        );
5022    }
5023
5024    #[test]
5025    fn child_caixa_invalid_fires_before_duplicate_check() {
5026        // Order pin: a malformed name on a non-duplicate entry surfaces
5027        // its own diagnostic, even when a later entry would otherwise
5028        // collapse onto an earlier name. The per-entry shape gate runs
5029        // inline before the duplicate-key HashSet insert, mirroring
5030        // `placement_cluster_invalid_fires_before_duplicate_check`
5031        // (6cbb900).
5032        let s = SupervisorSpec {
5033            children: vec![
5034                child("Worker", "^0.1", RestartPolicy::Permanent),
5035                child("cache", "^0.1", RestartPolicy::Transient),
5036                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5037            ],
5038            ..SupervisorSpec::default()
5039        };
5040        let err = s.validate().unwrap_err();
5041        assert!(
5042            matches!(
5043                err,
5044                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
5045            ),
5046            "got {err:?}"
5047        );
5048    }
5049
5050    #[test]
5051    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
5052        // The diagnostic-shape pin: the error names the offending
5053        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
5054        // the author can grep their caixa.lisp without re-running the
5055        // build. Mirrors the diagnostic-shape sweep on every prior
5056        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
5057        let s = SupervisorSpec {
5058            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
5059            ..SupervisorSpec::default()
5060        };
5061        let err = s.validate().unwrap_err();
5062        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5063            panic!("expected ChildCaixaInvalid, got other variant");
5064        };
5065        assert_eq!(caixa, "My_Worker");
5066        assert!(
5067            !reason.is_empty(),
5068            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
5069        );
5070    }
5071
5072    // ── value-shape: zero restart_window + duplicate child names ──────────
5073
5074    #[test]
5075    fn validate_accepts_none_restart_window() {
5076        // Omitted `:restart-window` is the "never reset" sentinel —
5077        // valid by design. Mirrors :limits axes where None = unbounded.
5078        let s = SupervisorSpec {
5079            restart_window: None,
5080            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5081            ..SupervisorSpec::default()
5082        };
5083        s.validate().unwrap();
5084    }
5085
5086    #[test]
5087    fn validate_rejects_zero_restart_window() {
5088        // Same "0 means the opposite of what you think" footgun closed
5089        // for :politicas :timeout (Envoy treats 0s as infinite) and
5090        // :limits :wall-clock (wasmtime traps before the call starts).
5091        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
5092        let s = SupervisorSpec {
5093            restart_window: Some(Duration::ZERO),
5094            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5095            ..SupervisorSpec::default()
5096        };
5097        assert_eq!(
5098            s.validate().unwrap_err(),
5099            SupervisorError::RestartWindowZero
5100        );
5101    }
5102
5103    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
5104    //
5105    // The fourth (and last) typed-`Duration` axis in caixa-core to get
5106    // the integer-millisecond canonical-form gate — peer with
5107    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
5108    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
5109    // path is already gated at the shared codec layer (see
5110    // `restart_window_serde_rejects_fractional_seconds`); this arm
5111    // closes the programmatic-struct-literal path the codec gate can't
5112    // see.
5113
5114    #[test]
5115    fn validate_rejects_sub_millisecond_restart_window() {
5116        // The fail-before-pass-after pin: a programmatic
5117        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
5118        // `validate` on every pre-gate codebase, then truncated to
5119        // `as_millis() == 1` on first serialize — the shared codec
5120        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
5121        // 1_000_000 ns, the typed `restart_window` no longer matches
5122        // its rendered form.
5123        let s = SupervisorSpec {
5124            restart_window: Some(Duration::from_micros(1500)),
5125            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5126            ..SupervisorSpec::default()
5127        };
5128        match s.validate().unwrap_err() {
5129            SupervisorError::RestartWindowNotCanonical { window } => {
5130                assert_eq!(window, Duration::from_micros(1500));
5131            }
5132            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5133        }
5134    }
5135
5136    #[test]
5137    fn validate_rejects_one_nanosecond_restart_window() {
5138        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
5139        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
5140        // so the shared codec emits the literal `"0s"` — the next
5141        // serde round-trip would parse back to `Duration::ZERO`, which
5142        // the `RestartWindowZero` arm then rejects on re-validate. The
5143        // canonical-form gate at this layer surfaces a self-locating
5144        // diagnostic naming the offending Duration verbatim rather
5145        // than a downstream `RestartWindowZero` whose remediation
5146        // points at omitting the slot.
5147        let s = SupervisorSpec {
5148            restart_window: Some(Duration::from_nanos(1)),
5149            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5150            ..SupervisorSpec::default()
5151        };
5152        match s.validate().unwrap_err() {
5153            SupervisorError::RestartWindowNotCanonical { window } => {
5154                assert_eq!(window, Duration::from_nanos(1));
5155            }
5156            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5157        }
5158    }
5159
5160    #[test]
5161    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
5162        // The 1-ns-past-1ms boundary case: a `Duration` carrying
5163        // 1_000_001 ns is structurally past the integer-ms granularity
5164        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
5165        // trip would truncate to `1ms` and the consumer would observe
5166        // a 1-ns drift on every emit. Same boundary the peer
5167        // `validate_rejects_nanosecond_past_canonical_boundary` test
5168        // in limits.rs pins for the `:limits :wall-clock` axis.
5169        let w = Duration::from_nanos(1_000_001);
5170        let s = SupervisorSpec {
5171            restart_window: Some(w),
5172            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5173            ..SupervisorSpec::default()
5174        };
5175        assert_eq!(
5176            s.validate().unwrap_err(),
5177            SupervisorError::RestartWindowNotCanonical { window: w }
5178        );
5179    }
5180
5181    #[test]
5182    fn validate_accepts_integer_millisecond_restart_window_values() {
5183        // The positive-control sweep: every `Duration` the shared
5184        // codec can round-trip losslessly — the canonical
5185        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
5186        // pair emits and accepts — passes `validate` without
5187        // surfacing the new canonical-form arm. Mirrors
5188        // `validate_accepts_integer_millisecond_wall_clock_values` on
5189        // the sibling `:limits :wall-clock` axis.
5190        for w in [
5191            Duration::from_millis(1),
5192            Duration::from_millis(500),
5193            Duration::from_millis(1500),
5194            Duration::from_secs(1),
5195            Duration::from_secs(30),
5196            Duration::from_secs(60),
5197            Duration::from_secs(120),
5198            Duration::from_secs(3600),
5199        ] {
5200            let s = SupervisorSpec {
5201                restart_window: Some(w),
5202                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5203                ..SupervisorSpec::default()
5204            };
5205            s.validate()
5206                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
5207        }
5208    }
5209
5210    #[test]
5211    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
5212        // Cross-arm ordering pin: `Duration::ZERO` has
5213        // `subsec_nanos() == 0` and would otherwise pass the
5214        // canonical-form arm — the zero-floor arm must fire first so
5215        // the more self-locating `RestartWindowZero` diagnostic (with
5216        // its omit-axis remediation directly named) leads. Same
5217        // posture every peer zero-then-shape gate uses
5218        // (`WallClockZero` → `WallClockNotCanonical`,
5219        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
5220        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
5221        let s = SupervisorSpec {
5222            restart_window: Some(Duration::ZERO),
5223            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5224            ..SupervisorSpec::default()
5225        };
5226        assert_eq!(
5227            s.validate().unwrap_err(),
5228            SupervisorError::RestartWindowZero
5229        );
5230    }
5231
5232    #[test]
5233    fn restart_window_canonical_diagnostic_carries_offending_duration() {
5234        // Diagnostic-shape pin: the canonical-form arm names the
5235        // offending `Duration` verbatim so the author's grep lands on
5236        // the field's value, not a generic "duration not canonical"
5237        // message. Same shape every other typed-canonical-form arm
5238        // on this surface carries (`WallClockNotCanonical` carries
5239        // the offending `Duration` verbatim,
5240        // `PolicyTimeoutNotCanonical` carries the offending
5241        // `Duration` verbatim).
5242        let w = Duration::from_micros(500);
5243        let s = SupervisorSpec {
5244            restart_window: Some(w),
5245            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5246            ..SupervisorSpec::default()
5247        };
5248        let err = s.validate().unwrap_err();
5249        let msg = err.to_string();
5250        assert!(
5251            msg.contains("500"),
5252            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
5253        );
5254        assert!(
5255            msg.contains("sub-millisecond"),
5256            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
5257        );
5258    }
5259
5260    #[test]
5261    fn restart_window_validated_value_round_trips_through_codec() {
5262        // The structural property the canonical-ms gate enforces:
5263        // every `SupervisorSpec::restart_window` past
5264        // `SupervisorSpec::validate` round-trips losslessly through
5265        // the shared duration codec (serialize → string →
5266        // deserialize → equal value). Pin this end-to-end so a future
5267        // change to either side (the validate gate's accepted
5268        // granularity, the codec's parse/render unit set) that breaks
5269        // the alignment surfaces here. Peer of
5270        // `wall_clock_validated_value_round_trips_through_codec` on
5271        // the sibling `:limits :wall-clock` axis.
5272        for w in [
5273            Duration::from_millis(1),
5274            Duration::from_millis(1500),
5275            Duration::from_secs(30),
5276            Duration::from_secs(3600),
5277        ] {
5278            let s = SupervisorSpec {
5279                restart_window: Some(w),
5280                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5281                ..SupervisorSpec::default()
5282            };
5283            s.validate().unwrap();
5284            let json = serde_json::to_string(&s).unwrap();
5285            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5286            assert_eq!(back.restart_window, Some(w));
5287        }
5288    }
5289
5290    // ── value-shape: upper cap on :restart-window ─────────────────────────
5291    //
5292    // The fourth (and last) typed-`Duration` axis in caixa-core to get
5293    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
5294    // `:politicas :timeout` (2e8ee7e), and `:politicas
5295    // :circuit-breaker :window` (379a814). Brackets the typed
5296    // `:restart-window` axis structurally: every validated value lies
5297    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
5298    // granularity, closing the
5299    // rolling-window-degenerates-to-lifetime-counter footgun the prior
5300    // zero-floor-and-canonical-form-only checks left open.
5301
5302    #[test]
5303    fn validate_rejects_restart_window_above_cap() {
5304        // The fail-before-pass-after pin: 3601s = 1h + 1s is
5305        // structurally one canonical-tick past the
5306        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
5307        // integer-millisecond magnitude the canonical-form arm above
5308        // accepts cleanly, that the shared duration codec round-trips
5309        // losslessly as `"3601s"`, and that silently passed validate on
5310        // every pre-gate codebase because the typed slot's only checks
5311        // were the zero-floor and canonical-form arms. The runtime
5312        // substrate consuming the value (Erlang/OTP's MaxIntensity/
5313        // Period reconciler, the future wasm-operator's per-supervisor
5314        // restart-intensity counter) reaches for a `Duration` so long
5315        // no realistic restart-recovery pattern resets the counter,
5316        // far from the source caixa.lisp.
5317        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5318        let s = SupervisorSpec {
5319            restart_window: Some(w),
5320            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5321            ..SupervisorSpec::default()
5322        };
5323        assert_eq!(
5324            s.validate().unwrap_err(),
5325            SupervisorError::RestartWindowExceedsCap { window: w }
5326        );
5327    }
5328
5329    #[test]
5330    fn validate_rejects_restart_window_one_millisecond_above_cap() {
5331        // Boundary case: exactly 1ms past the cap (the granularity the
5332        // canonical-form gate enforces). Catches a future "strictly
5333        // less than" half-measure and pins the diagnostic to name the
5334        // offending `Duration` verbatim. Peer of
5335        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
5336        // `rejects_policy_timeout_one_millisecond_above_cap` /
5337        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
5338        // on the sibling typed-`Duration` axes' top edges.
5339        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
5340        let s = SupervisorSpec {
5341            restart_window: Some(w),
5342            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5343            ..SupervisorSpec::default()
5344        };
5345        assert_eq!(
5346            s.validate().unwrap_err(),
5347            SupervisorError::RestartWindowExceedsCap { window: w }
5348        );
5349    }
5350
5351    #[test]
5352    fn validate_rejects_restart_window_far_above_cap() {
5353        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
5354        // `(:restart-window "7d")`, or any "I want a lifetime counter
5355        // but wrote a `<integer>h` magnitude anyway" typo — values the
5356        // canonical-form arm accepts as integer-millisecond magnitudes,
5357        // the codec round-trips losslessly through serde, but the
5358        // operator's `MaxIntensity / Period` reconciler cannot honor
5359        // as a meaningful rolling window. Until this gate landed
5360        // validate accepted them. Pin the common above-cap values (24h,
5361        // 7d, ~11.5d) so a future relaxation that drops the upper bound
5362        // surfaces here.
5363        for w in [
5364            Duration::from_secs(86_400),    // 24h
5365            Duration::from_secs(604_800),   // 7d
5366            Duration::from_secs(1_000_000), // ~11.5 days
5367        ] {
5368            let s = SupervisorSpec {
5369                restart_window: Some(w),
5370                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5371                ..SupervisorSpec::default()
5372            };
5373            assert_eq!(
5374                s.validate().unwrap_err(),
5375                SupervisorError::RestartWindowExceedsCap { window: w }
5376            );
5377        }
5378    }
5379
5380    #[test]
5381    fn validate_accepts_restart_window_at_cap() {
5382        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
5383        // (1h) — must validate. The cap is inclusive on the top edge,
5384        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
5385        // [`crate::POLICY_TIMEOUT_MAX`] /
5386        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
5387        // capped axes. Pin the boundary explicitly so a future
5388        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
5389        // instead of `>`) surfaces here as a test failure rather than a
5390        // silent contract narrowing.
5391        let s = SupervisorSpec {
5392            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5393            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5394            ..SupervisorSpec::default()
5395        };
5396        s.validate()
5397            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
5398    }
5399
5400    #[test]
5401    fn validate_accepts_restart_window_typical_values() {
5402        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
5403        // per-supervisor production-playbook band positive-control
5404        // sweep — every value Learn You Some Erlang's `{intensity, 5,
5405        // 60}` worker-supervisor `Period = 60s` default, Elixir's
5406        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
5407        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
5408        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
5409        // default recommend (5s..=300s) must pass, plus a sweep
5410        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
5411        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
5412        // on the sibling `:limits :wall-clock` axis.
5413        for w in [
5414            Duration::from_millis(1),
5415            Duration::from_millis(500),
5416            Duration::from_secs(1),
5417            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
5418            Duration::from_secs(10), // Riak Core lower
5419            Duration::from_secs(30),
5420            Duration::from_secs(60),  // Learn You Some Erlang default
5421            Duration::from_secs(120), // OTP supervisor MaxT typical
5422            Duration::from_secs(300), // Riak Core upper
5423            Duration::from_secs(900), // 15m
5424            Duration::from_secs(1800),
5425            Duration::from_secs(3600), // exactly 1h, the cap
5426        ] {
5427            let s = SupervisorSpec {
5428                restart_window: Some(w),
5429                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5430                ..SupervisorSpec::default()
5431            };
5432            s.validate()
5433                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
5434        }
5435    }
5436
5437    #[test]
5438    fn restart_window_zero_takes_precedence_over_cap() {
5439        // The cross-arm ordering pin: `Duration::ZERO` is structurally
5440        // outside both `>= 1ms` (zero-floor) and `<=
5441        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
5442        // diagnostic is the more self-locating one (it directly names
5443        // the omit-axis remediation), so the validate gate must fire
5444        // on zero first. Same shape every other zero-then-cap ordering
5445        // on this surface uses (`WallClockZero` then
5446        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
5447        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
5448        // `PolicyBreakerWindowExceedsCap`).
5449        let s = SupervisorSpec {
5450            restart_window: Some(Duration::ZERO),
5451            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5452            ..SupervisorSpec::default()
5453        };
5454        assert_eq!(
5455            s.validate().unwrap_err(),
5456            SupervisorError::RestartWindowZero,
5457            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
5458        );
5459    }
5460
5461    #[test]
5462    fn restart_window_canonical_takes_precedence_over_cap() {
5463        // The cross-arm ordering pin: a `Duration` that is *both*
5464        // sub-millisecond (non-canonical-form) and structurally above
5465        // the cap surfaces the canonical-form diagnostic first,
5466        // because the round-trip-shape break is the more fundamental
5467        // issue (the value can't even round-trip through the codec,
5468        // so the cap diagnostic naming `1ms..=1h` would be misleading
5469        // — there's no integer-ms form of the offending value). Pin
5470        // the order so a future refactor that reorders the arms
5471        // surfaces here as a test failure rather than a silent
5472        // diagnostic regression. Peer of
5473        // `wall_clock_canonical_takes_precedence_over_cap` /
5474        // `policy_timeout_canonical_takes_precedence_over_cap`.
5475        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
5476        let s = SupervisorSpec {
5477            restart_window: Some(w),
5478            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5479            ..SupervisorSpec::default()
5480        };
5481        assert_eq!(
5482            s.validate().unwrap_err(),
5483            SupervisorError::RestartWindowNotCanonical { window: w },
5484            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
5485        );
5486    }
5487
5488    #[test]
5489    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
5490        // The cross-arm ordering pin between the `:max-restarts` cap
5491        // and the sibling `:restart-window` cap. A supervisor carrying
5492        // both an over-cap `max_restarts` AND an over-cap window must
5493        // surface the `MaxRestartsExceedsCap` diagnostic first — the
5494        // cap arm is wired immediately after the zero-restart arm and
5495        // strictly before every window-axis arm (zero / canonical /
5496        // cap), so the offending value the diagnostic names matches
5497        // the order the author would discover the gates by reading
5498        // top-to-bottom through `SupervisorSpec::validate`. Pin the
5499        // order so a future refactor that reorders the arms surfaces
5500        // here as a test failure rather than a silent diagnostic
5501        // regression. Peer of
5502        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
5503        // on the sibling zero / canonical window arms.
5504        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5505        let s = SupervisorSpec {
5506            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5507            restart_window: Some(w),
5508            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5509            ..SupervisorSpec::default()
5510        };
5511        assert_eq!(
5512            s.validate().unwrap_err(),
5513            SupervisorError::MaxRestartsExceedsCap {
5514                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5515            },
5516            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5517        );
5518    }
5519
5520    #[test]
5521    fn restart_window_cap_diagnostic_carries_offending_value() {
5522        // The diagnostic-shape pin: the offending `Duration` is
5523        // carried verbatim into the
5524        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
5525        // surfaced error message names the value the author wrote,
5526        // not just the cap. Same self-locating diagnostic shape every
5527        // other typed-cap arm on this surface carries
5528        // (`WallClockExceedsCap` carries the offending `Duration`
5529        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
5530        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
5531        // the offending `Duration` verbatim).
5532        let w = Duration::from_secs(7200); // 2h
5533        let s = SupervisorSpec {
5534            restart_window: Some(w),
5535            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5536            ..SupervisorSpec::default()
5537        };
5538        let err = s.validate().unwrap_err();
5539        assert!(
5540            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
5541            "got {err:?}"
5542        );
5543        let msg = err.to_string();
5544        assert!(
5545            msg.contains("7200"),
5546            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
5547        );
5548    }
5549
5550    #[test]
5551    fn supervisor_restart_window_cap_pins_canonical_value() {
5552        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
5553        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
5554        // shared duration codec emits as a clean canonical string
5555        // (`"<n>h"`). Pinning the literal value here surfaces a future
5556        // drift (a relaxation to 24h, a tightening to 5m) as a
5557        // deliberate test edit, not a silent contract narrowing.
5558        //
5559        // The four typed-`Duration` caps on the validation surface
5560        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
5561        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
5562        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
5563        // single uniform top edge at the codec's largest emitted unit
5564        // — a structural-property invariant the equality assertions
5565        // here enshrine, so a future drift on any of the four
5566        // surfaces as a deliberate test edit. Same shape every other
5567        // typed-cap value pin uses
5568        // (`wall_clock_cap_pins_canonical_value`,
5569        // `policy_timeout_cap_pins_canonical_value`,
5570        // `circuit_breaker_window_cap_pins_canonical_value`).
5571        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
5572        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
5573        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
5574        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
5575        assert_eq!(
5576            SUPERVISOR_RESTART_WINDOW_MAX,
5577            crate::POLICY_BREAKER_WINDOW_MAX
5578        );
5579    }
5580
5581    #[test]
5582    fn restart_window_cap_value_round_trips_through_codec() {
5583        // The codec round-trip property the cap arm preserves: the
5584        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
5585        // through the shared duration codec — every value at the cap
5586        // serializes to the canonical `"1h"` form and parses back
5587        // identically. Pin the round-trip so a future change to the
5588        // codec's unit set or to the cap's magnitude that breaks the
5589        // round-trip property surfaces here. Peer of
5590        // `wall_clock_cap_value_round_trips_through_codec` on the
5591        // sibling `:limits :wall-clock` axis.
5592        let s = SupervisorSpec {
5593            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5594            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5595            ..SupervisorSpec::default()
5596        };
5597        s.validate().unwrap();
5598        let json = serde_json::to_string(&s).unwrap();
5599        assert!(
5600            json.contains("\"1h\""),
5601            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
5602        );
5603        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5604        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
5605    }
5606
5607    #[test]
5608    fn validate_rejects_duplicate_child_caixa() {
5609        // Two children with the same :caixa render to two ComputeUnits
5610        // with the same name in the cluster's HelmRelease values —
5611        // one silently overwrites the other. Erlang/OTP's child_spec.id
5612        // is required-unique per supervisor; same set-not-multiset
5613        // discipline applied here as for :membros / :placement
5614        // :clusters / :entrada :paths.
5615        let s = SupervisorSpec {
5616            children: vec![
5617                child("worker", "^0.1", RestartPolicy::Permanent),
5618                child("cache", "^0.1", RestartPolicy::Transient),
5619                child("worker", "^0.2", RestartPolicy::Permanent),
5620            ],
5621            ..SupervisorSpec::default()
5622        };
5623        let err = s.validate().unwrap_err();
5624        assert!(
5625            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
5626            "got {err:?}"
5627        );
5628    }
5629
5630    #[test]
5631    fn validate_duplicate_child_diagnostic_names_first_collision() {
5632        // Iteration walks the :children list in declaration order —
5633        // the diagnostic names the first repeat, deterministically,
5634        // even when multiple names duplicate.
5635        let s = SupervisorSpec {
5636            children: vec![
5637                child("a", "^0.1", RestartPolicy::Permanent),
5638                child("b", "^0.1", RestartPolicy::Permanent),
5639                child("a", "^0.1", RestartPolicy::Permanent),
5640                child("b", "^0.1", RestartPolicy::Permanent),
5641            ],
5642            ..SupervisorSpec::default()
5643        };
5644        let err = s.validate().unwrap_err();
5645        assert!(
5646            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
5647            "got {err:?}"
5648        );
5649    }
5650
5651    // ── self-supervision cross-slot gate ──────────────────────────
5652
5653    #[test]
5654    fn validate_no_self_supervision_rejects_self_referential_child() {
5655        // A supervisor whose `:children` lists its own `:nome` is a
5656        // one-node reconciliation cycle — rejected, naming the parent.
5657        let children = vec![
5658            child("worker", "^0.1", RestartPolicy::Permanent),
5659            child("orquestra", "^0.1", RestartPolicy::Permanent),
5660        ];
5661        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
5662        assert!(
5663            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
5664            "got {err:?}"
5665        );
5666    }
5667
5668    #[test]
5669    fn validate_no_self_supervision_accepts_distinct_children() {
5670        // Positive control: distinct child names (including a child that
5671        // is itself a supervisor — nested trees are valid OTP) pass.
5672        let children = vec![
5673            child("worker", "^0.1", RestartPolicy::Permanent),
5674            child("sub-tree", "^0.1", RestartPolicy::Permanent),
5675        ];
5676        validate_no_self_supervision(&children, "orquestra").unwrap();
5677    }
5678
5679    #[test]
5680    fn validate_no_self_supervision_empty_children_is_ok() {
5681        // SimpleOneForOne / no-static-children supervisors have nothing
5682        // to self-reference — the gate is vacuously satisfied.
5683        validate_no_self_supervision(&[], "orquestra").unwrap();
5684    }
5685
5686    #[test]
5687    fn validate_simple_one_for_one_skips_uniqueness_check() {
5688        // SimpleOneForOne supervisors carry no static children — the
5689        // duplicate-child loop never runs. A zero-window declaration
5690        // on a SimpleOneForOne supervisor still trips the window check
5691        // (window applies to dynamic children too).
5692        let s = SupervisorSpec {
5693            estrategia: RestartStrategy::SimpleOneForOne,
5694            restart_window: None,
5695            children: vec![],
5696            ..SupervisorSpec::default()
5697        };
5698        s.validate().unwrap();
5699        let s_zero = SupervisorSpec {
5700            estrategia: RestartStrategy::SimpleOneForOne,
5701            restart_window: Some(Duration::ZERO),
5702            children: vec![],
5703            ..SupervisorSpec::default()
5704        };
5705        assert_eq!(
5706            s_zero.validate().unwrap_err(),
5707            SupervisorError::RestartWindowZero
5708        );
5709    }
5710
5711    #[test]
5712    fn validate_zero_window_runs_after_max_restarts_check() {
5713        // Pin the order: max_restarts == 0 fires before
5714        // restart_window == 0s, so an author with both wrong sees the
5715        // counter-axis diagnostic first (matches the order in the
5716        // struct and in the doc comment).
5717        let s = SupervisorSpec {
5718            max_restarts: 0,
5719            restart_window: Some(Duration::ZERO),
5720            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5721            ..SupervisorSpec::default()
5722        };
5723        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5724    }
5725
5726    #[test]
5727    fn round_trip_all_strategies() {
5728        for &strat in RestartStrategy::ALL {
5729            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
5730            // shape partition through the [`gen_platform::IsVariant`]
5731            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
5732            // predicate rather than the raw
5733            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
5734            // open-coded pattern-match — same closed-set-typed-enum
5735            // arm-discriminator dispatch discipline the sibling
5736            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
5737            // (915a934) extended onto its two paired positive / negated
5738            // `matches!` filter sites, and the sibling
5739            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
5740            // predicate convergence (766ec63) extended onto the M3 mesh-
5741            // slot per-`:placement` distribution-strategy `matches!`
5742            // discriminator axis. See the sibling
5743            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
5744            // fixture and the peer `manifest::tests::
5745            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
5746            // fixture — all three sites (the last unlifted
5747            // `matches!`-based arm-discriminator axis on the OTP-shape
5748            // supervisor sibling-restart-strategy closed-set typed enum,
5749            // acknowledged in 915a934's Prior-commits footnote as the
5750            // outstanding follow-up) now consult one typed dispatch on
5751            // the substrate primitive.
5752            let s = SupervisorSpec {
5753                estrategia: strat,
5754                children: if strat.is_simple_one_for_one() {
5755                    vec![]
5756                } else {
5757                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
5758                },
5759                ..SupervisorSpec::default()
5760            };
5761            let json = serde_json::to_string(&s).unwrap();
5762            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5763            assert_eq!(s, back);
5764        }
5765    }
5766
5767    #[test]
5768    fn round_trip_all_restart_policies() {
5769        for policy in [
5770            RestartPolicy::Permanent,
5771            RestartPolicy::Temporary,
5772            RestartPolicy::Transient,
5773        ] {
5774            let c = child("w", "^0.1", policy);
5775            let json = serde_json::to_string(&c).unwrap();
5776            let back: ChildSpec = serde_json::from_str(&json).unwrap();
5777            assert_eq!(c, back);
5778        }
5779    }
5780
5781    #[test]
5782    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
5783        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
5784        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
5785        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
5786        // is the only variant that satisfies `.is_simple_one_for_one()`;
5787        // every static-children-bearing arm (`OneForOne` / `OneForAll`
5788        // / `RestForOne`) returns `false`. This pin makes the partition
5789        // invariant load-bearing at caixa-core test time so a future
5790        // derive regression (a hole that returns `false` for
5791        // `SimpleOneForOne` too, or a byte-collision that flips a second
5792        // variant to `true`) trips here rather than laundering the arm
5793        // at the three test-fixture builder sites (a hole flips the
5794        // `SimpleOneForOne` fixture to carry a non-empty children list
5795        // and the subsequent `SupervisorSpec::validate` would refuse the
5796        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
5797        // a collision flips a peer strategy's fixture to carry an empty
5798        // children list and the subsequent `validate` would refuse with
5799        // [`SupervisorError::NoChildren`] — either way, the pin fires
5800        // here, at the derive site, rather than at the fixture-refusal
5801        // site far away). Peer of the sibling
5802        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
5803        // (915a934) pin on the M2 OTP-appup axis and the sibling
5804        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
5805        // pin on the M0 `:kind` axis.
5806        let cases: &[(RestartStrategy, bool)] = &[
5807            (RestartStrategy::OneForOne, false),
5808            (RestartStrategy::OneForAll, false),
5809            (RestartStrategy::RestForOne, false),
5810            (RestartStrategy::SimpleOneForOne, true),
5811        ];
5812        for (variant, expected) in cases {
5813            assert_eq!(
5814                variant.is_simple_one_for_one(),
5815                *expected,
5816                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
5817                 return {expected} (partition invariant on the \
5818                 IsVariant-derived arm-discriminator predicate — every \
5819                 test-fixture site that partitions the `:children` slot \
5820                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
5821                 off this typed dispatch, so a derive regression must \
5822                 surface here rather than at the fixture-refusal site)"
5823            );
5824        }
5825    }
5826
5827    #[test]
5828    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
5829        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
5830        // fixture-shape partition against the pre-lift
5831        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
5832        // pattern-match every test-fixture builder site previously
5833        // coupled to inline. Asserts the two projections agree byte-for-
5834        // byte on every arm of the enum, so a future derive regression
5835        // that flipped either predicate's arm-set would surface here at
5836        // caixa-core test time rather than at the three fixture-builder
5837        // sites (`supervisor::tests::round_trip_all_strategies`,
5838        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
5839        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
5840        // far from the derive site. Same peer-shape byte-identity pin
5841        // every sibling `IsVariant`-derive-routed convergence carries on
5842        // the substrate's closed-set typed-enum surface (peer of
5843        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
5844        // on the M2 OTP-appup axis).
5845        for &strat in RestartStrategy::ALL {
5846            let via_predicate = strat.is_simple_one_for_one();
5847            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
5848            assert_eq!(
5849                via_predicate, via_matches,
5850                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
5851                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
5852                 the pre-lift open-coded pattern and the \
5853                 IsVariant-derived predicate are the same axis, \
5854                 one typed dispatch"
5855            );
5856        }
5857    }
5858
5859    #[test]
5860    fn duration_codec_round_trip_canonical_units() {
5861        // Note the canonical-form rule: durations serialize to the
5862        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
5863        // "60s" — but the round-trip preserves the underlying Duration.
5864        let cases = [
5865            ("30s", Duration::from_secs(30)),
5866            ("5m", Duration::from_secs(300)),
5867            ("1h", Duration::from_secs(3600)),
5868            ("500ms", Duration::from_millis(500)),
5869        ];
5870        for (lit, dur) in cases {
5871            let s = SupervisorSpec {
5872                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5873                restart_window: Some(dur),
5874                ..SupervisorSpec::default()
5875            };
5876            let json = serde_json::to_string(&s).unwrap();
5877            assert!(
5878                json.contains(&format!("\"{lit}\"")),
5879                "expected \"{lit}\" in {json}"
5880            );
5881            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5882            assert_eq!(back.restart_window, Some(dur));
5883        }
5884    }
5885
5886    #[test]
5887    fn duration_canonicalizes_to_largest_unit() {
5888        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
5889        // typed Duration still equals 60s on the way back.
5890        let s = SupervisorSpec {
5891            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5892            restart_window: Some(Duration::from_secs(60)),
5893            ..SupervisorSpec::default()
5894        };
5895        let json = serde_json::to_string(&s).unwrap();
5896        assert!(json.contains("\"1m\""), "{json}");
5897        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5898        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
5899    }
5900
5901    #[test]
5902    fn three_child_one_for_one_validates() {
5903        let s = SupervisorSpec {
5904            estrategia: RestartStrategy::OneForOne,
5905            max_restarts: 5,
5906            restart_window: Some(Duration::from_secs(60)),
5907            children: vec![
5908                child("worker", "^0.1", RestartPolicy::Permanent),
5909                child("cache", "^0.1", RestartPolicy::Transient),
5910                child("scratch", "^0.1", RestartPolicy::Temporary),
5911            ],
5912        };
5913        s.validate().unwrap();
5914    }
5915
5916    #[test]
5917    fn json_uses_pascal_case_for_strategy_and_policy() {
5918        // Variant names are PascalCase by default in serde, matching
5919        // tatara-lisp's enum convention (`:estrategia OneForOne`).
5920        let c = child("w", "^0.1", RestartPolicy::Permanent);
5921        let json = serde_json::to_string(&c).unwrap();
5922        assert!(json.contains("\"Permanent\""));
5923        assert!(!json.contains("\"permanent\""));
5924
5925        let s = SupervisorSpec {
5926            estrategia: RestartStrategy::OneForOne,
5927            children: vec![c],
5928            ..SupervisorSpec::default()
5929        };
5930        let json = serde_json::to_string(&s).unwrap();
5931        assert!(json.contains("\"estrategia\":\"OneForOne\""));
5932    }
5933
5934    // ── shared duration codec: integer-magnitude canonical-form gate ──
5935    //
5936    // The gate lifts the discipline `crate::limits::parse_duration`
5937    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
5938    // the shared codec backing the remaining three typed-duration
5939    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
5940    // `:politicas :circuit-breaker :window`. Every magnitude `render`
5941    // emits is a non-negative integer with no decimal point and no
5942    // leading sign, so the codec's accepted set must match for
5943    // serialize/deserialize to round-trip without canonical-form
5944    // drift.
5945
5946    #[test]
5947    fn parse_accepts_integer_canonical_units() {
5948        // Pin the happy-path: every canonical author shape `render`
5949        // ever emits parses to the same `Duration` value, so the
5950        // codec's accepted set is at least a superset of its emitted
5951        // set on the canonical-unit axis.
5952        for (lit, dur) in [
5953            ("30s", Duration::from_secs(30)),
5954            ("500ms", Duration::from_millis(500)),
5955            ("2m", Duration::from_secs(120)),
5956            ("1h", Duration::from_secs(3600)),
5957            ("0s", Duration::ZERO),
5958        ] {
5959            assert_eq!(
5960                duration_codec::parse(lit).unwrap(),
5961                dur,
5962                "parse({lit:?}) should be {dur:?}"
5963            );
5964        }
5965    }
5966
5967    #[test]
5968    fn parse_accepts_bare_integer_as_seconds() {
5969        // The `"s" | ""` arm: a bare integer with no unit is read as
5970        // seconds. Pin this so the unit-empty form keeps parsing (it
5971        // renders to `"<n>s"` on serialize — that's a unit-choice
5972        // drift the integer-magnitude gate does NOT close, matching
5973        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
5974        // the peer `:limits :memory` codec).
5975        assert_eq!(
5976            duration_codec::parse("30").unwrap(),
5977            Duration::from_secs(30)
5978        );
5979    }
5980
5981    #[test]
5982    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
5983        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
5984        // on first serialize — DRIFT. The integer-magnitude gate names
5985        // the offending `"1.5"` verbatim and points at the canonical
5986        // remediation `"1500ms"`.
5987        let err = duration_codec::parse("1.5s").unwrap_err();
5988        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
5989        assert!(
5990            err.contains("not a non-negative integer"),
5991            "missing canonical-form reason in {err:?}"
5992        );
5993        assert!(
5994            err.contains("\"1500ms\""),
5995            "missing canonical-form remediation in {err:?}"
5996        );
5997    }
5998
5999    #[test]
6000    fn parse_rejects_decimal_shaped_integer_seconds() {
6001        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
6002        // `1s` exactly, so the round-trip looks correct — but the
6003        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
6004        // decimal-shape-with-integer-value form so author intent is
6005        // never silently rewritten.
6006        let err = duration_codec::parse("1.0s").unwrap_err();
6007        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
6008        assert!(
6009            err.contains("not a non-negative integer"),
6010            "missing canonical-form reason in {err:?}"
6011        );
6012    }
6013
6014    #[test]
6015    fn parse_rejects_half_unit_minute() {
6016        // `"0.5m"` is the unit-fraction footgun — author writes a
6017        // human-readable half-minute, serde silently rewrites to
6018        // `"30s"` on next emit. The gate names the offending
6019        // magnitude `"0.5"` and points at the integer-in-smaller-unit
6020        // form.
6021        let err = duration_codec::parse("0.5m").unwrap_err();
6022        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
6023        assert!(
6024            err.contains("\"30s\""),
6025            "missing canonical-form remediation in {err:?}"
6026        );
6027    }
6028
6029    #[test]
6030    fn parse_rejects_leading_plus_sign() {
6031        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
6032        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
6033        // cleanly to 30s and round-tripped to `"30s"` on next emit
6034        // (DRIFT). The digit-only gate closes the leading-sign class
6035        // first; the diagnostic names `"+30"` verbatim.
6036        let err = duration_codec::parse("+30s").unwrap_err();
6037        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
6038        assert!(
6039            err.contains("not a non-negative integer"),
6040            "missing canonical-form reason in {err:?}"
6041        );
6042    }
6043
6044    #[test]
6045    fn parse_rejects_leading_minus_sign() {
6046        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
6047        // rejected with `"negative duration in \"-30s\""`. Under the
6048        // integer-magnitude gate the diagnostic is unified — `-30` is
6049        // non-digit-only, f64-numeric, and surfaces with the canonical-
6050        // form reason (no leading `+` / `-` sign) naming the offending
6051        // `"-30"` verbatim. Same diagnostic shape as every other
6052        // rejected non-integer magnitude.
6053        let err = duration_codec::parse("-30s").unwrap_err();
6054        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
6055        assert!(
6056            err.contains("not a non-negative integer"),
6057            "missing canonical-form reason in {err:?}"
6058        );
6059    }
6060
6061    #[test]
6062    fn parse_garbage_still_falls_through_to_bad_magnitude() {
6063        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
6064        // through to the narrower "bad duration magnitude" arm — the
6065        // canonical-form diagnostic is reserved for the parser-shape
6066        // footgun case, not the "not a number at all" case. Same
6067        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
6068        // the peer `:limits :memory` codec.
6069        let err = duration_codec::parse("--1s").unwrap_err();
6070        assert!(
6071            err.contains("bad duration magnitude"),
6072            "expected bad-magnitude wording in {err:?}"
6073        );
6074    }
6075
6076    #[test]
6077    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
6078        // The accepted set is now closed under `u64`-exact integer
6079        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
6080        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
6081        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
6082        // possible. Pin the integer-exact arms across the four unit
6083        // suffixes so a future refactor that reaches back for f64
6084        // (`from_secs_f64`, `mul_f64`) surfaces here.
6085        assert_eq!(
6086            duration_codec::parse("3600s").unwrap(),
6087            Duration::from_secs(3600)
6088        );
6089        assert_eq!(
6090            duration_codec::parse("60m").unwrap(),
6091            Duration::from_secs(3600)
6092        );
6093        assert_eq!(
6094            duration_codec::parse("1h").unwrap(),
6095            Duration::from_secs(3600)
6096        );
6097        assert_eq!(
6098            duration_codec::parse("999ms").unwrap(),
6099            Duration::from_millis(999)
6100        );
6101    }
6102
6103    #[test]
6104    fn restart_window_serde_rejects_fractional_seconds() {
6105        // The shared codec backs `SupervisorSpec::restart_window`
6106        // (`with = "duration_codec"`) — so the gate applies on serde
6107        // deserialize for the typed Supervisor slot. A
6108        // `{"restartWindow":"1.5s"}` payload that previously round-
6109        // tripped to a different canonical string on next serialize
6110        // is now refused at deserialize with the integer-magnitude
6111        // diagnostic.
6112        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6113            "restartWindow":"1.5s",
6114            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6115        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6116        let msg = err.to_string();
6117        assert!(
6118            msg.contains("not a non-negative integer"),
6119            "expected integer-magnitude diagnostic in {msg:?}"
6120        );
6121        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
6122    }
6123
6124    #[test]
6125    fn restart_window_serde_rejects_leading_plus() {
6126        // The `u64::from_str` leading-`+` permissiveness gap that
6127        // motivated the digit-only gate (the `f64`-side accepted
6128        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
6129        // is now closed on the shared codec — surfaces as a structured
6130        // diagnostic at the serde layer for every typed-duration slot.
6131        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6132            "restartWindow":"+30s",
6133            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6134        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6135        let msg = err.to_string();
6136        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
6137        assert!(
6138            msg.contains("not a non-negative integer"),
6139            "missing canonical-form reason in {msg:?}"
6140        );
6141    }
6142
6143    #[test]
6144    fn parse_rejects_leading_zero_magnitude() {
6145        // `"030s"` is digit-only, so the existing non-digit-only / sign
6146        // / fractional arm doesn't catch it — `u64::from_str("030")`
6147        // returns `Ok(30)`, so before this gate `"030s"` parsed to
6148        // `Duration::from_secs(30)` and round-tripped through `render`
6149        // to `"30s"` — a *different* canonical string on the next emit,
6150        // breaking the THEORY.md Part V render-determinism contract
6151        // exactly the way `"+30s"` did before the leading-`+` arm
6152        // landed. Peer with the `rate_limit_codec` leading-zero arm
6153        // (4f46830) on the same canonical-form-drift axis.
6154        let err = duration_codec::parse("030s").unwrap_err();
6155        assert!(
6156            err.contains("non-canonical leading zero"),
6157            "expected leading-zero diagnostic in {err:?}"
6158        );
6159        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6160        assert!(
6161            err.contains("\"30s\""),
6162            "missing canonical-form remediation in {err:?}"
6163        );
6164        assert!(
6165            err.contains("THEORY.md"),
6166            "missing render-determinism citation in {err:?}"
6167        );
6168    }
6169
6170    #[test]
6171    fn parse_rejects_multi_digit_zero_magnitude() {
6172        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
6173        // digit-only, parse losslessly to `Duration::ZERO`, but render
6174        // back to `"0s"` (the single-byte canonical form) on the next
6175        // emit. The leading-zero arm refuses the drift class at the
6176        // codec layer; the semantic-zero gate downstream
6177        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
6178        // the single-byte canonical form `"0s"` separately on the
6179        // typed-validate layer.
6180        let err = duration_codec::parse("00s").unwrap_err();
6181        assert!(
6182            err.contains("non-canonical leading zero"),
6183            "expected leading-zero diagnostic in {err:?}"
6184        );
6185        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
6186    }
6187
6188    #[test]
6189    fn parse_rejects_leading_zero_per_hour_window() {
6190        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
6191        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
6192        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
6193        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
6194        // `h` / bare-integer-as-seconds) inherits the same gate.
6195        let err = duration_codec::parse("01h").unwrap_err();
6196        assert!(
6197            err.contains("non-canonical leading zero"),
6198            "expected leading-zero diagnostic in {err:?}"
6199        );
6200        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
6201    }
6202
6203    #[test]
6204    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
6205        // The `parse_accepts_bare_integer_as_seconds` happy-path
6206        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
6207        // multi-byte starts-with-`0`, parses losslessly to
6208        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
6209        // bare-integer surface accepts permissive unit-empty
6210        // shorthand but still must reject leading-zero padding.
6211        let err = duration_codec::parse("030").unwrap_err();
6212        assert!(
6213            err.contains("non-canonical leading zero"),
6214            "expected leading-zero diagnostic in {err:?}"
6215        );
6216        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6217    }
6218
6219    #[test]
6220    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
6221        // The codec-layer / typed-validate-layer boundary: `"0s"` /
6222        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
6223        // each round-trips losslessly through `render`
6224        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
6225        // accepts them. The downstream semantic-zero gates
6226        // (`SupervisorError::ZeroRestartWindow`,
6227        // `AplicacaoError::PolicyTimeoutZero`,
6228        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
6229        // zero-magnitude authoring at the typed-validate layer above,
6230        // peer with the `rate_limit_codec` codec-layer / typed-
6231        // validate-layer partition for `"0/s"`.
6232        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
6233        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
6234        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
6235    }
6236
6237    #[test]
6238    fn parse_accepts_canonical_magnitude_with_leading_one() {
6239        // The complementary boundary: a future tightening cannot
6240        // drift into rejecting valid canonical magnitudes that
6241        // happen to start with `1` (or any digit `[1-9]`). Pin
6242        // every canonical-unit suffix so the leading-zero arm
6243        // remains strictly narrower than the digit-only arm.
6244        assert_eq!(
6245            duration_codec::parse("100ms").unwrap(),
6246            Duration::from_millis(100)
6247        );
6248        assert_eq!(
6249            duration_codec::parse("100s").unwrap(),
6250            Duration::from_secs(100)
6251        );
6252        assert_eq!(
6253            duration_codec::parse("10m").unwrap(),
6254            Duration::from_secs(600)
6255        );
6256        assert_eq!(
6257            duration_codec::parse("10h").unwrap(),
6258            Duration::from_secs(36_000)
6259        );
6260    }
6261
6262    #[test]
6263    fn restart_window_serde_rejects_leading_zero() {
6264        // The shared codec backs `SupervisorSpec::restart_window`
6265        // (`with = "duration_codec"`) — so the leading-zero arm
6266        // applies on serde deserialize for the typed Supervisor slot.
6267        // A `{"restartWindow":"030s"}` payload that previously round-
6268        // tripped to a different canonical string on next serialize
6269        // is now refused at deserialize with the leading-zero
6270        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
6271        // / `restart_window_serde_rejects_fractional_seconds` on the
6272        // same canonical-form-drift axis.
6273        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6274            "restartWindow":"030s",
6275            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6276        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6277        let msg = err.to_string();
6278        assert!(
6279            msg.contains("non-canonical leading zero"),
6280            "expected leading-zero diagnostic in {msg:?}"
6281        );
6282        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
6283    }
6284
6285    #[test]
6286    fn parse_rejects_leading_whitespace() {
6287        // `" 30s"` — the canonical paste-from-aligned-doc /
6288        // paste-from-YAML-quoted-plain-scalar footgun. Before this
6289        // gate the top-level `s.trim()` at parse entry silently ate
6290        // the leading space and parsed the value to
6291        // `Duration::from_secs(30)`, which then round-tripped through
6292        // `render` to `"30s"` (a *different* canonical string on the
6293        // next emit) — the exact canonical-form-drift class the
6294        // leading-`+` / leading-zero arms already close, extended
6295        // to the whitespace-byte class. Peer with the sibling
6296        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
6297        // the M3 `:politicas` axis.
6298        let err = duration_codec::parse(" 30s").unwrap_err();
6299        assert!(
6300            err.contains("contains whitespace byte"),
6301            "expected whitespace diagnostic in {err:?}"
6302        );
6303        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6304        assert!(
6305            err.contains("THEORY.md"),
6306            "missing render-determinism contract citation in {err:?}"
6307        );
6308    }
6309
6310    #[test]
6311    fn parse_rejects_trailing_whitespace() {
6312        // `"30s "` — the canonical shell-history / trailing-space
6313        // paste footgun. Before this gate the top-level `s.trim()`
6314        // silently ate the trailing space and parsed to
6315        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
6316        // next emit — same canonical-form drift as the leading-space
6317        // sibling, closed on the same whitespace-byte arm.
6318        let err = duration_codec::parse("30s ").unwrap_err();
6319        assert!(
6320            err.contains("contains whitespace byte"),
6321            "expected whitespace diagnostic in {err:?}"
6322        );
6323        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6324    }
6325
6326    #[test]
6327    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
6328        // `"30 s"` — the canonical typographically-spaced author
6329        // shape (the same idiom every prose reference to a duration
6330        // renders as, mistakenly retained when the value is pasted
6331        // into a codec-shaped slot). Before this gate the per-part
6332        // `num_part.trim()` / `unit.trim()` calls silently ate the
6333        // whitespace between the magnitude and the unit and parsed
6334        // the value to `Duration::from_secs(30)`, round-tripping to
6335        // `"30s"` — the codec's *internal* whitespace-tolerance
6336        // vector, orthogonal to the leading / trailing surface but
6337        // the same canonical-form-drift class. Pins the arm as
6338        // strictly stronger than the pre-existing top-level
6339        // `s.trim()` behavior: it fires on whitespace anywhere in
6340        // the value, not just at the string boundary.
6341        let err = duration_codec::parse("30 s").unwrap_err();
6342        assert!(
6343            err.contains("contains whitespace byte"),
6344            "expected whitespace diagnostic in {err:?}"
6345        );
6346        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6347    }
6348
6349    #[test]
6350    fn parse_rejects_tab_byte() {
6351        // `"\t30s"` — the canonical paste-from-indented-doc /
6352        // paste-from-YAML-block-scalar footgun where a tab byte leads
6353        // the magnitude. Pins that the gate covers tab (`0x09`) as
6354        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
6355        // members and both would be silently swallowed by `s.trim()`
6356        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
6357        // space alone to the full ASCII-whitespace set (space `0x20`,
6358        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
6359        // the tab arm as a representative of the non-space members.
6360        let err = duration_codec::parse("\t30s").unwrap_err();
6361        assert!(
6362            err.contains("contains whitespace byte"),
6363            "expected whitespace diagnostic in {err:?}"
6364        );
6365        assert!(
6366            err.contains("0x09"),
6367            "missing offending tab byte in {err:?}"
6368        );
6369    }
6370
6371    #[test]
6372    fn restart_window_serde_rejects_whitespace() {
6373        // The shared codec backs `SupervisorSpec::restart_window`
6374        // (`with = "duration_codec"`) — so the whitespace arm
6375        // applies on serde deserialize for the typed Supervisor slot.
6376        // A `{"restartWindow":" 30s"}` payload that previously round-
6377        // tripped to a different canonical string on next serialize
6378        // is now refused at deserialize with the whitespace-byte
6379        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
6380        // / `restart_window_serde_rejects_leading_plus` /
6381        // `restart_window_serde_rejects_fractional_seconds` on the
6382        // same canonical-form-drift axis.
6383        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6384            "restartWindow":" 30s",
6385            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6386        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6387        let msg = err.to_string();
6388        assert!(
6389            msg.contains("contains whitespace byte"),
6390            "expected whitespace diagnostic in {msg:?}"
6391        );
6392        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
6393    }
6394
6395    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
6396    //
6397    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
6398    // duration codec — closes the strictly-complementary class the
6399    // byte-scan cannot see, through the lifted
6400    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
6401    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
6402    // and `:politicas :circuit-breaker :window` simultaneously via
6403    // this shared codec.
6404
6405    #[test]
6406    fn duration_codec_parse_rejects_leading_nbsp() {
6407        // NBSP prefix — the strictly-complementary drift class the
6408        // ASCII byte-scan cannot see. `str::trim` strips it silently
6409        // and the value drifts to `"30s"` on next serialize.
6410        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
6411        assert!(
6412            err.contains("non-ASCII Unicode whitespace character"),
6413            "expected non-ASCII whitespace diagnostic in {err:?}"
6414        );
6415        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
6416    }
6417
6418    #[test]
6419    fn duration_codec_parse_rejects_trailing_line_separator() {
6420        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
6421        // footgun.
6422        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
6423        assert!(
6424            err.contains("non-ASCII Unicode whitespace character"),
6425            "expected non-ASCII whitespace diagnostic in {err:?}"
6426        );
6427        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
6428    }
6429
6430    #[test]
6431    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
6432        // Positive-control pin: every ASCII-only canonical form the
6433        // renderer emits stays accepted through the new arm.
6434        assert_eq!(
6435            duration_codec::parse("30s").unwrap(),
6436            Duration::from_secs(30)
6437        );
6438        assert_eq!(
6439            duration_codec::parse("500ms").unwrap(),
6440            Duration::from_millis(500)
6441        );
6442        assert_eq!(
6443            duration_codec::parse("1h").unwrap(),
6444            Duration::from_secs(3600)
6445        );
6446    }
6447
6448    #[test]
6449    fn restart_window_serde_rejects_non_ascii_whitespace() {
6450        // The shared codec backs `SupervisorSpec::restart_window` — so
6451        // the new non-ASCII Unicode whitespace arm applies on serde
6452        // deserialize for the typed Supervisor slot. A
6453        // `{"restartWindow":" 30s"}` payload that previously
6454        // survived the ASCII byte-scan (only ASCII whitespace was
6455        // refused) is now refused at deserialize with the
6456        // non-ASCII-whitespace-and-codepoint diagnostic.
6457        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
6458            \"restartWindow\":\"\u{00A0}30s\",\
6459            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
6460        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6461        let msg = err.to_string();
6462        assert!(
6463            msg.contains("non-ASCII Unicode whitespace character"),
6464            "expected non-ASCII whitespace diagnostic in {msg:?}"
6465        );
6466        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
6467    }
6468
6469    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
6470
6471    #[test]
6472    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
6473        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
6474        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
6475        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
6476        // name the exact camelCase JSON keys the
6477        // `#[serde(rename_all = "camelCase")]` attribute on
6478        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
6479        // field carries `Some(_)` / non-empty) and pin that each canonical
6480        // byte-sequence appears verbatim in the JSON — a future accidental
6481        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
6482        // name flip at the derive attribute (any of which would silently
6483        // break every downstream JSON consumer that reaches for one of the
6484        // four consts via `Value::get(...)`) surfaces here as a build-time
6485        // test failure at `supervisor.rs`, not as an apply-time
6486        // `.get(<stale-canonical-const>)` returning `None` far from the
6487        // derive-attr drift's commit. Peer with the sibling
6488        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
6489        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
6490        // M2 typed-slot family established, extended here to close the
6491        // top-level Supervisor axis.
6492        let spec = SupervisorSpec {
6493            estrategia: RestartStrategy::OneForOne,
6494            max_restarts: 5,
6495            restart_window: Some(Duration::from_secs(60)),
6496            children: vec![ChildSpec {
6497                caixa: "w".into(),
6498                versao: "^0.1".into(),
6499                restart: RestartPolicy::Permanent,
6500            }],
6501        };
6502        let json = serde_json::to_string(&spec).unwrap();
6503        for key in [
6504            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6505            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6506            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6507            crate::render::SUPERVISOR_KEY_CHILDREN,
6508        ] {
6509            let quoted = format!("\"{key}\"");
6510            assert!(
6511                json.contains(&quoted),
6512                "serialized SupervisorSpec must carry the lifted \
6513                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
6514                 the JSON emission (got: {json})",
6515            );
6516        }
6517    }
6518
6519    #[test]
6520    fn supervisor_key_consts_are_pairwise_distinct() {
6521        // Cross-axis drift-detection pin: a future collapse of two
6522        // canonical top-level byte-strings onto the same value (e.g. an
6523        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
6524        // also read `"estrategia"`) would silently reroute every
6525        // downstream probe on one axis onto the sibling axis's overlay
6526        // entry and pass every propagation-probe test that expected only
6527        // the stale axis's value. Peer of the sibling four-way distinct
6528        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
6529        let all = [
6530            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6531            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6532            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6533            crate::render::SUPERVISOR_KEY_CHILDREN,
6534        ];
6535        for (i, a) in all.iter().enumerate() {
6536            for b in all.iter().skip(i + 1) {
6537                assert_ne!(
6538                    a, b,
6539                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
6540                     canonical byte-sequences — got `{a}` == `{b}`",
6541                );
6542            }
6543        }
6544    }
6545
6546    #[test]
6547    fn supervisor_key_consts_are_lower_camel_case_shape() {
6548        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
6549        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6550        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6551        // capital, no whitespace / dots) — the canonical shape the
6552        // `#[serde(rename_all = "camelCase")]` derive produces on
6553        // `SupervisorSpec`. A future flip to a non-camelCase attribute
6554        // at the derive surfaces both here (this test fails on the
6555        // stale-constant shape) and at
6556        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6557        // (that test fails on the mismatch between const and derive).
6558        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
6559        // (d8b8b4f) on the sibling M2 `:limits` axis.
6560        for key in [
6561            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6562            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6563            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6564            crate::render::SUPERVISOR_KEY_CHILDREN,
6565        ] {
6566            assert!(
6567                !key.is_empty(),
6568                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
6569            );
6570            let first = key.chars().next().unwrap();
6571            assert!(
6572                first.is_ascii_lowercase(),
6573                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
6574                 (got {key:?}, leads with {first:?})",
6575            );
6576            assert!(
6577                key.chars().all(|c| c.is_ascii_alphanumeric()),
6578                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
6579                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6580            );
6581        }
6582    }
6583
6584    #[test]
6585    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
6586        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
6587        // (camelCase JSON keys, no leading colon) must never collide
6588        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
6589        // consts (kebab-case author-facing labels with leading colon)
6590        // that sit next to them at `caixa_core::render`. Both families
6591        // cover the same four typed Supervisor slots on two distinct
6592        // axes (author-side kebab vs renderer-side camelCase);
6593        // collapsing either family onto the other's byte-shape would
6594        // silently reroute the render-side probe onto the author-facing
6595        // surface, or vice versa. Peer of the byte-distinctness
6596        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
6597        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
6598        let pairs = [
6599            (
6600                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6601                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
6602            ),
6603            (
6604                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6605                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
6606            ),
6607            (
6608                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6609                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
6610            ),
6611            (
6612                crate::render::SUPERVISOR_KEY_CHILDREN,
6613                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
6614            ),
6615        ];
6616        for (json_key, author_key) in pairs {
6617            assert_ne!(
6618                json_key, author_key,
6619                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
6620                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
6621                 got JSON `{json_key}` == author `{author_key}`",
6622            );
6623        }
6624    }
6625
6626    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
6627
6628    #[test]
6629    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
6630        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
6631        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
6632        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
6633        // keys the `#[serde(rename_all = "camelCase")]` attribute on
6634        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
6635        // pin that each canonical byte-sequence appears verbatim in the
6636        // JSON — a future accidental `rename_all = "snake_case"` /
6637        // `"kebab-case"` / verbatim-field-name flip at the derive
6638        // attribute (any of which would silently break every downstream
6639        // JSON consumer that reaches for one of the three consts via
6640        // `Value::get(...)`) surfaces here as a build-time test failure at
6641        // `supervisor.rs`, not as an apply-time
6642        // `.get(<stale-canonical-const>)` returning `None` far from the
6643        // derive-attr drift's commit. Peer with the enclosing
6644        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6645        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
6646        // discipline the SupervisorSpec top-level lift established,
6647        // extended here to the sibling per-`:children` entry `ChildSpec`
6648        // derive so the last M2 typed-struct sub-block
6649        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
6650        // surface without a lifted serde-key peer joins the substrate's
6651        // "one canonical byte-string per typed serialized-key axis"
6652        // discipline.
6653        let c = ChildSpec {
6654            caixa: "worker".into(),
6655            versao: "^0.1".into(),
6656            restart: RestartPolicy::Permanent,
6657        };
6658        let json = serde_json::to_string(&c).unwrap();
6659        for key in [
6660            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6661            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6662            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6663        ] {
6664            let quoted = format!("\"{key}\"");
6665            assert!(
6666                json.contains(&quoted),
6667                "serialized ChildSpec must carry the lifted \
6668                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
6669                 in the JSON emission (got: {json})",
6670            );
6671        }
6672    }
6673
6674    #[test]
6675    fn supervisor_child_key_consts_are_pairwise_distinct() {
6676        // Cross-axis drift-detection pin: a future collapse of two
6677        // canonical `ChildSpec` per-entry byte-strings onto the same
6678        // value (e.g. an accidental copy-paste flip of
6679        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
6680        // silently reroute every downstream probe on one axis onto the
6681        // sibling axis's overlay entry and pass every propagation-probe
6682        // test that expected only the stale axis's value. Peer of the
6683        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
6684        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
6685        // pair (ce80ca0).
6686        let all = [
6687            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6688            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6689            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6690        ];
6691        for (i, a) in all.iter().enumerate() {
6692            for b in all.iter().skip(i + 1) {
6693                assert_ne!(
6694                    a, b,
6695                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
6696                     distinct canonical byte-sequences — got `{a}` == `{b}`",
6697                );
6698            }
6699        }
6700    }
6701
6702    #[test]
6703    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
6704        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
6705        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6706        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6707        // capital, no whitespace / dots) — the canonical shape the
6708        // `#[serde(rename_all = "camelCase")]` derive produces on
6709        // `ChildSpec`. A future flip to a non-camelCase attribute at the
6710        // derive surfaces both here (this test fails on the
6711        // stale-constant shape) and at
6712        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
6713        // (that test fails on the mismatch between const and derive).
6714        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
6715        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
6716        for key in [
6717            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6718            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6719            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6720        ] {
6721            assert!(
6722                !key.is_empty(),
6723                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
6724            );
6725            let first = key.chars().next().unwrap();
6726            assert!(
6727                first.is_ascii_lowercase(),
6728                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
6729                 byte (got {key:?}, leads with {first:?})",
6730            );
6731            assert!(
6732                key.chars().all(|c| c.is_ascii_alphanumeric()),
6733                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
6734                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6735            );
6736        }
6737    }
6738
6739    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
6740
6741    #[test]
6742    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
6743        // The fail-before-pass-after pin: pre-lift there was no
6744        // single-source binding between the [`RestartStrategy`] variant
6745        // name the un-`rename`d `Serialize` derive emits under
6746        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
6747        // every downstream cluster-side dispatcher (the future
6748        // wasm-operator's per-supervisor sibling-restart branch, the
6749        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
6750        // admission-time enum-arm bind, the `caixa-operator`'s
6751        // hierarchical reconciliation scheduler's per-strategy fan-out)
6752        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
6753        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
6754        // override, or a variant rename in the source — would silently
6755        // rebrand the emitted scalar under one spelling while every
6756        // downstream dispatcher still probed the other, with the failure
6757        // surfacing at the operator's reconcile posture (subtrees coming
6758        // up under the `default()` `OneForOne` arm rather than the typed
6759        // slot's declared strategy — a bad child would then only take
6760        // itself down instead of the sibling set the author intended, so
6761        // shared-state children fall out of sync) far from the source
6762        // rebrand commit and with no field naming the drift. Pinning the
6763        // two paths (the `Serialize` derive's serialized string AND the
6764        // [`RestartStrategy::as_str`] helper) to the same four lifted
6765        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
6766        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
6767        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
6768        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
6769        // byte-strings makes any future drift on either endpoint fail
6770        // here at caixa-core build time. Peer of the M3
6771        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
6772        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
6773        // three-path-convergence discipline, extended to close the
6774        // OTP-shaped per-supervisor sibling-restart axis.
6775        for (variant, expected) in [
6776            (
6777                RestartStrategy::OneForOne,
6778                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6779            ),
6780            (
6781                RestartStrategy::OneForAll,
6782                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6783            ),
6784            (
6785                RestartStrategy::RestForOne,
6786                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6787            ),
6788            (
6789                RestartStrategy::SimpleOneForOne,
6790                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6791            ),
6792        ] {
6793            let json = serde_json::to_string(&variant).unwrap();
6794            assert_eq!(
6795                json,
6796                format!("\"{expected}\""),
6797                "RestartStrategy::{variant:?} must serialize to {expected:?}"
6798            );
6799            assert_eq!(
6800                variant.as_str(),
6801                expected,
6802                "RestartStrategy::{variant:?}.as_str() must return the lifted \
6803                 SUPERVISOR_ESTRATEGIA_* constant"
6804            );
6805        }
6806    }
6807
6808    #[test]
6809    fn supervisor_estrategia_consts_are_pairwise_distinct() {
6810        // Cross-arm drift-detection pin: a future collapse of two
6811        // canonical variant byte-strings onto the same value (e.g. an
6812        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
6813        // to also read `"OneForOne"`) would silently reroute every
6814        // downstream operator's per-strategy dispatch onto the sibling
6815        // arm's reconcile branch and pass every propagation-probe test
6816        // that expected only the stale arm's value — the mis-strategied
6817        // subtree would come up with the wrong sibling-restart posture
6818        // on every subsequent failure. Peer of the sibling four-way
6819        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
6820        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
6821        let all = [
6822            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6823            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6824            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6825            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6826        ];
6827        for (i, a) in all.iter().enumerate() {
6828            for (j, b) in all.iter().enumerate() {
6829                if i != j {
6830                    assert_ne!(
6831                        a, b,
6832                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
6833                         — got duplicate {a:?} at indices {i} and {j}",
6834                    );
6835                }
6836            }
6837        }
6838    }
6839
6840    #[test]
6841    fn restart_strategy_display_routes_through_as_str_helper() {
6842        // The fail-before-pass-after pin on the first half of the
6843        // three-path convergence: pre-convergence the sibling
6844        // OTP-shape typed enum [`RestartStrategy`] carried a
6845        // [`std::fmt::Display`] surface via its
6846        // `#[discriminant(also_display)]` gen-platform derive route,
6847        // which arrived kebab-case as `"one-for-one"` /
6848        // `"one-for-all"` / `"rest-for-one"` /
6849        // `"simple-one-for-one"` while the wire format ran as
6850        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
6851        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
6852        // Every consumer reaching for a strategy byte-string past the
6853        // wire format had to pick between three paths
6854        // ([`RestartStrategy::as_str`], the `Serialize` derive's
6855        // serialized string, or `format!("{v}")` on the
6856        // discriminant-Display route), any two of which a future
6857        // variant rename or `#[serde(rename_all = "kebab-case")]`
6858        // attribute would silently desynchronize. Wiring
6859        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
6860        // closes the third path: every `format!("{v}")` call reaches
6861        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6862        // const the wire format and the [`RestartStrategy::as_str`]
6863        // helper already route through, so a future variant rename
6864        // lands at exactly one place. Pin the routing here so a future
6865        // `impl std::fmt::Display for RestartStrategy`
6866        // reimplementation that hand-rolls the arms instead of
6867        // delegating to [`RestartStrategy::as_str`] fails at
6868        // caixa-core build time. Peer of the M3
6869        // `placement_strategy_display_routes_through_as_str_helper`
6870        // (cc8f749) which the M3 axis converged first.
6871        for &variant in RestartStrategy::ALL {
6872            assert_eq!(
6873                variant.to_string(),
6874                variant.as_str(),
6875                "RestartStrategy::{variant:?} Display must route through \
6876                 RestartStrategy::as_str (single source of truth: the lifted \
6877                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
6878            );
6879        }
6880    }
6881
6882    #[test]
6883    fn restart_strategy_display_matches_serialized_wire_byte_string() {
6884        // The fail-before-pass-after pin on the second half of the
6885        // three-path convergence: `Display` (user-facing text) agrees
6886        // byte-for-byte with the `Serialize` derive's wire format
6887        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
6888        // scalar) on every variant. Pre-convergence the two paths
6889        // were structurally independent — a future
6890        // `#[serde(rename_all = "kebab-case")]` attribute on the
6891        // enum would silently rebrand the emitted wire scalar
6892        // (`one-for-one`, `one-for-all`, `rest-for-one`,
6893        // `simple-one-for-one`) while every consumer that
6894        // pretty-prints the strategy (the future wasm-operator's
6895        // per-supervisor sibling-restart-strategy diagnostic line,
6896        // the future `feira app graph` per-supervisor strategy line,
6897        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
6898        // materializer's admission-webhook rejection body) would
6899        // still emit the PascalCase form the `as_str` / `Display`
6900        // route returns, with the mismatch surfacing at consumer
6901        // parse time / operator dispatch time far from the source
6902        // rebrand commit. Pin the two paths byte-for-byte here so any
6903        // future serde-attribute or variant-rename drift is a
6904        // caixa-core-build-time test failure at this call, not a
6905        // silent per-consumer dispatch miss. Peer of the M3
6906        // `placement_strategy_display_matches_serialized_wire_byte_string`
6907        // (cc8f749) which the M3 axis converged first.
6908        for &variant in RestartStrategy::ALL {
6909            let wire = serde_json::to_string(&variant).unwrap();
6910            let unquoted = wire
6911                .strip_prefix('"')
6912                .and_then(|s| s.strip_suffix('"'))
6913                .expect("serialized RestartStrategy is a JSON string");
6914            assert_eq!(
6915                variant.to_string(),
6916                unquoted,
6917                "RestartStrategy::{variant:?} Display byte-string must match the \
6918                 Serialize derive's wire byte-string (three-path convergence: \
6919                 Display + as_str + Serialize all resolve to the same \
6920                 SUPERVISOR_ESTRATEGIA_* const)"
6921            );
6922        }
6923    }
6924
6925    #[test]
6926    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
6927        // Fail-before-pass-after byte-parity pin on the lifted
6928        // `impl AsRef<str> for RestartStrategy` — asserts the
6929        // standard-library trait impl and the substrate-primitive
6930        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
6931        // to the same `&str` per instance across the four-arm
6932        // closed set, so any future silent detour that routes the
6933        // impl through a divergent projection (a per-arm inline
6934        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
6935        // re-inlining that opens a compile-time link to the un-lifted
6936        // arm-literal, a swap onto the kebab-case
6937        // [`gen_platform::Discriminant`] catalog identity that would
6938        // collide the wire axis with the dispatcher-catalog axis) trips
6939        // at caixa-core test time under `PartialEq` rather than at a
6940        // downstream `impl AsRef<str>`-bound consumer's silent split.
6941        // Sweeps every one of the four arms
6942        // [`RestartStrategy::ALL`] carries so no arm's projection is
6943        // covered only by the sibling wire-format `Serialize` derive
6944        // path. Peer of the sibling
6945        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
6946        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
6947        // top-level `:versao` typed newtype — the two pins together
6948        // cover the substrate primitive's `AsRef<str>` projection axis
6949        // on the paired newtype + closed-set-typed-enum surface.
6950        for &variant in RestartStrategy::ALL {
6951            assert_eq!(
6952                <RestartStrategy as AsRef<str>>::as_ref(&variant),
6953                variant.as_str(),
6954                "AsRef<str> impl on RestartStrategy::{variant:?} must \
6955                 byte-equal RestartStrategy::as_str on the same instance \
6956                 — divergence signals a silent detour off the substrate-\
6957                 primitive accessor"
6958            );
6959        }
6960    }
6961
6962    #[test]
6963    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
6964        // Fail-before-pass-after byte-parity pin on the three-path
6965        // convergence discipline the M2 sibling-restart primitive now
6966        // carries on the `&str`-projection axis:
6967        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
6968        // lifted impl), `format!("{s}")` (the pre-existing
6969        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
6970        // primitive `pub const fn` accessor both trait impls delegate
6971        // through) must resolve to the same byte-string on every
6972        // instance across the four-arm closed set. Refuses any future
6973        // divergence between the two trait impls (a stray
6974        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
6975        // rather than delegating through the shared accessor; a
6976        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
6977        // literal cascade) that would silently split the two
6978        // projection paths of the same closed-set typed enum. Mirrors
6979        // the sibling three-path-convergence discipline the peer
6980        // [`crate::CaixaVersion`] typed newtype carries on its
6981        // `AsRef<str>` / `Display` / `as_str` triple
6982        // (version.rs pin
6983        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
6984        // 16d5c7e).
6985        for &variant in RestartStrategy::ALL {
6986            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
6987            let via_display: String = format!("{variant}");
6988            let via_accessor: &str = variant.as_str();
6989            assert_eq!(via_as_ref, via_accessor);
6990            assert_eq!(via_display, via_accessor);
6991            assert_eq!(via_as_ref, via_display.as_str());
6992        }
6993    }
6994
6995    #[test]
6996    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
6997        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
6998        // exhaustive-iteration surface: every variant appears exactly
6999        // once, and the slice length matches the arm count of the
7000        // closed set. Every consumer that walks the accepted-strategy
7001        // set (a future `feira supervisor --estrategia …` CLI-side
7002        // arg-parse's "did you mean" hint, a future M4 admission-
7003        // webhook's rejection body naming the accepted-`:estrategia`
7004        // list, the [`RestartStrategy::from_wire`] reverse-projection
7005        // consumers that iterate the accept-set for diagnostic
7006        // rendering) reads through this slice, so a future arm addition
7007        // that grows the enum but forgets to grow [`Self::ALL`]
7008        // silently truncates every downstream consumer's accept-set at
7009        // the same pre-addition boundary — this pin fails at caixa-core
7010        // build time on the pairwise-distinct + arm-count invariants.
7011        //
7012        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
7013        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7014        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7015        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7016        // pins on the peer closed-set typed-enum axes.
7017        let all: &[RestartStrategy] = RestartStrategy::ALL;
7018        assert_eq!(
7019            all.len(),
7020            4,
7021            "RestartStrategy::ALL must enumerate every variant of the \
7022             four-arm closed set (OneForOne, OneForAll, RestForOne, \
7023             SimpleOneForOne); got {all:?}"
7024        );
7025        for (i, a) in all.iter().enumerate() {
7026            for (j, b) in all.iter().enumerate() {
7027                if i != j {
7028                    assert_ne!(
7029                        a, b,
7030                        "RestartStrategy::ALL must carry every variant exactly \
7031                         once — got duplicate {a:?} at indices {i} and {j}"
7032                    );
7033                }
7034            }
7035        }
7036        for variant in [
7037            RestartStrategy::OneForOne,
7038            RestartStrategy::OneForAll,
7039            RestartStrategy::RestForOne,
7040            RestartStrategy::SimpleOneForOne,
7041        ] {
7042            assert!(
7043                all.contains(&variant),
7044                "RestartStrategy::ALL must contain {variant:?} — a future arm \
7045                 addition that grows the enum but forgets to grow the ALL slice \
7046                 silently truncates every downstream consumer's accept-set at \
7047                 the pre-addition boundary"
7048            );
7049        }
7050    }
7051
7052    #[test]
7053    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
7054        // Fail-before-pass-after pin on the forward accept-set of the
7055        // [`RestartStrategy::from_wire`] reverse projection: every
7056        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7057        // constant the [`RestartStrategy::as_str`] emitter walks parses
7058        // back to its paired variant. Any future arm addition that
7059        // grows the emitter's `as_str` match but forgets to grow the
7060        // parser's `from_wire` match silently splits the two halves of
7061        // the round-trip — the wire byte-string one non-serde consumer
7062        // parses from the one the emitter wrote — with the failure
7063        // surfacing at parse time far from the rebrand commit. Pinning
7064        // the four-arm accept-set here catches the drift at caixa-core
7065        // build time.
7066        //
7067        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
7068        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
7069        // accept-set pins on the peer closed-set typed-enum `str → Self`
7070        // axes.
7071        for (wire, expected) in [
7072            (
7073                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7074                RestartStrategy::OneForOne,
7075            ),
7076            (
7077                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7078                RestartStrategy::OneForAll,
7079            ),
7080            (
7081                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7082                RestartStrategy::RestForOne,
7083            ),
7084            (
7085                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7086                RestartStrategy::SimpleOneForOne,
7087            ),
7088        ] {
7089            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7090                panic!(
7091                    "RestartStrategy::from_wire({wire:?}) must accept every \
7092                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
7093                     lifted canonical byte-string that RestartStrategy::{expected:?} \
7094                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
7095                )
7096            });
7097            assert_eq!(
7098                parsed, expected,
7099                "RestartStrategy::from_wire({wire:?}) must return \
7100                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
7101            );
7102        }
7103    }
7104
7105    #[test]
7106    fn restart_strategy_from_wire_round_trips_through_as_str() {
7107        // Fail-before-pass-after pin on the closed round-trip between
7108        // the forward [`RestartStrategy::as_str`] emitter and the
7109        // reverse [`RestartStrategy::from_wire`] parser: for every
7110        // variant in [`RestartStrategy::ALL`], parsing the emitter's
7111        // output must return exactly the same variant. Any per-arm
7112        // divergence — a future arm added to `as_str` but not
7113        // `from_wire`, an accidental copy-paste flip in one but not
7114        // the other — silently splits the emit and parse halves and
7115        // the failure surfaces at consumer parse time far from the
7116        // drift site. The `ALL`-iterating shape means a future arm
7117        // addition picks up the coverage by construction.
7118        //
7119        // Peer of the sibling
7120        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
7121        // (18c7342) round-trip pin on
7122        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
7123        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
7124        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
7125        for &variant in RestartStrategy::ALL {
7126            let wire = variant.as_str();
7127            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7128                panic!(
7129                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7130                     must be Some({variant:?}) — the two halves of the round-trip \
7131                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
7132                     got None on wire byte-string {wire:?}"
7133                )
7134            });
7135            assert_eq!(
7136                parsed, variant,
7137                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7138                 must round-trip to the same variant; got {parsed:?}"
7139            );
7140        }
7141    }
7142
7143    #[test]
7144    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
7145        // Fail-before-pass-after pin on the closed-set refusal
7146        // discipline of [`RestartStrategy::from_wire`]: every
7147        // byte-string outside the four-arm accept-set returns `None`
7148        // rather than silently collapsing onto the [`Default`]
7149        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
7150        // exercised here sweeps the load-bearing drift shapes: the
7151        // empty string (a stripped serde-attribute drift), all-
7152        // whitespace strings (the canonical text-editor accidental
7153        // padding shape), the kebab-case dispatcher-catalog identities
7154        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
7155        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
7156        // derived [`std::str::FromStr`] accept-set, which parses the
7157        // *other* axis of this enum's two-axis split and must not leak
7158        // into the `from_wire` PascalCase-wire accept-set), the
7159        // lowercased single-word forms (`"oneforone"`), the padded
7160        // canonical scalar (`" OneForOne "`), the trailing-newline
7161        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
7162        // (`"AllForOne"` — the canonical typo direction).
7163        //
7164        // Peer of the sibling
7165        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
7166        // (2aa6d23) +
7167        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
7168        // (18c7342) refusal pins on the peer closed-set typed-enum
7169        // axes.
7170        for bad in [
7171            "",
7172            " ",
7173            "\n",
7174            "\t",
7175            "one-for-one",
7176            "one-for-all",
7177            "rest-for-one",
7178            "simple-one-for-one",
7179            "oneforone",
7180            "OneForOnes",
7181            "one_for_one",
7182            "one for one",
7183            "ONEFORONE",
7184            "OneForOne ",
7185            " OneForOne",
7186            " SimpleOneForOne ",
7187            "OneForOne\n",
7188            "restforone",
7189            "REST_FOR_ONE",
7190            "AllForOne",
7191            "Simple",
7192            "?",
7193        ] {
7194            assert!(
7195                RestartStrategy::from_wire(bad).is_none(),
7196                "RestartStrategy::from_wire({bad:?}) must return None — the \
7197                 parser's accept-set is exactly the four RestartStrategy::as_str \
7198                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
7199                 and this byte-string is outside that closed set"
7200            );
7201        }
7202    }
7203
7204    #[test]
7205    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
7206        // Fail-before-pass-after pin on the fourth path of the four-path
7207        // convergence: `from_wire` (the reverse projection) inverts the
7208        // `Serialize` derive's wire byte-string on every variant.
7209        // Together with the pre-existing three-path convergence
7210        // (`Display` + `as_str` + `Serialize` all resolve to the same
7211        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
7212        // pinned by
7213        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
7214        // this closes the round-trip: the wire byte-string the
7215        // `Serialize` derive emits parses back to the same variant
7216        // through `from_wire`, so any future serde-attribute or variant-
7217        // rename drift on the emit half now surfaces as a matched drift
7218        // on the parse half at caixa-core build time — the two halves
7219        // migrate as a unit through the lifted consts on any future
7220        // rename, and the round-trip cannot silently split.
7221        //
7222        // Peer of the sibling
7223        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7224        // (18c7342) wire-format pin on
7225        // [`crate::aplicacao::PlacementStrategy::from_wire`].
7226        for &variant in RestartStrategy::ALL {
7227            let wire = serde_json::to_string(&variant).unwrap();
7228            let unquoted = wire
7229                .strip_prefix('"')
7230                .and_then(|s| s.strip_suffix('"'))
7231                .expect("serialized RestartStrategy is a JSON string");
7232            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
7233                panic!(
7234                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
7235                     Serialize derive's wire byte-string for \
7236                     RestartStrategy::{variant:?} — the four-path convergence \
7237                     (Display + as_str + Serialize + from_wire) resolves through \
7238                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
7239                )
7240            });
7241            assert_eq!(
7242                parsed, variant,
7243                "RestartStrategy::from_wire of the Serialize derive's wire \
7244                 byte-string for RestartStrategy::{variant:?} must round-trip \
7245                 to the same variant; got {parsed:?}"
7246            );
7247        }
7248    }
7249
7250    #[test]
7251    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
7252        // Fail-before-pass-after byte-parity pin on the newly lifted
7253        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
7254        // library trait impl and the substrate-primitive
7255        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
7256        // the same four-arm accept-set across every arm the exhaustive
7257        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7258        // detour that routes the trait impl through a divergent projection
7259        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
7260        // … }` re-inlining that opens a compile-time link to the un-
7261        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
7262        // attribute drift that silently splits the wire byte-string from
7263        // every consumer that reaches for this typed dispatch, an
7264        // accidental swap onto the kebab-case dispatcher-catalog axis the
7265        // pre-existing [`std::str::FromStr`] impl parses through and which
7266        // would collide the two-axis wire/catalog split the sibling
7267        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
7268        // trips at caixa-core test time under `assert_eq!` rather than at
7269        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
7270        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
7271        // carries so no arm's projection is covered only by the sibling
7272        // method-named `from_wire` path. Peer of the sibling
7273        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
7274        // (3c83606),
7275        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
7276        // (bf33136), and the M3
7277        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
7278        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
7279        // onto the first M2-OTP-shape closed-set typed enum on the caixa
7280        // surface.
7281        for &variant in RestartStrategy::ALL {
7282            let wire = variant.as_str();
7283            assert_eq!(
7284                <RestartStrategy as TryFrom<&str>>::try_from(wire),
7285                Ok(variant),
7286                "TryFrom<&str> impl on RestartStrategy must round-trip \
7287                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
7288                 Ok(RestartStrategy::{variant:?}) — divergence from \
7289                 RestartStrategy::from_wire signals a silent detour off \
7290                 the substrate-primitive accessor"
7291            );
7292            assert_eq!(
7293                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
7294                RestartStrategy::from_wire(wire),
7295                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
7296                 RestartStrategy::from_wire on the same input"
7297            );
7298        }
7299    }
7300
7301    #[test]
7302    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
7303        // Rejection witness on the `impl TryFrom<&str> for
7304        // RestartStrategy` — sweeps a candidate set of byte-strings
7305        // outside the four-arm PascalCase wire accept-set the sibling
7306        // [`RestartStrategy::as_str`] emits and asserts every one lands on
7307        // `Err(())`, so a future accidental widening of the trait impl's
7308        // accept-set (a stray additional
7309        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
7310        // path, a silent inclusion of the kebab-case dispatcher-catalog
7311        // byte-string the pre-existing [`std::str::FromStr`] impl the
7312        // [`gen_platform::FromStrKind`] derive installs parses onto the
7313        // wire axis — which would collide the two-axis
7314        // wire/dispatcher-catalog split the sibling
7315        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
7316        // an English-rebrand or plural-arm silent alias that would
7317        // widen the wire accept-set past the OTP-canonical four) trips at
7318        // caixa-core test time. The candidate set includes the empty
7319        // string, whitespace-only padding, the kebab-case dispatcher-
7320        // catalog byte-strings on the sibling axis (a caller who confuses
7321        // the two axes trips here rather than at a downstream consumer's
7322        // silent reject), a lowercase / uppercase / mixed-case fold of
7323        // each PascalCase arm (a caller who assumes case-fold acceptance
7324        // trips here), leading/trailing whitespace padding, the trailing-
7325        // newline shape, quote-wrapped candidates, and a residual set of
7326        // plausible-but-wrong English rebrand candidates. Peer of the
7327        // sibling
7328        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
7329        // (3c83606) and
7330        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
7331        // (6fd00cd) rejection witnesses.
7332        let rejected: &[&str] = &[
7333            "",
7334            " ",
7335            "\n",
7336            "\t",
7337            "one-for-one",
7338            "one-for-all",
7339            "rest-for-one",
7340            "simple-one-for-one",
7341            "oneforone",
7342            "one_for_one",
7343            "OneForOnes",
7344            "ONEFORONE",
7345            "oneforall",
7346            "restforone",
7347            "simpleoneforone",
7348            "OneForOne ",
7349            " OneForOne",
7350            " OneForAll ",
7351            "OneForOne\n",
7352            "RestForOne\t",
7353            "OneForEach",
7354            "AllForOne",
7355            "one for one",
7356            "\"OneForOne\"",
7357            "?",
7358        ];
7359        for &input in rejected {
7360            assert_eq!(
7361                <RestartStrategy as TryFrom<&str>>::try_from(input),
7362                Err(()),
7363                "TryFrom<&str> impl on RestartStrategy must reject the \
7364                 non-wire byte-string {input:?} — silent acceptance signals \
7365                 an accept-set widening off the paired \
7366                 RestartStrategy::from_wire resolver"
7367            );
7368        }
7369    }
7370
7371    #[test]
7372    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
7373        // Cross-axis partition pin: the paired `TryFrom<&str>` and
7374        // `from_wire` reverse projections must resolve identically on
7375        // *every* input, not just the ones [`RestartStrategy::ALL`]
7376        // enumerates. Sweeps a mixed candidate set spanning accepted
7377        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
7378        // dispatcher-catalog byte-strings, empty, whitespace-padded,
7379        // quoted, English-rebrand candidates) inputs and asserts the
7380        // trait's `Result::ok()` projection byte-equals the method-named
7381        // resolver's `Option<Self>` return-shape on each, locking the two
7382        // paths together by construction so any future detour (a stray
7383        // `try_from` special-case that widens or narrows the accept-set
7384        // outside the paired `from_wire` resolver, an accidental swap
7385        // onto the kebab-case [`std::str::FromStr`] impl the
7386        // [`gen_platform::FromStrKind`] derive installs on the sibling
7387        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
7388        // the sibling
7389        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
7390        // pin — extends the round-trip discipline onto the M2-OTP-shape
7391        // sibling-restart axis.
7392        let candidates: &[&str] = &[
7393            "OneForOne",
7394            "OneForAll",
7395            "RestForOne",
7396            "SimpleOneForOne",
7397            "",
7398            "one-for-one",
7399            "one-for-all",
7400            "rest-for-one",
7401            "simple-one-for-one",
7402            "oneforone",
7403            "unknown",
7404            "OneForOne ",
7405            " OneForOne",
7406            "\"OneForOne\"",
7407            "OneForEach",
7408            "?",
7409        ];
7410        for &input in candidates {
7411            let via_trait: Option<RestartStrategy> =
7412                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
7413            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
7414            assert_eq!(
7415                via_trait, via_method,
7416                "TryFrom<&str> and from_wire must resolve identically on \
7417                 input {input:?} — divergence signals the two reverse-\
7418                 projection paths have drifted onto different accept-sets"
7419            );
7420        }
7421    }
7422
7423    #[test]
7424    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
7425        // Fail-before-pass-after byte-parity pin on the newly lifted
7426        // `impl From<RestartStrategy> for &'static str` — asserts the
7427        // standard-library trait impl and the substrate-primitive
7428        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
7429        // the same four-arm emit-set across every arm the exhaustive
7430        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7431        // detour that routes the trait impl through a divergent
7432        // projection (a per-arm inline `match strategy { OneForOne =>
7433        // "OneForOne", … }` re-inlining that opens a compile-time link to
7434        // the un-lifted arm-literal, an accidental swap onto the sibling
7435        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
7436        // would collide the two-axis wire/catalog split the sibling
7437        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
7438        // at caixa-core test time under `assert_eq!` rather than at a
7439        // downstream `impl Into<&'static str>`-bound consumer's silent
7440        // split. Sweeps every one of the four arms
7441        // [`RestartStrategy::ALL`] carries so no arm's projection is
7442        // covered only by the sibling method-named `as_str` /
7443        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
7444        // `<&'static str as From<RestartStrategy>>::from` output in a
7445        // `const`-shape binding to make the `'static` lifetime promise a
7446        // build-time invariant — a future accidental downgrade of any of
7447        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7448        // constants to a non-`&'static str` (a `String::leak()`-produced
7449        // return, a `Box::leak`-cast) trips at caixa-core build time
7450        // rather than at a downstream `'static`-bound consumer.
7451        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7452        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7453        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7454        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7455        for &variant in RestartStrategy::ALL {
7456            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7457            let via_method: &'static str = variant.as_str();
7458            assert_eq!(
7459                via_trait, via_method,
7460                "From<RestartStrategy> for &'static str impl must round-trip \
7461                 RestartStrategy::{variant:?} to the same lifted \
7462                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
7463                 divergence signals a silent detour off the substrate-primitive \
7464                 accessor"
7465            );
7466            let via_into: &'static str = variant.into();
7467            assert_eq!(
7468                via_into, via_method,
7469                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
7470                 byte-equal RestartStrategy::as_str on the same input — the \
7471                 blanket-derived Into shape must resolve to the same as_str \
7472                 dispatch as the explicit From impl"
7473            );
7474        }
7475        assert_eq!(
7476            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7477            [
7478                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7479                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7480                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7481                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7482            ],
7483            "const-context RestartStrategy::as_str must resolve to the four \
7484             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
7485             downgrade of any arm to a non-const or non-static byte-string \
7486             breaks the `&'static str`-lifetime promise the paired \
7487             From<RestartStrategy> for &'static str impl carries by \
7488             construction"
7489        );
7490    }
7491
7492    #[test]
7493    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
7494        // Cross-axis partition pin: the paired trait-idiomatic
7495        // `From<RestartStrategy> for &'static str` forward projection and
7496        // the method-named [`RestartStrategy::as_str`] forward projection
7497        // must resolve identically on *every* arm, not just the ones
7498        // named in the primary byte-parity pin above. Sweeps every
7499        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
7500        // output byte-equals the method-named accessor's return-value on
7501        // each, locking the two forward-projection paths together by
7502        // construction so any future detour (a stray `From` special-case
7503        // that lands on a divergent per-arm literal outside the paired
7504        // `as_str` dispatch, a hypothetical rebrand touching one axis
7505        // without the other) trips at caixa-core test time. Peer of the
7506        // sibling reverse-projection partition pin
7507        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7508        // — extends the round-trip discipline onto the trait-idiomatic
7509        // *forward* axis, closing the two-way `Self ↔ &'static str`
7510        // round-trip on the trait-idiomatic pair
7511        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
7512        // well as the pre-existing method-named pair
7513        // (`as_str` + `from_wire`).
7514        for &variant in RestartStrategy::ALL {
7515            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7516            let via_method: &'static str = variant.as_str();
7517            assert_eq!(
7518                via_trait, via_method,
7519                "From<RestartStrategy> for &'static str and \
7520                 RestartStrategy::as_str must resolve identically on \
7521                 RestartStrategy::{variant:?} — divergence signals the \
7522                 two forward-projection paths have drifted onto different \
7523                 emit-sets"
7524            );
7525        }
7526        // Round-trip witness: every arm's forward `From` output re-parses
7527        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
7528        // to the original variant. Closes the two-way `RestartStrategy ↔
7529        // &'static str` round-trip on the trait-idiomatic axis pair,
7530        // mirroring the pre-existing method-named `as_str` + `from_wire`
7531        // round-trip on the substrate-primitive axis pair.
7532        for &variant in RestartStrategy::ALL {
7533            let emitted: &'static str = variant.into();
7534            let re_parsed: Result<RestartStrategy, ()> =
7535                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7536            assert_eq!(
7537                re_parsed,
7538                Ok(variant),
7539                "trait-idiomatic axis pair must round-trip \
7540                 RestartStrategy::{variant:?} through `.into::<&'static \
7541                 str>()` and back through `TryFrom<&str>` — a break signals \
7542                 the forward-emit and reverse-parse axes have drifted onto \
7543                 different vocabularies"
7544            );
7545        }
7546    }
7547
7548    #[test]
7549    fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
7550        // Fail-before-pass-after byte-parity pin on the newly lifted
7551        // `impl From<&RestartStrategy> for &'static str` — asserts the
7552        // borrowed-input standard-library trait impl and the substrate-
7553        // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
7554        // resolve to the same four-arm emit-set across every arm the
7555        // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
7556        // `From` trait does not auto-derive the borrowed-input sibling
7557        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
7558        // where T: Copy, U: From<T>` blanket in `core`), so the
7559        // borrowed-input axis is a distinct trait-idiomatic surface
7560        // that a `.iter().map(Into::into)` shape over
7561        // [`RestartStrategy::ALL`] (whose iterator yields
7562        // `&RestartStrategy`, not `RestartStrategy`) reaches through
7563        // this impl and no other — the paired owned-input
7564        // [`From<RestartStrategy>`] impl requires an explicit
7565        // `.copied()` / dereference before the trait fires.
7566        // Materializes the `<&'static str as
7567        // From<&RestartStrategy>>::from` output in a `const`-shape
7568        // binding to make the `'static` lifetime promise a build-time
7569        // invariant.
7570        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7571        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7572        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7573        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7574        for variant in RestartStrategy::ALL {
7575            let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
7576            let via_method: &'static str = variant.as_str();
7577            assert_eq!(
7578                via_trait, via_method,
7579                "From<&RestartStrategy> for &'static str impl must \
7580                 round-trip &RestartStrategy::{variant:?} to the same \
7581                 lifted SUPERVISOR_ESTRATEGIA_* const \
7582                 RestartStrategy::as_str returns — divergence signals a \
7583                 silent detour off the substrate-primitive accessor"
7584            );
7585            let via_into: &'static str = variant.into();
7586            assert_eq!(
7587                via_into, via_method,
7588                "Into<&'static str>::into on &RestartStrategy::{variant:?} \
7589                 must byte-equal RestartStrategy::as_str on the same input — \
7590                 the blanket-derived Into shape must resolve to the same \
7591                 as_str dispatch as the explicit From impl"
7592            );
7593        }
7594        assert_eq!(
7595            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7596            [
7597                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7598                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7599                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7600                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7601            ],
7602            "const-context RestartStrategy::as_str must resolve to the \
7603             four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
7604             input From<&RestartStrategy> for &'static str impl inherits \
7605             its `'static` lifetime promise from the same accessor the \
7606             owned-input sibling routes through"
7607        );
7608    }
7609
7610    #[test]
7611    fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
7612        // Cross-axis partition pin: the paired trait-idiomatic
7613        // owned-input `From<RestartStrategy> for &'static str` (523157d
7614        // campaign-shape) and borrowed-input `From<&RestartStrategy> for
7615        // &'static str` (this lift) forward projections must resolve
7616        // identically on every arm, locking the two input-shape paths
7617        // together so any future detour trips at caixa-core test time.
7618        // Then a witness that a `.iter().map(Into::into)` pipe over
7619        // [`RestartStrategy::ALL`] (whose iterator yields
7620        // `&RestartStrategy`) materializes the four-arm accept-set
7621        // through the borrowed-input axis alone — the exact shape a
7622        // future wasm-operator per-supervisor sibling-restart-strategy
7623        // diagnostic line, a future substrate-wide per-arm diagnostic
7624        // column, or a
7625        // `HashMap::<&'static str, RestartStrategy>::from_iter(
7626        //     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
7627        // per-strategy lookup reaches through — closing the two-way
7628        // owned/borrowed input-shape symmetry on the forward-projection
7629        // trait-idiomatic axis. Peer of the sibling
7630        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7631        // (64aa742) /
7632        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7633        // (5ab993a) /
7634        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7635        // (807b0b5) partition pins on the sibling closed-set typed-enum
7636        // discriminator axes — extends the borrowed-input axis
7637        // discipline onto the first M2 OTP-shape sibling-restart
7638        // closed-set typed enum on the caixa surface. Also closes the
7639        // direct two-way `&Self → &'static str → Self` round-trip via
7640        // the paired [`TryFrom<&str>`] axis — unlike the peer
7641        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
7642        // lowercase Portuguese diagnostic bytes while the reverse
7643        // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
7644        // trip through an intermediate wire-vocab hop), the
7645        // [`RestartStrategy::as_str`] emit and
7646        // [`RestartStrategy::from_wire`] parse share the same
7647        // `PascalCase` vocabulary by construction, so the borrowed-
7648        // input forward axis and the reverse axis compose directly.
7649        for &variant in RestartStrategy::ALL {
7650            let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7651            let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
7652            assert_eq!(
7653                owned, borrowed,
7654                "From<RestartStrategy> and From<&RestartStrategy> for \
7655                 &'static str must resolve identically on \
7656                 RestartStrategy::{variant:?} — divergence signals the \
7657                 owned-input and borrowed-input forward-projection paths \
7658                 have drifted onto different emit-sets"
7659            );
7660        }
7661        let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
7662        let via_method: Vec<&'static str> =
7663            RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
7664        assert_eq!(
7665            via_iter, via_method,
7666            "`.iter().map(Into::into)` over RestartStrategy::ALL must \
7667             byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
7668             borrowed-input `From<&RestartStrategy> for &'static str` \
7669             axis is what makes the `.iter().map(Into::into)` shape route \
7670             through the substrate-primitive `RestartStrategy::as_str` \
7671             accessor rather than through a per-call-site `.copied()` / \
7672             dereference detour"
7673        );
7674        for variant in RestartStrategy::ALL {
7675            let emitted: &'static str = variant.into();
7676            let re_parsed: Result<RestartStrategy, ()> =
7677                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7678            assert_eq!(
7679                re_parsed,
7680                Ok(*variant),
7681                "trait-idiomatic borrowed-input forward-projection + \
7682                 reverse-projection axis pair must round-trip \
7683                 &RestartStrategy::{variant:?} through `.into::<&'static \
7684                 str>()` (via the borrowed-input axis) and back through \
7685                 `TryFrom<&str>` — a break signals the borrowed-input \
7686                 forward-emit and reverse-parse axes have drifted onto \
7687                 different vocabularies"
7688            );
7689        }
7690    }
7691
7692    #[test]
7693    fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
7694        // Fail-before-pass-after byte-parity pin on the newly lifted
7695        // `impl From<RestartStrategy> for String` — asserts the
7696        // owned-`String`-returning standard-library trait impl and the
7697        // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
7698        // accessor resolve to the same four-arm emit-set across every
7699        // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
7700        // Rust's standard library does not carry a blanket
7701        // `impl<T: AsRef<str>> From<T> for String` (nor an
7702        // `impl<T: fmt::Display> From<T> for String`), so the
7703        // owned-`String` forward-projection axis is a distinct
7704        // trait-idiomatic surface that a
7705        // `let key: String = strategy.into();`-shaped call site
7706        // reaches through this impl and no other — the paired sibling
7707        // `From<RestartStrategy> for &'static str` impl forces every
7708        // owned-`String` call site through an explicit
7709        // `.to_owned()` / `String::from` restatement.
7710        for &variant in RestartStrategy::ALL {
7711            let via_trait: String = <String as From<RestartStrategy>>::from(variant);
7712            let via_method: &'static str = variant.as_str();
7713            assert_eq!(
7714                via_trait.as_str(),
7715                via_method,
7716                "From<RestartStrategy> for String impl must round-trip \
7717                 RestartStrategy::{variant:?} to the same lifted \
7718                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
7719                 returns — divergence signals a silent detour off the \
7720                 substrate-primitive accessor"
7721            );
7722            let via_into: String = variant.into();
7723            assert_eq!(
7724                via_into.as_str(),
7725                via_method,
7726                "Into<String>::into on RestartStrategy::{variant:?} must \
7727                 byte-equal RestartStrategy::as_str on the same input — the \
7728                 blanket-derived Into shape must resolve to the same as_str \
7729                 dispatch as the explicit From impl"
7730            );
7731        }
7732    }
7733
7734    #[test]
7735    fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
7736        // Cross-axis partition pin: the paired trait-idiomatic
7737        // owned-`String` `From<RestartStrategy> for String` (this lift)
7738        // and owned-`&'static str` `From<RestartStrategy> for &'static
7739        // str` (523157d) forward projections must resolve identically
7740        // on every arm, locking the two return-type-shape paths
7741        // together so any future detour trips at caixa-core test time.
7742        // Also byte-parity witness against the sibling
7743        // [`ToString::to_string`] surface routed through
7744        // [`std::fmt::Display`] — the three owned-heap-string paths
7745        // (`.into::<String>()`, `String::from`, `.to_string()`) must
7746        // resolve identically on every arm so a future consumer that
7747        // picks any of the three lands on the same lifted
7748        // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
7749        // witness through the paired trait-idiomatic reverse
7750        // [`TryFrom<&str>`] axis on the owned-`String`'s
7751        // [`String::as_str`] borrow that closes the two-way
7752        // `Self → String → Self` round-trip on the trait-idiomatic
7753        // owned-`String` forward + reverse axis pair.
7754        for &variant in RestartStrategy::ALL {
7755            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
7756            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7757            assert_eq!(
7758                owned_string.as_str(),
7759                owned_static,
7760                "From<RestartStrategy> for String and From<RestartStrategy> \
7761                 for &'static str must resolve identically on \
7762                 RestartStrategy::{variant:?} — divergence signals the \
7763                 owned-`String` and owned-`&'static str` forward-projection \
7764                 return-type-shape paths have drifted onto different \
7765                 emit-sets"
7766            );
7767            let via_to_string: String = variant.to_string();
7768            assert_eq!(
7769                owned_string, via_to_string,
7770                "From<RestartStrategy> for String must byte-equal \
7771                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
7772                 divergence signals the trait-idiomatic owned-`String` \
7773                 forward-projection axis and the ToString-through-Display \
7774                 axis have drifted onto different emit-sets"
7775            );
7776        }
7777        let via_iter: Vec<String> = RestartStrategy::ALL
7778            .iter()
7779            .copied()
7780            .map(String::from)
7781            .collect();
7782        let via_method: Vec<String> = RestartStrategy::ALL
7783            .iter()
7784            .map(|s| s.as_str().to_owned())
7785            .collect();
7786        assert_eq!(
7787            via_iter, via_method,
7788            "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
7789             must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
7790             every arm — the owned-`String` `From<RestartStrategy> for \
7791             String` axis is what makes the `String::from` composition \
7792             route through the substrate-primitive `RestartStrategy::as_str` \
7793             accessor rather than through a per-call-site `.to_owned()` / \
7794             `String::from(strategy.as_str())` detour"
7795        );
7796        for &variant in RestartStrategy::ALL {
7797            let emitted: String = variant.into();
7798            let re_parsed: Result<RestartStrategy, ()> =
7799                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
7800            assert_eq!(
7801                re_parsed,
7802                Ok(variant),
7803                "trait-idiomatic owned-`String` forward-projection + \
7804                 reverse-projection axis pair must round-trip \
7805                 RestartStrategy::{variant:?} through `.into::<String>()` \
7806                 and back through `TryFrom<&str>` on the owned-`String`'s \
7807                 String::as_str borrow — a break signals the owned-`String` \
7808                 forward-emit and reverse-parse axes have drifted onto \
7809                 different vocabularies"
7810            );
7811        }
7812    }
7813
7814    #[test]
7815    fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
7816        // Fail-before-pass-after byte-parity pin on the newly lifted
7817        // `impl From<&RestartStrategy> for String` — asserts the
7818        // borrowed-input owned-`String`-returning standard-library trait
7819        // impl and the substrate-primitive [`RestartStrategy::as_str`]
7820        // `pub const fn` accessor resolve to the same four-arm emit-set
7821        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
7822        // enumerates. Rust's standard library does not carry a blanket
7823        // `impl<T: AsRef<str>> From<&T> for String` (nor an
7824        // `impl<T: fmt::Display> From<&T> for String`), so the
7825        // borrowed-input owned-`String` forward-projection axis is a
7826        // distinct trait-idiomatic surface that a
7827        // `let key: String = (&strategy).into();`-shaped call site
7828        // reaches through this impl and no other — the paired sibling
7829        // `From<RestartStrategy> for String` impl forces every
7830        // borrowed-input call site through an explicit `Copy` deref
7831        // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
7832        // `.to_string()` detour.
7833        for &variant in RestartStrategy::ALL {
7834            let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
7835            let via_method: &'static str = variant.as_str();
7836            assert_eq!(
7837                via_trait.as_str(),
7838                via_method,
7839                "From<&RestartStrategy> for String impl must round-trip \
7840                 &RestartStrategy::{variant:?} to the same lifted \
7841                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
7842                 returns — divergence signals a silent detour off the \
7843                 substrate-primitive accessor"
7844            );
7845            let via_into: String = (&variant).into();
7846            assert_eq!(
7847                via_into.as_str(),
7848                via_method,
7849                "Into<String>::into on &RestartStrategy::{variant:?} must \
7850                 byte-equal RestartStrategy::as_str on the same input — the \
7851                 blanket-derived Into shape must resolve to the same as_str \
7852                 dispatch as the explicit From impl"
7853            );
7854        }
7855    }
7856
7857    #[test]
7858    fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
7859        // Cross-axis partition pin: the newly lifted trait-idiomatic
7860        // borrowed-input owned-`String` `From<&RestartStrategy> for
7861        // String` (this lift), the paired owned-input owned-`String`
7862        // `From<RestartStrategy> for String` (7baa18a), the paired
7863        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
7864        // for &'static str` (e941836), and the paired owned-input
7865        // owned-`&'static str` `From<RestartStrategy> for &'static str`
7866        // (523157d) — every corner of the `{Self, &Self} × {&'static
7867        // str, String}` 2×2 trait-idiomatic projection family — must
7868        // resolve identically on every arm, locking the four
7869        // return-shape × input-shape paths together so any future
7870        // detour trips at caixa-core test time. Also byte-parity
7871        // witness against the sibling [`ToString::to_string`] surface
7872        // routed through [`std::fmt::Display`] and a direct round-trip
7873        // witness through the paired trait-idiomatic reverse
7874        // [`TryFrom<&str>`] axis on the owned-`String`'s
7875        // [`String::as_str`] borrow that closes the two-way
7876        // `&Self → String → Self` round-trip on the trait-idiomatic
7877        // borrowed-input owned-`String` forward + reverse axis pair.
7878        for &variant in RestartStrategy::ALL {
7879            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
7880            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
7881            let borrowed_static: &'static str =
7882                <&'static str as From<&RestartStrategy>>::from(&variant);
7883            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7884            assert_eq!(
7885                borrowed_string, owned_string,
7886                "From<&RestartStrategy> for String and From<RestartStrategy> \
7887                 for String must resolve identically on \
7888                 RestartStrategy::{variant:?} — divergence signals the \
7889                 borrowed-input and owned-input owned-`String` \
7890                 forward-projection input-shape paths have drifted onto \
7891                 different emit-sets"
7892            );
7893            assert_eq!(
7894                borrowed_string.as_str(),
7895                borrowed_static,
7896                "From<&RestartStrategy> for String and From<&RestartStrategy> \
7897                 for &'static str must resolve identically on \
7898                 RestartStrategy::{variant:?} — divergence signals the \
7899                 borrowed-input `&'static str` and owned-`String` \
7900                 return-shape paths have drifted onto different emit-sets"
7901            );
7902            assert_eq!(
7903                borrowed_string.as_str(),
7904                owned_static,
7905                "From<&RestartStrategy> for String and From<RestartStrategy> \
7906                 for &'static str must resolve identically on \
7907                 RestartStrategy::{variant:?} — divergence signals a break \
7908                 in the diagonal corner of the {{Self, &Self}} × \
7909                 {{&'static str, String}} 2×2 trait-idiomatic \
7910                 projection family"
7911            );
7912            let via_to_string: String = variant.to_string();
7913            assert_eq!(
7914                borrowed_string, via_to_string,
7915                "From<&RestartStrategy> for String must byte-equal \
7916                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
7917                 divergence signals the trait-idiomatic borrowed-input \
7918                 owned-`String` forward-projection axis and the \
7919                 ToString-through-Display axis have drifted onto different \
7920                 emit-sets"
7921            );
7922        }
7923        let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
7924        let via_method: Vec<String> = RestartStrategy::ALL
7925            .iter()
7926            .map(|s| s.as_str().to_owned())
7927            .collect();
7928        assert_eq!(
7929            via_iter, via_method,
7930            "`.iter().map(String::from)` over RestartStrategy::ALL — a \
7931             call site whose iteration axis holds `&RestartStrategy` by \
7932             construction — must byte-equal `.iter().map(|s| \
7933             s.as_str().to_owned())` on every arm — the borrowed-input \
7934             owned-`String` `From<&RestartStrategy> for String` axis is \
7935             what makes the `String::from` composition route through the \
7936             substrate-primitive `RestartStrategy::as_str` accessor \
7937             without a spurious `Copy` deref (which would only be \
7938             reachable through the owned-input `From<RestartStrategy> for \
7939             String` axis by first calling `.copied()` on the iterator)"
7940        );
7941        for &variant in RestartStrategy::ALL {
7942            let emitted: String = (&variant).into();
7943            let re_parsed: Result<RestartStrategy, ()> =
7944                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
7945            assert_eq!(
7946                re_parsed,
7947                Ok(variant),
7948                "trait-idiomatic borrowed-input owned-`String` \
7949                 forward-projection + reverse-projection axis pair must \
7950                 round-trip &RestartStrategy::{variant:?} through \
7951                 `.into::<String>()` on the borrowed-input surface and \
7952                 back through `TryFrom<&str>` on the owned-`String`'s \
7953                 String::as_str borrow — a break signals the \
7954                 borrowed-input owned-`String` forward-emit and \
7955                 reverse-parse axes have drifted onto different \
7956                 vocabularies"
7957            );
7958        }
7959    }
7960
7961    #[test]
7962    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
7963        // Fail-before-pass-after byte-parity pin on the newly lifted
7964        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
7965        // library trait impl and the substrate-primitive
7966        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
7967        // the same three-arm accept-set across every arm the exhaustive
7968        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
7969        // detour that routes the trait impl through a divergent
7970        // projection (a per-arm inline `match s { "Permanent" =>
7971        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
7972        // link to the un-lifted arm-literal, a hypothetical
7973        // `#[serde(rename_all = "…")]` attribute drift that silently
7974        // splits the wire byte-string from every consumer that reaches
7975        // for this typed dispatch, an accidental swap onto the kebab-case
7976        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
7977        // impl parses through and which would collide the two-axis
7978        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
7979        // doc block makes load-bearing) trips at caixa-core test time
7980        // under `assert_eq!` rather than at a downstream
7981        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
7982        // every one of the three arms [`RestartPolicy::ALL`] carries so
7983        // no arm's projection is covered only by the sibling method-
7984        // named `from_wire` path. Peer of the sibling
7985        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
7986        // (5b828ed) — extends the trait-idiomatic reverse-projection
7987        // axis onto the third and final M2-OTP-shape closed-set typed
7988        // enum on the caixa surface (the paired per-child restart-
7989        // decision-policy sibling on the same M2 `:supervisor` slot).
7990        for &variant in RestartPolicy::ALL {
7991            let wire = variant.as_str();
7992            assert_eq!(
7993                <RestartPolicy as TryFrom<&str>>::try_from(wire),
7994                Ok(variant),
7995                "TryFrom<&str> impl on RestartPolicy must round-trip \
7996                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
7997                 Ok(RestartPolicy::{variant:?}) — divergence from \
7998                 RestartPolicy::from_wire signals a silent detour off \
7999                 the substrate-primitive accessor"
8000            );
8001            assert_eq!(
8002                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
8003                RestartPolicy::from_wire(wire),
8004                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
8005                 equal RestartPolicy::from_wire on the same input"
8006            );
8007        }
8008    }
8009
8010    #[test]
8011    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
8012        // Rejection witness on the `impl TryFrom<&str> for
8013        // RestartPolicy` — sweeps a candidate set of byte-strings
8014        // outside the three-arm PascalCase wire accept-set the sibling
8015        // [`RestartPolicy::as_str`] emits and asserts every one lands on
8016        // `Err(())`, so a future accidental widening of the trait impl's
8017        // accept-set (a stray additional
8018        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
8019        // path, a silent inclusion of the kebab-case dispatcher-catalog
8020        // byte-string the pre-existing [`std::str::FromStr`] impl the
8021        // [`gen_platform::FromStrKind`] derive installs parses onto the
8022        // wire axis — which would collide the two-axis
8023        // wire/dispatcher-catalog split the sibling
8024        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
8025        // an English-rebrand or plural-arm silent alias that would widen
8026        // the wire accept-set past the OTP-canonical three) trips at
8027        // caixa-core test time. The candidate set includes the empty
8028        // string, whitespace-only padding, the kebab-case dispatcher-
8029        // catalog byte-strings on the sibling axis (a caller who
8030        // confuses the two axes trips here rather than at a downstream
8031        // consumer's silent reject), a lowercase / uppercase / mixed-case
8032        // fold of each PascalCase arm (a caller who assumes case-fold
8033        // acceptance trips here), leading/trailing whitespace padding,
8034        // the trailing-newline shape, quote-wrapped candidates, and a
8035        // residual set of plausible-but-wrong English rebrand
8036        // candidates. Peer of the sibling
8037        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
8038        // (5b828ed) rejection witness.
8039        let rejected: &[&str] = &[
8040            "",
8041            " ",
8042            "\n",
8043            "\t",
8044            "permanent",
8045            "temporary",
8046            "transient",
8047            "PERMANENT",
8048            "TEMPORARY",
8049            "TRANSIENT",
8050            "Permanents",
8051            "Permanent ",
8052            " Permanent",
8053            " Temporary ",
8054            "Permanent\n",
8055            "Transient\t",
8056            "\"Permanent\"",
8057            "Ephemeral",
8058            "Always",
8059            "Never",
8060            "OnAbnormalExit",
8061            "intrinsic",
8062            "?",
8063        ];
8064        for &input in rejected {
8065            assert_eq!(
8066                <RestartPolicy as TryFrom<&str>>::try_from(input),
8067                Err(()),
8068                "TryFrom<&str> impl on RestartPolicy must reject the \
8069                 non-wire byte-string {input:?} — silent acceptance \
8070                 signals an accept-set widening off the paired \
8071                 RestartPolicy::from_wire resolver"
8072            );
8073        }
8074    }
8075
8076    #[test]
8077    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
8078        // Cross-axis partition pin: the paired `TryFrom<&str>` and
8079        // `from_wire` reverse projections must resolve identically on
8080        // *every* input, not just the ones [`RestartPolicy::ALL`]
8081        // enumerates. Sweeps a mixed candidate set spanning accepted
8082        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
8083        // case dispatcher-catalog byte-strings, empty, whitespace-
8084        // padded, quoted, English-rebrand candidates) inputs and asserts
8085        // the trait's `Result::ok()` projection byte-equals the method-
8086        // named resolver's `Option<Self>` return-shape on each, locking
8087        // the two paths together by construction so any future detour
8088        // (a stray `try_from` special-case that widens or narrows the
8089        // accept-set outside the paired `from_wire` resolver, an
8090        // accidental swap onto the kebab-case [`std::str::FromStr`]
8091        // impl the [`gen_platform::FromStrKind`] derive installs on the
8092        // sibling dispatcher-catalog axis) trips at caixa-core test
8093        // time. Peer of the sibling
8094        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
8095        // pin — extends the round-trip discipline onto the M2-OTP-shape
8096        // per-child restart-policy axis.
8097        let candidates: &[&str] = &[
8098            "Permanent",
8099            "Temporary",
8100            "Transient",
8101            "",
8102            "permanent",
8103            "temporary",
8104            "transient",
8105            "PERMANENT",
8106            "unknown",
8107            "Permanent ",
8108            " Permanent",
8109            "\"Permanent\"",
8110            "Ephemeral",
8111            "OnAbnormalExit",
8112            "?",
8113        ];
8114        for &input in candidates {
8115            let via_trait: Option<RestartPolicy> =
8116                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
8117            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
8118            assert_eq!(
8119                via_trait, via_method,
8120                "TryFrom<&str> and from_wire must resolve identically on \
8121                 input {input:?} — divergence signals the two reverse-\
8122                 projection paths have drifted onto different accept-sets"
8123            );
8124        }
8125    }
8126
8127    #[test]
8128    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
8129        // Fail-before-pass-after byte-parity pin on the newly lifted
8130        // `impl From<RestartPolicy> for &'static str` — asserts the
8131        // standard-library trait impl and the substrate-primitive
8132        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
8133        // the same three-arm emit-set across every arm the exhaustive
8134        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
8135        // detour that routes the trait impl through a divergent
8136        // projection (a per-arm inline `match policy { Permanent =>
8137        // "Permanent", … }` re-inlining that opens a compile-time link
8138        // to the un-lifted arm-literal, an accidental swap onto the
8139        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
8140        // axis that would collide the two-axis wire/catalog split the
8141        // sibling [`RestartPolicy::from_wire`] doc block makes
8142        // load-bearing) trips at caixa-core test time under
8143        // `assert_eq!` rather than at a downstream
8144        // `impl Into<&'static str>`-bound consumer's silent split.
8145        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
8146        // carries so no arm's projection is covered only by the sibling
8147        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
8148        // paths. Materializes the `<&'static str as
8149        // From<RestartPolicy>>::from` output in a `const`-shape binding
8150        // to make the `'static` lifetime promise a build-time invariant
8151        // — a future accidental downgrade of any of the three arms'
8152        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
8153        // non-`&'static str` (a `String::leak()`-produced return, a
8154        // `Box::leak`-cast) trips at caixa-core build time rather than
8155        // at a downstream `'static`-bound consumer. Peer of the sibling
8156        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
8157        // (523157d) — extends the trait-idiomatic forward-projection
8158        // axis onto the second (and second-of-two-in-M2) closed-set
8159        // typed enum on the caixa surface (the paired per-child
8160        // restart-decision-policy sibling on the same M2 `:supervisor`
8161        // slot).
8162        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
8163        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
8164        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
8165        for &variant in RestartPolicy::ALL {
8166            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8167            let via_method: &'static str = variant.as_str();
8168            assert_eq!(
8169                via_trait, via_method,
8170                "From<RestartPolicy> for &'static str impl must round-trip \
8171                 RestartPolicy::{variant:?} to the same lifted \
8172                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
8173                 divergence signals a silent detour off the substrate-primitive \
8174                 accessor"
8175            );
8176            let via_into: &'static str = variant.into();
8177            assert_eq!(
8178                via_into, via_method,
8179                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
8180                 byte-equal RestartPolicy::as_str on the same input — the \
8181                 blanket-derived Into shape must resolve to the same as_str \
8182                 dispatch as the explicit From impl"
8183            );
8184        }
8185        assert_eq!(
8186            [PERMANENT, TEMPORARY, TRANSIENT],
8187            [
8188                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8189                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8190                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8191            ],
8192            "const-context RestartPolicy::as_str must resolve to the three \
8193             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
8194             downgrade of any arm to a non-const or non-static byte-string \
8195             breaks the `&'static str`-lifetime promise the paired \
8196             From<RestartPolicy> for &'static str impl carries by \
8197             construction"
8198        );
8199    }
8200
8201    #[test]
8202    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
8203        // Cross-axis partition pin: the paired trait-idiomatic
8204        // `From<RestartPolicy> for &'static str` forward projection and
8205        // the method-named [`RestartPolicy::as_str`] forward projection
8206        // must resolve identically on *every* arm, not just the ones
8207        // named in the primary byte-parity pin above. Sweeps every
8208        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
8209        // output byte-equals the method-named accessor's return-value on
8210        // each, locking the two forward-projection paths together by
8211        // construction so any future detour (a stray `From` special-case
8212        // that lands on a divergent per-arm literal outside the paired
8213        // `as_str` dispatch, a hypothetical rebrand touching one axis
8214        // without the other) trips at caixa-core test time. Peer of the
8215        // sibling forward-projection partition pin
8216        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
8217        // (523157d) — extends the round-trip discipline onto the
8218        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
8219        // surface, closing the two-way `Self ↔ &'static str` round-trip
8220        // on the trait-idiomatic pair (`From<Self> for &'static str` +
8221        // `TryFrom<&str> for Self`) as well as the pre-existing method-
8222        // named pair (`as_str` + `from_wire`).
8223        for &variant in RestartPolicy::ALL {
8224            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8225            let via_method: &'static str = variant.as_str();
8226            assert_eq!(
8227                via_trait, via_method,
8228                "From<RestartPolicy> for &'static str and \
8229                 RestartPolicy::as_str must resolve identically on \
8230                 RestartPolicy::{variant:?} — divergence signals the \
8231                 two forward-projection paths have drifted onto different \
8232                 emit-sets"
8233            );
8234        }
8235        // Round-trip witness: every arm's forward `From` output re-parses
8236        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8237        // to the original variant. Closes the two-way `RestartPolicy ↔
8238        // &'static str` round-trip on the trait-idiomatic axis pair,
8239        // mirroring the pre-existing method-named `as_str` + `from_wire`
8240        // round-trip on the substrate-primitive axis pair.
8241        for &variant in RestartPolicy::ALL {
8242            let emitted: &'static str = variant.into();
8243            let re_parsed: Result<RestartPolicy, ()> =
8244                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
8245            assert_eq!(
8246                re_parsed,
8247                Ok(variant),
8248                "trait-idiomatic axis pair must round-trip \
8249                 RestartPolicy::{variant:?} through `.into::<&'static \
8250                 str>()` and back through `TryFrom<&str>` — a break signals \
8251                 the forward-emit and reverse-parse axes have drifted onto \
8252                 different vocabularies"
8253            );
8254        }
8255    }
8256
8257    #[test]
8258    fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
8259        // Fail-before-pass-after byte-parity pin on the newly lifted
8260        // `impl From<&RestartPolicy> for &'static str` — asserts the
8261        // borrowed-input standard-library trait impl and the substrate-
8262        // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
8263        // resolve to the same three-arm emit-set across every arm the
8264        // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
8265        // `From` trait does not auto-derive the borrowed-input sibling
8266        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8267        // where T: Copy, U: From<T>` blanket in `core`), so the
8268        // borrowed-input axis is a distinct trait-idiomatic surface
8269        // that a `.iter().map(Into::into)` shape over
8270        // [`RestartPolicy::ALL`] (whose iterator yields
8271        // `&RestartPolicy`, not `RestartPolicy`) reaches through this
8272        // impl and no other — the paired owned-input
8273        // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
8274        // / dereference before the trait fires. Materializes the
8275        // `<&'static str as From<&RestartPolicy>>::from` output in a
8276        // `const`-shape binding to make the `'static` lifetime promise
8277        // a build-time invariant.
8278        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
8279        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
8280        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
8281        for variant in RestartPolicy::ALL {
8282            let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
8283            let via_method: &'static str = variant.as_str();
8284            assert_eq!(
8285                via_trait, via_method,
8286                "From<&RestartPolicy> for &'static str impl must round-trip \
8287                 &RestartPolicy::{variant:?} to the same lifted \
8288                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
8289                 returns — divergence signals a silent detour off the \
8290                 substrate-primitive accessor"
8291            );
8292            let via_into: &'static str = variant.into();
8293            assert_eq!(
8294                via_into, via_method,
8295                "Into<&'static str>::into on &RestartPolicy::{variant:?} \
8296                 must byte-equal RestartPolicy::as_str on the same input — \
8297                 the blanket-derived Into shape must resolve to the same \
8298                 as_str dispatch as the explicit From impl"
8299            );
8300        }
8301        assert_eq!(
8302            [PERMANENT, TEMPORARY, TRANSIENT],
8303            [
8304                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8305                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8306                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8307            ],
8308            "const-context RestartPolicy::as_str must resolve to the three \
8309             lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
8310             From<&RestartPolicy> for &'static str impl inherits its \
8311             `'static` lifetime promise from the same accessor the \
8312             owned-input sibling routes through"
8313        );
8314    }
8315
8316    #[test]
8317    fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8318        // Cross-axis partition pin: the paired trait-idiomatic
8319        // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
8320        // campaign-shape) and borrowed-input `From<&RestartPolicy> for
8321        // &'static str` (this lift) forward projections must resolve
8322        // identically on every arm, locking the two input-shape paths
8323        // together so any future detour trips at caixa-core test time.
8324        // Then a witness that a `.iter().map(Into::into)` pipe over
8325        // [`RestartPolicy::ALL`] (whose iterator yields
8326        // `&RestartPolicy`) materializes the three-arm accept-set
8327        // through the borrowed-input axis alone — the exact shape a
8328        // future wasm-operator per-child post-exit restart-decision
8329        // diagnostic line, a future substrate-wide per-arm diagnostic
8330        // column, or a
8331        // `HashMap::<&'static str, RestartPolicy>::from_iter(
8332        //     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
8333        // per-policy lookup reaches through — closing the two-way
8334        // owned/borrowed input-shape symmetry on the forward-projection
8335        // trait-idiomatic axis. Peer of the sibling
8336        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8337        // (64aa742) /
8338        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8339        // (5ab993a) /
8340        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8341        // (807b0b5) /
8342        // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8343        // (e941836) partition pins on the sibling closed-set typed-enum
8344        // discriminator axes — extends the borrowed-input axis
8345        // discipline onto the second-of-two M2 OTP-shape closed-set
8346        // typed enum on the caixa surface (per-child restart-decision
8347        // policy). Also closes the direct two-way `&Self → &'static
8348        // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
8349        // — unlike the peer [`crate::CaixaKind`] axis pair (whose
8350        // forward `From` emits lowercase Portuguese diagnostic bytes
8351        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
8352        // forcing the round-trip through an intermediate wire-vocab
8353        // hop), the [`RestartPolicy::as_str`] emit and
8354        // [`RestartPolicy::from_wire`] parse share the same
8355        // `PascalCase` vocabulary by construction, so the borrowed-
8356        // input forward axis and the reverse axis compose directly.
8357        for &variant in RestartPolicy::ALL {
8358            let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8359            let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
8360            assert_eq!(
8361                owned, borrowed,
8362                "From<RestartPolicy> and From<&RestartPolicy> for \
8363                 &'static str must resolve identically on \
8364                 RestartPolicy::{variant:?} — divergence signals the \
8365                 owned-input and borrowed-input forward-projection paths \
8366                 have drifted onto different emit-sets"
8367            );
8368        }
8369        let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
8370        let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
8371        assert_eq!(
8372            via_iter, via_method,
8373            "`.iter().map(Into::into)` over RestartPolicy::ALL must \
8374             byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
8375             borrowed-input `From<&RestartPolicy> for &'static str` axis \
8376             is what makes the `.iter().map(Into::into)` shape route \
8377             through the substrate-primitive `RestartPolicy::as_str` \
8378             accessor rather than through a per-call-site `.copied()` / \
8379             dereference detour"
8380        );
8381        for variant in RestartPolicy::ALL {
8382            let emitted: &'static str = variant.into();
8383            let re_parsed: Result<RestartPolicy, ()> =
8384                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
8385            assert_eq!(
8386                re_parsed,
8387                Ok(*variant),
8388                "trait-idiomatic borrowed-input forward-projection + \
8389                 reverse-projection axis pair must round-trip \
8390                 &RestartPolicy::{variant:?} through `.into::<&'static \
8391                 str>()` (via the borrowed-input axis) and back through \
8392                 `TryFrom<&str>` — a break signals the borrowed-input \
8393                 forward-emit and reverse-parse axes have drifted onto \
8394                 different vocabularies"
8395            );
8396        }
8397    }
8398
8399    #[test]
8400    fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
8401        // Fail-before-pass-after byte-parity pin on the newly lifted
8402        // `impl From<RestartPolicy> for String` — asserts the
8403        // owned-`String`-returning standard-library trait impl and the
8404        // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
8405        // accessor resolve to the same three-arm emit-set across every
8406        // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
8407        // Rust's standard library does not carry a blanket
8408        // `impl<T: AsRef<str>> From<T> for String` (nor an
8409        // `impl<T: fmt::Display> From<T> for String`), so the
8410        // owned-`String` forward-projection axis is a distinct
8411        // trait-idiomatic surface that a `let key: String =
8412        // policy.into();`-shaped call site reaches through this impl
8413        // and no other — the paired sibling `From<RestartPolicy> for
8414        // &'static str` impl forces every owned-`String` call site
8415        // through an explicit `.to_owned()` / `String::from`
8416        // restatement. Peer of the first-mover
8417        // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
8418        // (7baa18a) — extends the trait-idiomatic owned-`String`
8419        // forward-projection axis onto the second-of-two M2 OTP-shape
8420        // closed-set typed enums on the caixa surface (per-child
8421        // restart-decision-policy sibling on the same M2 `:supervisor`
8422        // slot).
8423        for &variant in RestartPolicy::ALL {
8424            let via_trait: String = <String as From<RestartPolicy>>::from(variant);
8425            let via_method: &'static str = variant.as_str();
8426            assert_eq!(
8427                via_trait.as_str(),
8428                via_method,
8429                "From<RestartPolicy> for String impl must round-trip \
8430                 RestartPolicy::{variant:?} to the same lifted \
8431                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
8432                 returns — divergence signals a silent detour off the \
8433                 substrate-primitive accessor"
8434            );
8435            let via_into: String = variant.into();
8436            assert_eq!(
8437                via_into.as_str(),
8438                via_method,
8439                "Into<String>::into on RestartPolicy::{variant:?} must \
8440                 byte-equal RestartPolicy::as_str on the same input — the \
8441                 blanket-derived Into shape must resolve to the same as_str \
8442                 dispatch as the explicit From impl"
8443            );
8444        }
8445    }
8446
8447    #[test]
8448    fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
8449        // Cross-axis partition pin: the paired trait-idiomatic
8450        // owned-`String` `From<RestartPolicy> for String` (this lift)
8451        // and owned-`&'static str` `From<RestartPolicy> for &'static
8452        // str` (9fb37d0) forward projections must resolve identically
8453        // on every arm, locking the two return-type-shape paths
8454        // together so any future detour trips at caixa-core test time.
8455        // Also byte-parity witness against the sibling
8456        // [`ToString::to_string`] surface routed through
8457        // [`std::fmt::Display`] — the three owned-heap-string paths
8458        // (`.into::<String>()`, `String::from`, `.to_string()`) must
8459        // resolve identically on every arm so a future consumer that
8460        // picks any of the three lands on the same lifted
8461        // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
8462        // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
8463        // that materializes the three-arm accept-set through the
8464        // owned-`String` axis alone — the exact shape a future
8465        // wasm-operator per-child post-exit restart-decision
8466        // diagnostic line composer or a
8467        // `HashMap::<String, RestartPolicy>::from_iter(
8468        //     RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
8469        // owned-key per-policy lookup reaches through — closing the
8470        // owned-`String` forward-projection axis's iterator-pipe
8471        // shape. Then a direct round-trip witness through the paired
8472        // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
8473        // owned-`String`'s [`String::as_str`] borrow that closes the
8474        // two-way `Self → String → Self` round-trip on the trait-
8475        // idiomatic owned-`String` forward + reverse axis pair —
8476        // unlike the peer [`crate::CaixaKind`] axis pair (whose
8477        // forward `From` emits lowercase Portuguese diagnostic bytes
8478        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
8479        // forcing the round-trip through an intermediate wire-vocab
8480        // hop), the [`RestartPolicy::as_str`] emit and
8481        // [`RestartPolicy::from_wire`] parse share the same
8482        // `PascalCase` vocabulary by construction, so the owned-
8483        // `String` forward axis and the reverse axis compose directly.
8484        for &variant in RestartPolicy::ALL {
8485            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
8486            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8487            assert_eq!(
8488                owned_string.as_str(),
8489                owned_static,
8490                "From<RestartPolicy> for String and From<RestartPolicy> \
8491                 for &'static str must resolve identically on \
8492                 RestartPolicy::{variant:?} — divergence signals the \
8493                 owned-`String` and owned-`&'static str` forward-projection \
8494                 return-type-shape paths have drifted onto different \
8495                 emit-sets"
8496            );
8497            let via_to_string: String = variant.to_string();
8498            assert_eq!(
8499                owned_string, via_to_string,
8500                "From<RestartPolicy> for String must byte-equal \
8501                 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
8502                 divergence signals the trait-idiomatic owned-`String` \
8503                 forward-projection axis and the ToString-through-Display \
8504                 axis have drifted onto different emit-sets"
8505            );
8506        }
8507        let via_iter: Vec<String> = RestartPolicy::ALL
8508            .iter()
8509            .copied()
8510            .map(String::from)
8511            .collect();
8512        let via_method: Vec<String> = RestartPolicy::ALL
8513            .iter()
8514            .map(|p| p.as_str().to_owned())
8515            .collect();
8516        assert_eq!(
8517            via_iter, via_method,
8518            "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
8519             must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
8520             every arm — the owned-`String` `From<RestartPolicy> for \
8521             String` axis is what makes the `String::from` composition \
8522             route through the substrate-primitive `RestartPolicy::as_str` \
8523             accessor rather than through a per-call-site `.to_owned()` / \
8524             `String::from(policy.as_str())` detour"
8525        );
8526        for &variant in RestartPolicy::ALL {
8527            let emitted: String = variant.into();
8528            let re_parsed: Result<RestartPolicy, ()> =
8529                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
8530            assert_eq!(
8531                re_parsed,
8532                Ok(variant),
8533                "trait-idiomatic owned-`String` forward-projection + \
8534                 reverse-projection axis pair must round-trip \
8535                 RestartPolicy::{variant:?} through `.into::<String>()` \
8536                 and back through `TryFrom<&str>` on the owned-`String`'s \
8537                 String::as_str borrow — a break signals the owned-`String` \
8538                 forward-emit and reverse-parse axes have drifted onto \
8539                 different vocabularies"
8540            );
8541        }
8542    }
8543
8544    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
8545
8546    #[test]
8547    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
8548        // The fail-before-pass-after pin: pre-lift there was no
8549        // single-source binding between the [`RestartPolicy`] variant
8550        // name the un-`rename`d `Serialize` derive emits under
8551        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
8552        // byte-string every downstream cluster-side dispatcher (the
8553        // future wasm-operator's per-child post-exit restart-decision
8554        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8555        // materializer's admission-time enum-arm bind, the
8556        // `caixa-operator`'s hierarchical reconciliation scheduler's
8557        // per-child-policy fan-out) probes verbatim. A future
8558        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
8559        // or a per-variant `#[serde(rename = "…")]` override, or a
8560        // variant rename in the source — would silently rebrand the
8561        // emitted scalar under one spelling while every downstream
8562        // dispatcher still probed the other, with the failure surfacing
8563        // at the operator's reconcile posture (children coming up under
8564        // the `default()` `Permanent` arm rather than the typed slot's
8565        // declared policy — a `:temporary` `oneShot` child would be
8566        // restarted on clean exit, treating the successful-completion
8567        // signal as failure and re-running the completion-terminal
8568        // one-shot indefinitely; a `:transient` child that clean-exited
8569        // would be restarted, masking the clean-completion contract)
8570        // far from the source rebrand commit and with no field naming
8571        // the drift. Pinning the two paths (the `Serialize` derive's
8572        // serialized string AND the [`RestartPolicy::as_str`] helper)
8573        // to the same three lifted
8574        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
8575        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
8576        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
8577        // byte-strings makes any future drift on either endpoint fail
8578        // here at caixa-core build time. Peer of the sibling
8579        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
8580        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
8581        // and the M3
8582        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
8583        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
8584        // same three-path-convergence discipline, extended to close the
8585        // third OTP-shaped closed-enum discriminator axis on the caixa
8586        // typed surface (per-child restart-decision policy).
8587        for (variant, expected) in [
8588            (
8589                RestartPolicy::Permanent,
8590                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8591            ),
8592            (
8593                RestartPolicy::Temporary,
8594                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8595            ),
8596            (
8597                RestartPolicy::Transient,
8598                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8599            ),
8600        ] {
8601            let json = serde_json::to_string(&variant).unwrap();
8602            assert_eq!(
8603                json,
8604                format!("\"{expected}\""),
8605                "RestartPolicy::{variant:?} must serialize to {expected:?}"
8606            );
8607            assert_eq!(
8608                variant.as_str(),
8609                expected,
8610                "RestartPolicy::{variant:?}.as_str() must return the lifted \
8611                 SUPERVISOR_CHILD_RESTART_* constant"
8612            );
8613        }
8614    }
8615
8616    #[test]
8617    fn supervisor_child_restart_consts_are_pairwise_distinct() {
8618        // Cross-arm drift-detection pin: a future collapse of two
8619        // canonical variant byte-strings onto the same value (e.g. an
8620        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
8621        // to also read `"Permanent"`) would silently reroute every
8622        // downstream operator's per-child-policy dispatch onto the
8623        // sibling arm's reconcile branch and pass every propagation-probe
8624        // test that expected only the stale arm's value — a `:transient`
8625        // child would come up under the `:permanent` restart-decision
8626        // posture on every subsequent clean exit, so a completion-terminal
8627        // child would be restarted indefinitely against its declared
8628        // policy. Peer of the sibling
8629        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
8630        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
8631        // and the four-way distinct pin
8632        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
8633        // top-level `SUPERVISOR_KEY_*` axis.
8634        let all = [
8635            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8636            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8637            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8638        ];
8639        for (i, a) in all.iter().enumerate() {
8640            for (j, b) in all.iter().enumerate() {
8641                if i != j {
8642                    assert_ne!(
8643                        a, b,
8644                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
8645                         — got duplicate {a:?} at indices {i} and {j}",
8646                    );
8647                }
8648            }
8649        }
8650    }
8651
8652    #[test]
8653    fn restart_policy_display_routes_through_as_str_helper() {
8654        // The fail-before-pass-after pin on the first half of the
8655        // three-path convergence: pre-convergence [`RestartPolicy`]
8656        // carried a [`std::fmt::Display`] surface via its
8657        // `#[discriminant(also_display)]` gen-platform derive route,
8658        // which arrived kebab-case as `"permanent"` / `"temporary"`
8659        // / `"transient"` on this three-arm enum (whose variant
8660        // names each collapse to their own lowercase form under the
8661        // kebab-case transform) while the wire format ran as
8662        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
8663        // through the un-`rename`d serde derive. Every consumer
8664        // reaching for a policy byte-string past the wire format had
8665        // to pick between three paths ([`RestartPolicy::as_str`],
8666        // the `Serialize` derive's serialized string, or
8667        // `format!("{v}")` on the discriminant-Display route), any
8668        // two of which a future variant rename or
8669        // `#[serde(rename_all = "kebab-case")]` attribute would
8670        // silently desynchronize. Wiring [`std::fmt::Display`]
8671        // through [`RestartPolicy::as_str`] closes the third path:
8672        // every `format!("{v}")` call reaches the same lifted
8673        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
8674        // wire format and the [`RestartPolicy::as_str`] helper
8675        // already route through, so a future variant rename lands at
8676        // exactly one place. Pin the routing here so a future
8677        // `impl std::fmt::Display for RestartPolicy`
8678        // reimplementation that hand-rolls the arms instead of
8679        // delegating to [`RestartPolicy::as_str`] fails at
8680        // caixa-core build time. Peer of the sibling
8681        // [`restart_strategy_display_routes_through_as_str_helper`]
8682        // on the per-supervisor sibling-restart-strategy axis and
8683        // the M3
8684        // `placement_strategy_display_routes_through_as_str_helper`
8685        // (cc8f749) — the third of three OTP-shape closed-enum
8686        // discriminator axes on the caixa typed surface now
8687        // converged onto the same three-path
8688        // (Display → as_str → lifted const) discipline.
8689        for variant in [
8690            RestartPolicy::Permanent,
8691            RestartPolicy::Temporary,
8692            RestartPolicy::Transient,
8693        ] {
8694            assert_eq!(
8695                variant.to_string(),
8696                variant.as_str(),
8697                "RestartPolicy::{variant:?} Display must route through \
8698                 RestartPolicy::as_str (single source of truth: the lifted \
8699                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
8700            );
8701        }
8702    }
8703
8704    #[test]
8705    fn restart_policy_display_matches_serialized_wire_byte_string() {
8706        // The fail-before-pass-after pin on the second half of the
8707        // three-path convergence: `Display` (user-facing text) agrees
8708        // byte-for-byte with the `Serialize` derive's wire format
8709        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
8710        // scalar) on every variant. Pre-convergence the two paths
8711        // were structurally independent — a future
8712        // `#[serde(rename_all = "kebab-case")]` attribute on the
8713        // enum would silently rebrand the emitted wire scalar
8714        // (`permanent`, `temporary`, `transient`) while every
8715        // consumer that pretty-prints the policy (the future
8716        // wasm-operator's per-child post-exit restart-decision
8717        // diagnostic line, the future `feira app graph` per-child
8718        // restart column, the future M4
8719        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
8720        // per-child admission-webhook rejection body) would still
8721        // emit the PascalCase form the `as_str` / `Display` route
8722        // returns, with the mismatch surfacing at consumer parse
8723        // time / operator dispatch time far from the source rebrand
8724        // commit. Pin the two paths byte-for-byte here so any future
8725        // serde-attribute or variant-rename drift is a
8726        // caixa-core-build-time test failure at this call, not a
8727        // silent per-consumer dispatch miss. Peer of the sibling
8728        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
8729        // on the per-supervisor sibling-restart-strategy axis and
8730        // the M3
8731        // `placement_strategy_display_matches_serialized_wire_byte_string`
8732        // (cc8f749).
8733        for variant in [
8734            RestartPolicy::Permanent,
8735            RestartPolicy::Temporary,
8736            RestartPolicy::Transient,
8737        ] {
8738            let wire = serde_json::to_string(&variant).unwrap();
8739            let unquoted = wire
8740                .strip_prefix('"')
8741                .and_then(|s| s.strip_suffix('"'))
8742                .expect("serialized RestartPolicy is a JSON string");
8743            assert_eq!(
8744                variant.to_string(),
8745                unquoted,
8746                "RestartPolicy::{variant:?} Display byte-string must match the \
8747                 Serialize derive's wire byte-string (three-path convergence: \
8748                 Display + as_str + Serialize all resolve to the same \
8749                 SUPERVISOR_CHILD_RESTART_* const)"
8750            );
8751        }
8752    }
8753
8754    #[test]
8755    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
8756        // Fail-before-pass-after byte-parity pin on the lifted
8757        // `impl AsRef<str> for RestartPolicy` — asserts the
8758        // standard-library trait impl and the substrate-primitive
8759        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
8760        // to the same `&str` per instance across the three-arm
8761        // closed set, so any future silent detour that routes the
8762        // impl through a divergent projection (a per-arm inline
8763        // `match self { RestartPolicy::Permanent => "Permanent", … }`
8764        // re-inlining that opens a compile-time link to the un-lifted
8765        // arm-literal, a swap onto the kebab-case
8766        // [`gen_platform::Discriminant`] catalog identity that would
8767        // collide the wire axis with the dispatcher-catalog axis) trips
8768        // at caixa-core test time under `PartialEq` rather than at a
8769        // downstream `impl AsRef<str>`-bound consumer's silent split.
8770        // Sweeps every one of the three arms
8771        // [`RestartPolicy::ALL`] carries so no arm's projection is
8772        // covered only by the sibling wire-format `Serialize` derive
8773        // path. Peer of the sibling
8774        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
8775        // (63eb1a4) on the paired per-supervisor sibling-restart-
8776        // strategy axis and the [`crate::CaixaVersion`]
8777        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
8778        // top-level `:versao` typed newtype — the three pins together
8779        // cover the substrate primitive's `AsRef<str>` projection axis
8780        // on the paired newtype + M2 closed-set-typed-enum surface.
8781        for &variant in RestartPolicy::ALL {
8782            assert_eq!(
8783                <RestartPolicy as AsRef<str>>::as_ref(&variant),
8784                variant.as_str(),
8785                "AsRef<str> impl on RestartPolicy::{variant:?} must \
8786                 byte-equal RestartPolicy::as_str on the same instance \
8787                 — divergence signals a silent detour off the substrate-\
8788                 primitive accessor"
8789            );
8790        }
8791    }
8792
8793    #[test]
8794    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
8795        // Fail-before-pass-after byte-parity pin on the three-path
8796        // convergence discipline the M2 per-child-restart-policy
8797        // primitive now carries on the `&str`-projection axis:
8798        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
8799        // lifted impl), `format!("{v}")` (the pre-existing
8800        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
8801        // primitive `pub const fn` accessor both trait impls delegate
8802        // through) must resolve to the same byte-string on every
8803        // instance across the three-arm closed set. Refuses any future
8804        // divergence between the two trait impls (a stray
8805        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
8806        // rather than delegating through the shared accessor; a
8807        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
8808        // literal cascade) that would silently split the two
8809        // projection paths of the same closed-set typed enum. Mirrors
8810        // the sibling three-path-convergence discipline the peer
8811        // [`RestartStrategy`] typed enum carries on its
8812        // `AsRef<str>` / `Display` / `as_str` triple
8813        // (supervisor.rs pin
8814        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
8815        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
8816        // carries on the same triple (version.rs pin
8817        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
8818        // 16d5c7e).
8819        for &variant in RestartPolicy::ALL {
8820            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
8821            let via_display: String = format!("{variant}");
8822            let via_accessor: &str = variant.as_str();
8823            assert_eq!(via_as_ref, via_accessor);
8824            assert_eq!(via_display, via_accessor);
8825            assert_eq!(via_as_ref, via_display.as_str());
8826        }
8827    }
8828
8829    #[test]
8830    fn restart_policy_all_enumerates_every_variant_exactly_once() {
8831        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
8832        // exhaustive-iteration surface: every variant appears exactly
8833        // once, and the slice length matches the arm count of the
8834        // closed set. Every consumer that walks the accepted-policy
8835        // set (a future `feira supervisor --restart …` CLI-side
8836        // arg-parse's "did you mean" hint, a future M4 admission-
8837        // webhook's per-child rejection body naming the accepted-
8838        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
8839        // projection consumers that iterate the accept-set for
8840        // diagnostic rendering) reads through this slice, so a future
8841        // arm addition that grows the enum but forgets to grow
8842        // [`Self::ALL`] silently truncates every downstream consumer's
8843        // accept-set at the same pre-addition boundary — this pin
8844        // fails at caixa-core build time on the pairwise-distinct +
8845        // arm-count invariants.
8846        //
8847        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
8848        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
8849        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
8850        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
8851        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
8852        // pins on the peer closed-set typed-enum axes.
8853        let all: &[RestartPolicy] = RestartPolicy::ALL;
8854        assert_eq!(
8855            all.len(),
8856            3,
8857            "RestartPolicy::ALL must enumerate every variant of the \
8858             three-arm closed set (Permanent, Temporary, Transient); \
8859             got {all:?}"
8860        );
8861        for (i, a) in all.iter().enumerate() {
8862            for (j, b) in all.iter().enumerate() {
8863                if i != j {
8864                    assert_ne!(
8865                        a, b,
8866                        "RestartPolicy::ALL must carry every variant exactly \
8867                         once — got duplicate {a:?} at indices {i} and {j}"
8868                    );
8869                }
8870            }
8871        }
8872        for variant in [
8873            RestartPolicy::Permanent,
8874            RestartPolicy::Temporary,
8875            RestartPolicy::Transient,
8876        ] {
8877            assert!(
8878                all.contains(&variant),
8879                "RestartPolicy::ALL must contain {variant:?} — a future arm \
8880                 addition that grows the enum but forgets to grow the ALL slice \
8881                 silently truncates every downstream consumer's accept-set at \
8882                 the pre-addition boundary"
8883            );
8884        }
8885    }
8886
8887    #[test]
8888    fn restart_policy_from_wire_accepts_every_lifted_constant() {
8889        // Fail-before-pass-after pin on the forward accept-set of the
8890        // [`RestartPolicy::from_wire`] reverse projection: every
8891        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
8892        // constant the [`RestartPolicy::as_str`] emitter walks parses
8893        // back to its paired variant. Any future arm addition that
8894        // grows the emitter's `as_str` match but forgets to grow the
8895        // parser's `from_wire` match silently splits the two halves of
8896        // the round-trip — the wire byte-string one non-serde consumer
8897        // parses from the one the emitter wrote — with the failure
8898        // surfacing at the operator's reconcile posture (a `:temporary`
8899        // `oneShot` child restarted on clean exit, a `:transient` child
8900        // restarted after clean completion) far from the rebrand
8901        // commit. Pinning the three-arm accept-set here catches the
8902        // drift at caixa-core build time.
8903        //
8904        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
8905        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
8906        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
8907        // accept-set pins on the peer closed-set typed-enum `str → Self`
8908        // axes.
8909        for (wire, expected) in [
8910            (
8911                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8912                RestartPolicy::Permanent,
8913            ),
8914            (
8915                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8916                RestartPolicy::Temporary,
8917            ),
8918            (
8919                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8920                RestartPolicy::Transient,
8921            ),
8922        ] {
8923            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
8924                panic!(
8925                    "RestartPolicy::from_wire({wire:?}) must accept every \
8926                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
8927                     lifted canonical byte-string that RestartPolicy::{expected:?} \
8928                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
8929                )
8930            });
8931            assert_eq!(
8932                parsed, expected,
8933                "RestartPolicy::from_wire({wire:?}) must return \
8934                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
8935            );
8936        }
8937    }
8938
8939    #[test]
8940    fn restart_policy_from_wire_round_trips_through_as_str() {
8941        // Fail-before-pass-after pin on the closed round-trip between
8942        // the forward [`RestartPolicy::as_str`] emitter and the
8943        // reverse [`RestartPolicy::from_wire`] parser: for every
8944        // variant in [`RestartPolicy::ALL`], parsing the emitter's
8945        // output must return exactly the same variant. Any per-arm
8946        // divergence — a future arm added to `as_str` but not
8947        // `from_wire`, an accidental copy-paste flip in one but not
8948        // the other — silently splits the emit and parse halves and
8949        // the failure surfaces at consumer parse time far from the
8950        // drift site. The `ALL`-iterating shape means a future arm
8951        // addition picks up the coverage by construction.
8952        //
8953        // Peer of the sibling
8954        // [`restart_strategy_from_wire_round_trips_through_as_str`]
8955        // (4eec29c) round-trip pin on
8956        // [`RestartStrategy::from_wire`] and the M3
8957        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
8958        // (18c7342) round-trip pin on
8959        // [`crate::aplicacao::PlacementStrategy::from_wire`].
8960        for &variant in RestartPolicy::ALL {
8961            let wire = variant.as_str();
8962            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
8963                panic!(
8964                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
8965                     must be Some({variant:?}) — the two halves of the round-trip \
8966                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
8967                     got None on wire byte-string {wire:?}"
8968                )
8969            });
8970            assert_eq!(
8971                parsed, variant,
8972                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
8973                 must round-trip to the same variant; got {parsed:?}"
8974            );
8975        }
8976    }
8977
8978    #[test]
8979    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
8980        // Fail-before-pass-after pin on the closed-set refusal
8981        // discipline of [`RestartPolicy::from_wire`]: every
8982        // byte-string outside the three-arm accept-set returns `None`
8983        // rather than silently collapsing onto the [`Default`]
8984        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
8985        // exercised here sweeps the load-bearing drift shapes: the
8986        // empty string (a stripped serde-attribute drift), all-
8987        // whitespace strings (the canonical text-editor accidental
8988        // padding shape), the kebab-case dispatcher-catalog identities
8989        // (`"permanent"` / `"temporary"` / `"transient"` — the
8990        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
8991        // accept-set, which parses the *other* axis of this enum's
8992        // two-axis split and must not leak into the `from_wire`
8993        // PascalCase-wire accept-set — a lowercase leak here would
8994        // silently accept the operator's kebab-case
8995        // dispatcher-catalog probe under the wire-axis parser and mis-
8996        // route a `:permanent` intent), the padded canonical scalar
8997        // (`" Permanent "`), the trailing-newline shapes
8998        // (`"Permanent\n"`), the uppercase-single-word forms
8999        // (`"PERMANENT"`), and neighboring-but-unknown arms
9000        // (`"Restart"` — the canonical typo direction toward the
9001        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
9002        //
9003        // Peer of the sibling
9004        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
9005        // (4eec29c) +
9006        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
9007        // (2aa6d23) +
9008        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
9009        // (18c7342) refusal pins on the peer closed-set typed-enum
9010        // axes.
9011        for bad in [
9012            "",
9013            " ",
9014            "\n",
9015            "\t",
9016            "permanent",
9017            "temporary",
9018            "transient",
9019            "PERMANENT",
9020            "TEMPORARY",
9021            "TRANSIENT",
9022            "Permanents",
9023            "Permanent ",
9024            " Permanent",
9025            " Transient ",
9026            "Permanent\n",
9027            "perma",
9028            "Trans",
9029            "OneForOne",
9030            "Restart",
9031            "?",
9032        ] {
9033            assert!(
9034                RestartPolicy::from_wire(bad).is_none(),
9035                "RestartPolicy::from_wire({bad:?}) must return None — the \
9036                 parser's accept-set is exactly the three RestartPolicy::as_str \
9037                 outputs (Permanent, Temporary, Transient), and this \
9038                 byte-string is outside that closed set"
9039            );
9040        }
9041    }
9042
9043    #[test]
9044    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
9045        // Fail-before-pass-after pin on the fourth path of the four-path
9046        // convergence: `from_wire` (the reverse projection) inverts the
9047        // `Serialize` derive's wire byte-string on every variant.
9048        // Together with the pre-existing three-path convergence
9049        // (`Display` + `as_str` + `Serialize` all resolve to the same
9050        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
9051        // pinned by
9052        // [`restart_policy_display_matches_serialized_wire_byte_string`])
9053        // this closes the round-trip: the wire byte-string the
9054        // `Serialize` derive emits parses back to the same variant
9055        // through `from_wire`, so any future serde-attribute or variant-
9056        // rename drift on the emit half now surfaces as a matched drift
9057        // on the parse half at caixa-core build time — the two halves
9058        // migrate as a unit through the lifted consts on any future
9059        // rename, and the round-trip cannot silently split.
9060        //
9061        // Peer of the sibling
9062        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
9063        // (4eec29c) wire-format pin on
9064        // [`RestartStrategy::from_wire`] and the M3
9065        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
9066        // (18c7342) wire-format pin on
9067        // [`crate::aplicacao::PlacementStrategy::from_wire`].
9068        for &variant in RestartPolicy::ALL {
9069            let wire = serde_json::to_string(&variant).unwrap();
9070            let unquoted = wire
9071                .strip_prefix('"')
9072                .and_then(|s| s.strip_suffix('"'))
9073                .expect("serialized RestartPolicy is a JSON string");
9074            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
9075                panic!(
9076                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
9077                     Serialize derive's wire byte-string for \
9078                     RestartPolicy::{variant:?} — the four-path convergence \
9079                     (Display + as_str + Serialize + from_wire) resolves through \
9080                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
9081                )
9082            });
9083            assert_eq!(
9084                parsed, variant,
9085                "RestartPolicy::from_wire of the Serialize derive's wire \
9086                 byte-string for RestartPolicy::{variant:?} must round-trip \
9087                 to the same variant; got {parsed:?}"
9088            );
9089        }
9090    }
9091
9092    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
9093    //
9094    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
9095    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
9096    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
9097    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
9098    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
9099    // the peer per-`:upgrade-from :from` axis. The three pins jointly
9100    // brace the accessor against every future silent detour that would
9101    // desynchronize it from the raw `.caixa` field access every consumer
9102    // previously open-coded.
9103
9104    #[test]
9105    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
9106        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
9107        // [`ChildSpec::nome`] must return the `:children :caixa` field
9108        // byte-for-byte across every DNS-1123-label value the upstream
9109        // [`crate::render::require_valid_dns_1123_label`] gate at
9110        // `SupervisorSpec::validate` admits. Peer of the sibling
9111        // `membro_nome_returns_caixa_byte_equal_across_permutations`
9112        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
9113        // substrate-primitive accessor must byte-equal the raw field
9114        // access verbatim across every author-declared value" discipline
9115        // extended to the M2 supervisor-tree per-`:children` arm. Pins
9116        // against a future silent detour that re-normalized the child
9117        // identity (an accidental `.to_lowercase()` — every `:children
9118        // :caixa` is validated as a DNS-1123 label upstream, so any
9119        // re-normalization is redundant + a drift surface between the
9120        // validator and the accessor), a namespace-prefix rewrite (an
9121        // accidental `format!("{namespace}/{caixa}")` per-CR
9122        // fully-qualified rewrite that didn't land on the peer axes), or
9123        // a per-cluster alias stamp the future wasm-operator's
9124        // hierarchical reconciliation scheduler authors on one consumer
9125        // without the others. Five values sweep the accept-set the
9126        // DNS-1123 gate upstream admits (short single-word / dashed /
9127        // v-suffixed / mixed-digit child names).
9128        for name in [
9129            "worker",
9130            "cache-server",
9131            "scratch-job",
9132            "orders-v2",
9133            "session-8080",
9134        ] {
9135            let c = ChildSpec {
9136                caixa: name.into(),
9137                versao: "^0.1".into(),
9138                restart: RestartPolicy::Permanent,
9139            };
9140            assert_eq!(
9141                c.nome(),
9142                name,
9143                "ChildSpec::nome must return :children :caixa verbatim \
9144                 (got {:?}, expected {name:?})",
9145                c.nome(),
9146            );
9147            assert_eq!(
9148                c.nome(),
9149                c.caixa.as_str(),
9150                "ChildSpec::nome must byte-equal the .caixa field access",
9151            );
9152        }
9153    }
9154
9155    #[test]
9156    fn child_spec_nome_borrows_from_caixa_storage() {
9157        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
9158        // `&str` slice that borrows from the typed slot's own [`String`]
9159        // storage — same-address invariant with `c.caixa.as_str()`. Pins
9160        // against a future silent detour that allocated a fresh `String`
9161        // (`self.caixa.clone()` in the body would type-check but silently
9162        // drop the borrow, and every downstream consumer that assumed
9163        // the returned slice outlives `&self` would break on a stale-
9164        // reference use-after-free — the [`crate::render::insert_first_seen`]
9165        // dedup key at [`SupervisorSpec::validate`], the
9166        // [`validate_no_self_supervision`] equality check against the
9167        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
9168        // borrow — each would silently misbehave if this accessor
9169        // produced a detached copy). Peer of the sibling
9170        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
9171        // M3 per-`:membros` axis and the
9172        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
9173        // first M2 slot scalar accessor.
9174        let c = ChildSpec {
9175            caixa: "worker".into(),
9176            versao: "^0.1".into(),
9177            restart: RestartPolicy::Permanent,
9178        };
9179        let name = c.nome();
9180        let caixa_slice = c.caixa.as_str();
9181        assert_eq!(
9182            name.as_ptr(),
9183            caixa_slice.as_ptr(),
9184            "ChildSpec::nome must borrow from the .caixa String's backing \
9185             storage — a fresh allocation here means the accessor no \
9186             longer names the substrate-primitive typed dispatch and \
9187             every downstream consumer would silently carry a detached \
9188             copy",
9189        );
9190        assert_eq!(
9191            name.len(),
9192            caixa_slice.len(),
9193            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
9194             as well as in address",
9195        );
9196    }
9197
9198    #[test]
9199    fn validate_gates_child_nome_through_lifted_accessor() {
9200        // Bilateral coherence pin: every `:children :caixa` that
9201        // [`SupervisorSpec::validate`] accepts is one
9202        // [`crate::render::require_valid_dns_1123_label`] accepts on the
9203        // accessor-projected value, and vice versa on the reject side.
9204        // This closes the "the validator reads through the accessor"
9205        // contract structurally — a future silent detour that made the
9206        // accessor return a different byte-string than the validator
9207        // gates against would surface here as a coverage mismatch, not
9208        // as an apply-time DNS-1123 rejection at
9209        // `metadata.name: Invalid value` far from the caixa.lisp source.
9210        // Peer of the M2 sibling
9211        // `validate_parses_prior_versao_through_lifted_accessor`
9212        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
9213        // `validate_membros` peer discipline.
9214        //
9215        // Accept-set sweep: five DNS-1123-label values the upstream gate
9216        // admits.
9217        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
9218            let s = SupervisorSpec {
9219                children: vec![ChildSpec {
9220                    caixa: ok_name.into(),
9221                    versao: "^0.1".into(),
9222                    restart: RestartPolicy::Permanent,
9223                }],
9224                ..SupervisorSpec::default()
9225            };
9226            s.validate().unwrap_or_else(|e| {
9227                panic!(
9228                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
9229                     (upstream DNS-1123 gate accepts it): got {e:?}",
9230                );
9231            });
9232            let c = ChildSpec {
9233                caixa: ok_name.into(),
9234                versao: "^0.1".into(),
9235                restart: RestartPolicy::Permanent,
9236            };
9237            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
9238                .unwrap_or_else(|()| {
9239                    panic!(
9240                        "require_valid_dns_1123_label must accept the accessor-projected \
9241                     :children :caixa {ok_name:?}",
9242                    );
9243                });
9244        }
9245        // Reject-set sweep: five DNS-1123-label-violating shapes the
9246        // upstream gate refuses (empty / uppercase / underscore / dot /
9247        // leading-hyphen). Every rejection at the validator must
9248        // correspond to a rejection when the accessor's projected value
9249        // is fed back through the shared gate.
9250        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
9251            let s = SupervisorSpec {
9252                children: vec![ChildSpec {
9253                    caixa: bad_name.into(),
9254                    versao: "^0.1".into(),
9255                    restart: RestartPolicy::Permanent,
9256                }],
9257                ..SupervisorSpec::default()
9258            };
9259            let err = s.validate().unwrap_err();
9260            assert!(
9261                matches!(
9262                    err,
9263                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
9264                ),
9265                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
9266                 via the DNS-1123 gate: got {err:?}",
9267            );
9268            let c = ChildSpec {
9269                caixa: bad_name.into(),
9270                versao: "^0.1".into(),
9271                restart: RestartPolicy::Permanent,
9272            };
9273            assert!(
9274                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
9275                    .is_err(),
9276                "require_valid_dns_1123_label must reject the accessor-projected \
9277                 :children :caixa {bad_name:?}",
9278            );
9279        }
9280    }
9281
9282    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
9283    //
9284    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
9285    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
9286    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
9287    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
9288    // trio on the peer per-`:children` `String`-carry axis. The three pins
9289    // jointly brace the accessor against every future silent detour that
9290    // would desynchronize it from the raw `.versao` field access the
9291    // requirement gate + error carrier previously open-coded.
9292    //
9293    // Closes the last unlifted per-`:children` `String`-carry axis: the
9294    // pair (`nome`, `versao_requirement`) now jointly projects the
9295    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
9296    // consumer that fans on per-child identity + version pin reads,
9297    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
9298    // pair discipline verbatim.
9299    #[test]
9300    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
9301        // The canonical per-`:children` child-`:versao`-scalar pin:
9302        // [`ChildSpec::versao_requirement`] must return the `:children
9303        // :versao` field byte-for-byte across every Cargo-shaped semver
9304        // requirement value the upstream
9305        // [`crate::render::require_valid_versao_requirement`] gate admits.
9306        // Peer of the sibling
9307        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
9308        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
9309        // substrate-primitive accessor must byte-equal the raw field
9310        // access verbatim across every author-declared value" discipline
9311        // extended to the M2 supervisor-tree per-`:children` arm. Pins
9312        // against a future silent detour that re-canonicalized the
9313        // requirement (an accidental `.to_string()` via
9314        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
9315        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
9316        // silently drifted the error carrier's quoted requirement away
9317        // from the source `caixa.lisp`, an accidental whitespace trim on
9318        // `"^ 0.1"` that no consumer ever produced from the field-access
9319        // side, an accidental per-cluster lacre-projected concrete-version
9320        // rewrite that didn't land on the peer requirement-gate call).
9321        // Five values sweep the accept-set the shared
9322        // [`crate::render::require_valid_versao_requirement`] gate admits
9323        // (caret / tilde / exact / wildcard / bare-major).
9324        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
9325            let c = ChildSpec {
9326                caixa: "worker".into(),
9327                versao: req.into(),
9328                restart: RestartPolicy::Permanent,
9329            };
9330            assert_eq!(
9331                c.versao_requirement(),
9332                req,
9333                "ChildSpec::versao_requirement must return :children :versao \
9334                 verbatim (got {:?}, expected {req:?})",
9335                c.versao_requirement(),
9336            );
9337            assert_eq!(
9338                c.versao_requirement(),
9339                c.versao.as_str(),
9340                "ChildSpec::versao_requirement must byte-equal the .versao \
9341                 field access",
9342            );
9343        }
9344    }
9345
9346    #[test]
9347    fn child_spec_versao_requirement_borrows_from_versao_storage() {
9348        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
9349        // return a `&str` slice that borrows from the typed slot's own
9350        // [`String`] storage — same-address invariant with
9351        // `c.versao.as_str()`. Pins against a future silent detour that
9352        // allocated a fresh `String` (`self.versao.clone()` in the body
9353        // would type-check but silently drop the borrow, and every
9354        // downstream consumer that assumed the returned slice outlives
9355        // `&self` — the [`crate::render::require_valid_versao_requirement`]
9356        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
9357        // `.to_string()` carrier's byte-length assumption — would silently
9358        // misbehave if this accessor produced a detached copy). Peer of
9359        // the sibling `child_spec_nome_borrows_from_caixa_storage`
9360        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
9361        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
9362        // pin on the peer per-`:membros` `:versao` axis.
9363        let c = ChildSpec {
9364            caixa: "worker".into(),
9365            versao: "^0.1".into(),
9366            restart: RestartPolicy::Permanent,
9367        };
9368        let req = c.versao_requirement();
9369        let versao_slice = c.versao.as_str();
9370        assert_eq!(
9371            req.as_ptr(),
9372            versao_slice.as_ptr(),
9373            "ChildSpec::versao_requirement must borrow from the .versao \
9374             String's backing storage — a fresh allocation here means the \
9375             accessor no longer names the substrate-primitive typed \
9376             dispatch and every downstream consumer would silently carry \
9377             a detached copy",
9378        );
9379        assert_eq!(
9380            req.len(),
9381            versao_slice.len(),
9382            "ChildSpec::versao_requirement and .versao.as_str() must \
9383             byte-equal in length as well as in address",
9384        );
9385    }
9386
9387    #[test]
9388    fn validate_gates_child_versao_through_lifted_accessor() {
9389        // Bilateral coherence pin: every `:children :versao` that
9390        // [`SupervisorSpec::validate`] accepts is one
9391        // [`crate::render::require_valid_versao_requirement`] accepts on
9392        // the accessor-projected value, and vice versa on the reject side.
9393        // This closes the "the validator reads through the accessor"
9394        // contract structurally — a future silent detour that made the
9395        // accessor return a different byte-string than the validator gates
9396        // against would surface here as a coverage mismatch, not as a
9397        // resolver-time semver-parse rejection at lacre-closure time far
9398        // from the caixa.lisp source. Peer of the sibling
9399        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
9400        // the per-`:children :caixa` axis and the M2
9401        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
9402        // on the peer per-`:upgrade-from :from` axis.
9403        //
9404        // Accept-set sweep: five Cargo-shaped semver requirement values
9405        // the upstream gate admits (caret / tilde / exact / wildcard /
9406        // bare-major).
9407        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
9408            let s = SupervisorSpec {
9409                children: vec![ChildSpec {
9410                    caixa: "worker".into(),
9411                    versao: ok_req.into(),
9412                    restart: RestartPolicy::Permanent,
9413                }],
9414                ..SupervisorSpec::default()
9415            };
9416            s.validate().unwrap_or_else(|e| {
9417                panic!(
9418                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
9419                     (upstream versao-requirement gate accepts it): got {e:?}",
9420                );
9421            });
9422            let c = ChildSpec {
9423                caixa: "worker".into(),
9424                versao: ok_req.into(),
9425                restart: RestartPolicy::Permanent,
9426            };
9427            crate::render::require_valid_versao_requirement(
9428                c.versao_requirement(),
9429                || (),
9430                |_reason| (),
9431            )
9432            .unwrap_or_else(|()| {
9433                panic!(
9434                    "require_valid_versao_requirement must accept the accessor-projected \
9435                     :children :versao {ok_req:?}",
9436                );
9437            });
9438        }
9439        // Reject-set sweep: five requirement-violating shapes the upstream
9440        // gate refuses. The empty string closes the empty-first arm of the
9441        // shared [`crate::render::require_valid_versao_requirement`]
9442        // cascade; the four non-empty arms exercise distinct semver-parse
9443        // failure modes the M3 peer per-`:membros` reject-set already pins
9444        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
9445        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
9446        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
9447        // shared parser routing means the same reject-set must fail
9448        // identically at the M2 supervisor-tree per-`:children` accessor
9449        // arm here. Every rejection at the validator must correspond to a
9450        // rejection when the accessor's projected value is fed back
9451        // through the shared gate.
9452        //
9453        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
9454        // `"not-a-semver"` are intentionally *not* in the reject-set: the
9455        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
9456        // and the identifier-tail arm's grammar admits some non-canonical
9457        // shapes — matching what the M3 peer test suite already documents
9458        // as the shared parser's accept-set edges.)
9459        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
9460            let s = SupervisorSpec {
9461                children: vec![ChildSpec {
9462                    caixa: "worker".into(),
9463                    versao: bad_req.into(),
9464                    restart: RestartPolicy::Permanent,
9465                }],
9466                ..SupervisorSpec::default()
9467            };
9468            let err = s.validate().unwrap_err();
9469            assert!(
9470                matches!(
9471                    err,
9472                    SupervisorError::EmptyChildVersion { .. }
9473                        | SupervisorError::ChildVersaoInvalid { .. }
9474                ),
9475                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
9476                 via the versao-requirement gate: got {err:?}",
9477            );
9478            let c = ChildSpec {
9479                caixa: "worker".into(),
9480                versao: bad_req.into(),
9481                restart: RestartPolicy::Permanent,
9482            };
9483            assert!(
9484                crate::render::require_valid_versao_requirement(
9485                    c.versao_requirement(),
9486                    || (),
9487                    |_reason| (),
9488                )
9489                .is_err(),
9490                "require_valid_versao_requirement must reject the accessor-projected \
9491                 :children :versao {bad_req:?}",
9492            );
9493        }
9494    }
9495
9496    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
9497    //
9498    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
9499    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
9500    // already project the `String`-carry `(caixa, versao)` fields; the
9501    // `Copy`-composite-enum `restart` field is the third and final axis).
9502    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
9503    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
9504    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
9505    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
9506    // strategy scalar accessor — same "one typed dispatch on the substrate
9507    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
9508    // extended onto the M2 supervisor-slot per-`:children` restart-decision
9509    // axis. The pin below covers the accessor's byte-equal projection
9510    // against the raw field access across every variant in the closed
9511    // accept-set (`Permanent`, `Transient`, `Temporary`).
9512
9513    #[test]
9514    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
9515        // The canonical per-`:children` restart-decision-policy-scalar
9516        // pin: [`ChildSpec::restart`] must return the `:children :restart`
9517        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
9518        // typed slot's own [`RestartPolicy`] storage across every variant
9519        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
9520        // Pins against a future silent detour that re-derived the policy
9521        // from a peer axis (an accidental fallback to
9522        // `if is_supervisor_child { Permanent } else { Temporary }` that
9523        // collapsed the child's kind axis into the restart discriminator),
9524        // a variant remap the operator authors on one consumer without the
9525        // other, or a stale-derive detour that substituted
9526        // [`RestartPolicy::default`] when the field held any explicit
9527        // variant (which would silently collapse the distinction between
9528        // "author explicitly declared `:restart Permanent`" and "author
9529        // omitted the slot and inherited the default" the future
9530        // per-cluster restart-decision override slot depends on).
9531        //
9532        // Peer of the sibling per-`:supervisor`
9533        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
9534        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
9535        // axis and the M3
9536        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
9537        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
9538        // — same "the substrate-primitive accessor must byte-equal the raw
9539        // field access verbatim across every author-declared value"
9540        // discipline extended onto the M2 supervisor-slot per-`:children`
9541        // restart-decision-policy axis, closing the last unlifted axis on
9542        // the per-`:children` [`ChildSpec`] type.
9543        for restart in [
9544            RestartPolicy::Permanent,
9545            RestartPolicy::Transient,
9546            RestartPolicy::Temporary,
9547        ] {
9548            let c = ChildSpec {
9549                caixa: "worker".into(),
9550                versao: "^0.1".into(),
9551                restart,
9552            };
9553            assert_eq!(
9554                c.restart(),
9555                restart,
9556                "ChildSpec::restart must return :children :restart \
9557                 verbatim (got {:?}, expected {restart:?})",
9558                c.restart(),
9559            );
9560            assert_eq!(
9561                c.restart(),
9562                c.restart,
9563                "ChildSpec::restart accessor and .restart field access \
9564                 must byte-equal — the accessor is the substrate-primitive \
9565                 typed dispatch every downstream per-child restart-\
9566                 decision consumer must route through",
9567            );
9568        }
9569    }
9570
9571    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
9572    //
9573    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
9574    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
9575    // distribution-strategy accessor discipline onto the M2 supervisor-slot
9576    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
9577    // scalar axis. The two pins below cover (1) the accessor's byte-equal
9578    // projection against the raw field access across every variant in the
9579    // closed accept-set, and (2) the two-consumer coherence between the
9580    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
9581    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
9582    // carrier's `estrategia:` field — peer of the sibling M3
9583    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
9584    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
9585    // pair on the per-`:placement` distribution-strategy axis.
9586
9587    #[test]
9588    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
9589        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
9590        // pin: [`SupervisorSpec::estrategia`] must return the
9591        // `:supervisor :estrategia` field verbatim as a
9592        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
9593        // [`RestartStrategy`] storage across every variant in the closed
9594        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
9595        // `SimpleOneForOne`). Pins against a future silent detour that
9596        // re-derived the strategy from a peer axis (an accidental
9597        // fallback to `if children.is_empty() { SimpleOneForOne } else {
9598        // OneForOne }` collapse that read the children-count axis into
9599        // the strategy discriminator), a variant remap the operator
9600        // authors on one consumer without the other, or a stale-derive
9601        // detour that substituted [`RestartStrategy::default`] when the
9602        // field held any explicit variant (which would silently collapse
9603        // the distinction between "author explicitly declared
9604        // `:estrategia OneForOne`" and "author omitted the slot and
9605        // inherited the default" the future per-cluster strategy override
9606        // slot depends on). Peer of the sibling M3
9607        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
9608        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
9609        // axis — same "the substrate-primitive accessor must byte-equal
9610        // the raw field access verbatim across every author-declared
9611        // value" discipline extended onto the M2 supervisor-slot
9612        // per-`:supervisor` sibling-restart-strategy axis.
9613        for &estrategia in RestartStrategy::ALL {
9614            // `SimpleOneForOne` requires `children.is_empty()`; the peer
9615            // three strategies require a non-empty static children list.
9616            // Build each shape coherently so the pin's fixture would
9617            // itself pass [`SupervisorSpec::validate`] once fed through
9618            // the sibling coherence pin below — the byte-equal projection
9619            // asserted here is a strictly weaker property (a `Copy` field
9620            // read) that does not depend on `validate` running, but
9621            // keeping the fixture validate-clean means a future extension
9622            // of the pin to exercise `validate` end-to-end does not have
9623            // to re-author the children shape.
9624            //
9625            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
9626            // shape partition through the [`gen_platform::IsVariant`]
9627            // derive-generated
9628            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
9629            // than the raw `matches!(estrategia, RestartStrategy::
9630            // SimpleOneForOne)` open-coded pattern-match — same closed-
9631            // set-typed-enum arm-discriminator dispatch discipline the
9632            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
9633            // convergence (915a934) extended onto its two paired positive
9634            // / negated `matches!` sites and the peer
9635            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
9636            // predicate convergence (766ec63) extended onto the M3 mesh-
9637            // slot per-`:placement` distribution-strategy discriminator
9638            // axis. See the sibling `round_trip_all_strategies` and the
9639            // peer `manifest::tests::
9640            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
9641            // fixture for the two peer sites the same lift closes on.
9642            let children = if estrategia.is_simple_one_for_one() {
9643                Vec::new()
9644            } else {
9645                vec![ChildSpec {
9646                    caixa: "worker".into(),
9647                    versao: "^0.1".into(),
9648                    restart: RestartPolicy::Permanent,
9649                }]
9650            };
9651            let s = SupervisorSpec {
9652                estrategia,
9653                children,
9654                ..SupervisorSpec::default()
9655            };
9656            assert_eq!(
9657                s.estrategia(),
9658                estrategia,
9659                "SupervisorSpec::estrategia must return :supervisor :estrategia \
9660                 verbatim (got {:?}, expected {estrategia:?})",
9661                s.estrategia(),
9662            );
9663            assert_eq!(
9664                s.estrategia(),
9665                s.estrategia,
9666                "SupervisorSpec::estrategia accessor and .estrategia field \
9667                 access must byte-equal — the accessor is the substrate-\
9668                 primitive typed dispatch every downstream sibling-restart-\
9669                 strategy consumer must route through",
9670            );
9671        }
9672    }
9673
9674    #[test]
9675    fn validate_reads_through_lifted_estrategia_accessor() {
9676        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
9677        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
9678        // dispatch (which reads through [`SupervisorSpec::estrategia`]
9679        // to fan across the strategy-arm shape-gate cascades) and the
9680        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
9681        // error carrier's `estrategia:` field (which reads through
9682        // [`SupervisorSpec::estrategia`] to name the strategy the empty
9683        // `:children` list was declared against) must both key off the
9684        // lifted accessor, so any future rebrand on the typed slot's
9685        // reader shape lands at exactly one place. Pins the two-site
9686        // coherence by exercising the `NoChildren` error surface end-to-
9687        // end across every non-`SimpleOneForOne` variant and asserting
9688        // the surfaced `estrategia:` field byte-equals the accessor's
9689        // return. Peer of the sibling M3
9690        // `validate_placement_reads_through_lifted_estrategia_accessor`
9691        // (921fe1b) three-consumer coherence pin on the per-`:placement`
9692        // distribution-strategy axis.
9693        for estrategia in [
9694            RestartStrategy::OneForOne,
9695            RestartStrategy::OneForAll,
9696            RestartStrategy::RestForOne,
9697        ] {
9698            let s = SupervisorSpec {
9699                estrategia,
9700                children: Vec::new(),
9701                ..SupervisorSpec::default()
9702            };
9703            let err = s.validate().unwrap_err();
9704            match err {
9705                SupervisorError::NoChildren { estrategia: e } => {
9706                    assert_eq!(
9707                        e,
9708                        s.estrategia(),
9709                        "NoChildren.estrategia must byte-equal \
9710                         SupervisorSpec::estrategia() — the empty-`:children` \
9711                         refusal reads through the lifted accessor",
9712                    );
9713                    assert_eq!(
9714                        e, estrategia,
9715                        "NoChildren.estrategia must carry the author-declared \
9716                         :supervisor :estrategia variant verbatim (got {e:?}, \
9717                         expected {estrategia:?})",
9718                    );
9719                }
9720                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
9721            }
9722        }
9723    }
9724
9725    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
9726    //
9727    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
9728    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
9729    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
9730    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
9731    // The two pins below cover (1) the accessor's byte-equal projection
9732    // against the raw field access across every representative value in
9733    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
9734    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
9735    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
9736    // zero-floor / cap composition — the validate gate and the accessor
9737    // must route through the same substrate-primitive typed dispatch, so
9738    // any future silent detour that had the accessor perform a
9739    // bounds-collapsing clamp would fail here at caixa-core build time.
9740    // Peer of the sibling M3
9741    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
9742    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
9743
9744    #[test]
9745    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
9746        // The canonical per-`:supervisor` restart-budget-count scalar pin:
9747        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
9748        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
9749        // typed slot's own `u32` storage, byte-equal to the raw field
9750        // access across every representative value in the accept-set —
9751        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
9752        // accept-set the surrounding [`SupervisorSpec::validate`] gate
9753        // carves out on the sibling `ZeroMaxRestarts` refusal),
9754        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
9755        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
9756        // (a past-the-guard sentinel that pins the accessor doesn't
9757        // perform a silent bounds-collapse into `1` on the zero arm —
9758        // validate rejects zero but the accessor must ship the raw slot
9759        // verbatim so a validate-time gate regression surfaces at the
9760        // emit boundary rather than being silently absorbed), `u32::MAX`
9761        // (a past-the-guard sentinel that pins the accessor doesn't
9762        // perform a silent bounds-collapse through
9763        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
9764        //
9765        // Peer of the sibling M3
9766        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
9767        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
9768        // required-scalar axis — same "the substrate-primitive accessor
9769        // must byte-equal the raw field access verbatim across every
9770        // value in the `u32` accept-set" discipline extended onto the M2
9771        // supervisor-slot per-`:supervisor` restart-budget-count axis.
9772        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
9773            let s = SupervisorSpec {
9774                max_restarts,
9775                ..SupervisorSpec::default()
9776            };
9777            assert_eq!(
9778                s.max_restarts(),
9779                max_restarts,
9780                "SupervisorSpec::max_restarts must return :supervisor \
9781                 :max-restarts verbatim (got {}, expected {max_restarts})",
9782                s.max_restarts(),
9783            );
9784            assert_eq!(
9785                s.max_restarts(),
9786                s.max_restarts,
9787                "SupervisorSpec::max_restarts accessor and .max_restarts \
9788                 field access must byte-equal — the accessor is the \
9789                 substrate-primitive typed dispatch every downstream \
9790                 restart-budget-count consumer must route through",
9791            );
9792        }
9793    }
9794
9795    #[test]
9796    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
9797        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
9798        // zero-floor + upper-cap bracket must key off
9799        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
9800        // field access. Structurally: a `SupervisorSpec { max_restarts:
9801        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
9802        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
9803        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
9804        // (with the offending count carried verbatim from the accessor
9805        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
9806        // lower boundary of the accept-set) plus a `SupervisorSpec {
9807        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
9808        // boundary) must pass validate. The four together jointly pin the
9809        // accessor + validate-gate composition: any future silent detour
9810        // that had the accessor return a fresh `1` on the zero arm (a
9811        // `.max_restarts().max(1)` collapse) would silently absorb the
9812        // `ZeroMaxRestarts` refusal at the accessor boundary and the
9813        // validate gate would accept a struct-literal `SupervisorSpec {
9814        // max_restarts: 0, .. }` — the composition pin catches that at
9815        // caixa-core build time.
9816        //
9817        // Peer of the sibling M3
9818        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
9819        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
9820        // composition axis — same "the validate / shape-gate predicate
9821        // must route through the substrate-primitive typed dispatch"
9822        // discipline extended onto the peer M2 supervisor-slot
9823        // required-`u32` composition axis.
9824        let child = ChildSpec {
9825            caixa: "worker".into(),
9826            versao: "^0.1".into(),
9827            restart: RestartPolicy::Permanent,
9828        };
9829        // Zero-floor arm.
9830        let s = SupervisorSpec {
9831            max_restarts: 0,
9832            children: vec![child.clone()],
9833            ..SupervisorSpec::default()
9834        };
9835        assert_eq!(
9836            s.validate().unwrap_err(),
9837            SupervisorError::ZeroMaxRestarts,
9838            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
9839             — the accessor and the validate gate must route through the \
9840             same substrate-primitive typed dispatch on the zero-floor arm",
9841        );
9842        // Cap arm — the surfaced `max_restarts:` field must byte-equal
9843        // the accessor's return so a future rebrand on the accessor
9844        // lands in the diagnostic without a coordinated rewrite.
9845        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
9846        let s = SupervisorSpec {
9847            max_restarts: over_cap,
9848            children: vec![child.clone()],
9849            ..SupervisorSpec::default()
9850        };
9851        match s.validate().unwrap_err() {
9852            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
9853                assert_eq!(
9854                    max_restarts,
9855                    s.max_restarts(),
9856                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
9857                     SupervisorSpec::max_restarts() — the cap-arm refusal \
9858                     reads through the lifted accessor",
9859                );
9860                assert_eq!(
9861                    max_restarts, over_cap,
9862                    "MaxRestartsExceedsCap.max_restarts must carry the \
9863                     author-declared :supervisor :max-restarts value \
9864                     verbatim (got {max_restarts}, expected {over_cap})",
9865                );
9866            }
9867            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
9868        }
9869        // Lower + upper accept-set boundaries.
9870        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
9871            let s = SupervisorSpec {
9872                max_restarts,
9873                children: vec![child.clone()],
9874                ..SupervisorSpec::default()
9875            };
9876            assert!(
9877                s.validate().is_ok(),
9878                "validate must accept max_restarts == {max_restarts} \
9879                 (an accept-set boundary of \
9880                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
9881            );
9882        }
9883    }
9884
9885    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
9886    //
9887    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
9888    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
9889    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
9890    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
9891    // supervisor-slot per-`:supervisor` restart-intensity-denominator
9892    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
9893    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
9894    // per-`:supervisor` scalar-value axis. The three pins below cover
9895    // (1) the accessor's byte-equal projection against the raw field
9896    // access across every representative value in the `Option<Duration>`
9897    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
9898    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
9899    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
9900    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
9901    // `if let Some(w) = self.restart_window() { … }` bracket-arm
9902    // composition — the validate gate and the accessor must route through
9903    // the same substrate-primitive typed dispatch, so any future silent
9904    // detour that had the accessor perform a bounds-collapsing clamp
9905    // would fail here at caixa-core build time, and (3) the accessor's
9906    // by-copy idempotence pin — the returned `Option<Duration>` must
9907    // outlive `&self` and two successive calls must return byte-equal
9908    // values. Peer of the sibling M2
9909    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
9910    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
9911    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
9912    // (7073d0f) pin on the per-`:politicas :timeout` axis.
9913
9914    #[test]
9915    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
9916        // The canonical per-`:supervisor` restart-intensity-denominator
9917        // scalar pin: [`SupervisorSpec::restart_window`] must return the
9918        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
9919        // `Option<Duration>`, `Copy`-projected from the typed slot's own
9920        // `Option<Duration>` storage, byte-equal to the raw field access
9921        // across every representative value in the accept-set — `None`
9922        // (the "never reset — every restart across the supervisor's
9923        // lifetime counts against the sibling `:max-restarts` budget"
9924        // sentinel the field's own docstring names and the peer
9925        // `validate_accepts_none_restart_window` pin locks in on the
9926        // [`SupervisorSpec::validate`] entry-side),
9927        // `Some(Duration::from_millis(1))` (the structural minimum a
9928        // validated `:restart-window` may carry, the integer-millisecond
9929        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
9930        // everything sub-ms; `Duration::ZERO` is separately rejected by
9931        // [`SupervisorError::RestartWindowZero`]),
9932        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
9933        // surrounding [`SupervisorSpec::validate`] gate carves out on the
9934        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
9935        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
9936        // accessor doesn't perform a silent bounds-collapse into `None` on
9937        // the zero-Duration arm — validate rejects zero but the accessor
9938        // must ship the raw slot verbatim so a validate-time gate
9939        // regression surfaces at the emit boundary rather than being
9940        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
9941        // sentinel that pins the accessor doesn't perform a silent
9942        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
9943        // return path).
9944        //
9945        // Peer of the sibling M2
9946        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
9947        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
9948        // sibling M3
9949        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
9950        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
9951        // substrate-primitive accessor must byte-equal the raw field
9952        // access verbatim across every value in the `Option<Duration>`
9953        // accept-set" discipline extended onto the M2 supervisor-slot
9954        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
9955        // silent detour that re-derived the restart-window from a peer
9956        // axis (an accidental `.max_restarts.into()` collapse that read
9957        // the restart-budget-count as a duration — the two axes serve
9958        // different halves of the `MaxIntensity / Period` restart-
9959        // intensity ratio, and confusing them silently inverts the
9960        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
9961        // "zero means never reset" collapse (the canonical
9962        // `Option<Duration>` → `Duration` collapse footgun the
9963        // [`SupervisorError::RestartWindowZero`] validate arm guards on
9964        // the peer zero-floor axis; a zero period either trips on the
9965        // first failure or never trips depending on operator
9966        // interpretation, neither of which is the author's "never reset"
9967        // intent that `None` expresses structurally), or a per-arm
9968        // variant swap that landed on one consumer without the other.
9969        for restart_window in [
9970            None,
9971            Some(Duration::from_millis(1)),
9972            Some(SUPERVISOR_RESTART_WINDOW_MAX),
9973            Some(Duration::ZERO),
9974            Some(Duration::MAX),
9975        ] {
9976            let s = SupervisorSpec {
9977                restart_window,
9978                ..SupervisorSpec::default()
9979            };
9980            assert_eq!(
9981                s.restart_window(),
9982                restart_window,
9983                "SupervisorSpec::restart_window must return :supervisor \
9984                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
9985                s.restart_window(),
9986            );
9987            assert_eq!(
9988                s.restart_window(),
9989                s.restart_window,
9990                "SupervisorSpec::restart_window accessor and \
9991                 .restart_window field access must byte-equal — the \
9992                 accessor is the substrate-primitive typed dispatch every \
9993                 downstream restart-intensity-denominator consumer must \
9994                 route through",
9995            );
9996        }
9997    }
9998
9999    #[test]
10000    fn validate_restart_window_bracket_arm_routes_through_accessor() {
10001        // Composition pin: [`SupervisorSpec::validate`]'s
10002        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
10003        // zero-floor + integer-millisecond canonical-form + upper-cap
10004        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
10005        // the raw `.restart_window` field access. Structurally: a
10006        // `SupervisorSpec { restart_window: None, .. }` must pass the
10007        // arm gate structurally (the `if let Some(_)` shape returns
10008        // early on the `None` arm — the accessor and the validate gate
10009        // must agree on `None → skip the bracket cascade` so an authored
10010        // `:restart-window ()` structurally routes through the "never
10011        // reset" sentinel path), a `SupervisorSpec { restart_window:
10012        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
10013        // refusal exactly, a `SupervisorSpec { restart_window:
10014        // Some(Duration::from_micros(1500)), .. }` must surface the
10015        // `RestartWindowNotCanonical` refusal exactly (with the offending
10016        // duration carried verbatim from the accessor return), a
10017        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
10018        // + Duration::from_millis(1)), .. }` must surface the
10019        // `RestartWindowExceedsCap` refusal exactly (with the offending
10020        // duration carried verbatim from the accessor return), and a
10021        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
10022        // .. }` (the lower boundary of the accept-set) plus a
10023        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
10024        // .. }` (the upper boundary) must pass validate. The six together
10025        // jointly pin the accessor + validate-gate composition: any future
10026        // silent detour that had the accessor return a fresh `None` on any
10027        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
10028        // collapse) would silently absorb the `RestartWindowZero` refusal
10029        // at the accessor boundary and the validate gate would accept a
10030        // struct-literal `SupervisorSpec { restart_window:
10031        // Some(Duration::ZERO), .. }` — the composition pin catches that
10032        // at caixa-core build time.
10033        //
10034        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
10035        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
10036        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
10037        // accessor-composition pin on the per-`:politicas :timeout` axis —
10038        // same "the validate / shape-gate predicate must route through
10039        // the substrate-primitive typed dispatch" discipline extended
10040        // onto the peer M2 supervisor-slot optional-`Duration` axis.
10041        let child = ChildSpec {
10042            caixa: "worker".into(),
10043            versao: "^0.1".into(),
10044            restart: RestartPolicy::Permanent,
10045        };
10046        // None arm — must not surface any :restart-window-shaped refusal;
10047        // the `if let Some(_)` bracket returns early on `None` structurally.
10048        let s = SupervisorSpec {
10049            restart_window: None,
10050            children: vec![child.clone()],
10051            ..SupervisorSpec::default()
10052        };
10053        assert!(
10054            s.validate().is_ok(),
10055            "validate must accept restart_window: None (the never-reset \
10056             sentinel) — the `if let Some(_)` bracket returns early on \
10057             the None arm and the accessor must agree",
10058        );
10059        // Zero-floor arm.
10060        let s = SupervisorSpec {
10061            restart_window: Some(Duration::ZERO),
10062            children: vec![child.clone()],
10063            ..SupervisorSpec::default()
10064        };
10065        assert_eq!(
10066            s.validate().unwrap_err(),
10067            SupervisorError::RestartWindowZero,
10068            "validate must reject restart_window == Some(Duration::ZERO) \
10069             with RestartWindowZero — the accessor and the validate gate \
10070             must route through the same substrate-primitive typed \
10071             dispatch on the zero-floor arm",
10072        );
10073        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
10074        // byte-equal the accessor's return so a future rebrand on the
10075        // accessor lands in the diagnostic without a coordinated rewrite.
10076        let sub_ms = Duration::from_micros(1500);
10077        let s = SupervisorSpec {
10078            restart_window: Some(sub_ms),
10079            children: vec![child.clone()],
10080            ..SupervisorSpec::default()
10081        };
10082        match s.validate().unwrap_err() {
10083            SupervisorError::RestartWindowNotCanonical { window } => {
10084                assert_eq!(
10085                    Some(window),
10086                    s.restart_window(),
10087                    "RestartWindowNotCanonical.window must byte-equal \
10088                     SupervisorSpec::restart_window().unwrap() — the \
10089                     non-canonical-arm refusal reads through the lifted \
10090                     accessor",
10091                );
10092                assert_eq!(
10093                    window, sub_ms,
10094                    "RestartWindowNotCanonical.window must carry the \
10095                     author-declared :supervisor :restart-window value \
10096                     verbatim (got {window:?}, expected {sub_ms:?})",
10097                );
10098            }
10099            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
10100        }
10101        // Cap arm — the surfaced `window:` field must byte-equal the
10102        // accessor's return.
10103        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
10104        let s = SupervisorSpec {
10105            restart_window: Some(over_cap),
10106            children: vec![child.clone()],
10107            ..SupervisorSpec::default()
10108        };
10109        match s.validate().unwrap_err() {
10110            SupervisorError::RestartWindowExceedsCap { window } => {
10111                assert_eq!(
10112                    Some(window),
10113                    s.restart_window(),
10114                    "RestartWindowExceedsCap.window must byte-equal \
10115                     SupervisorSpec::restart_window().unwrap() — the \
10116                     cap-arm refusal reads through the lifted accessor",
10117                );
10118                assert_eq!(
10119                    window, over_cap,
10120                    "RestartWindowExceedsCap.window must carry the \
10121                     author-declared :supervisor :restart-window value \
10122                     verbatim (got {window:?}, expected {over_cap:?})",
10123                );
10124            }
10125            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
10126        }
10127        // Lower + upper accept-set boundaries.
10128        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
10129            let s = SupervisorSpec {
10130                restart_window: Some(restart_window),
10131                children: vec![child.clone()],
10132                ..SupervisorSpec::default()
10133            };
10134            assert!(
10135                s.validate().is_ok(),
10136                "validate must accept restart_window == Some({restart_window:?}) \
10137                 (an accept-set boundary of \
10138                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
10139            );
10140        }
10141    }
10142
10143    #[test]
10144    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
10145        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
10146        // `Option<Duration>` by copy — `Duration` is `Copy` (so
10147        // `Option<Duration>` is `Copy`) and the accessor must return by
10148        // value, not by reference. Peer of the sibling M2
10149        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
10150        // per-`:limits :wall-clock` axis and the sibling M3
10151        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
10152        // per-`:politicas :timeout` axis, extended onto the peer M2
10153        // supervisor-slot `Option<Duration>` copy-invariant shape — the
10154        // accessor's returned `Option<Duration>` must outlive `&self`
10155        // (multiple calls must return equal values from a dropped-`&self`
10156        // copy, since the returned Option carries no borrow), and calling
10157        // the accessor twice on the same SupervisorSpec must yield the
10158        // same `Option<Duration>` verbatim (idempotent, no side effects
10159        // on `&self`).
10160        //
10161        // Pins against a future silent detour that returned
10162        // `Option<&Duration>` (which would type-check but silently break
10163        // every downstream caller — the future wasm-operator's
10164        // per-supervisor restart-intensity counter consumes `Duration` by
10165        // value and `&Duration` would fold to a detached copy at the call
10166        // site), an accidental `Option::as_ref()` projection
10167        // (`self.restart_window.as_ref()` would also type-check but
10168        // return `Option<&Duration>`), or a one-arm-only accessor that
10169        // reads `Some(*w)` in the Some arm but reads a fresh
10170        // `Default::default()` (which would collapse to `Duration::ZERO`,
10171        // not `None`) in the None arm — a footgun the
10172        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
10173        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
10174        // requires `Period > 0` and `None` structurally expresses "never
10175        // reset" instead.
10176        for restart_window in [
10177            None,
10178            Some(Duration::from_millis(1)),
10179            Some(Duration::from_secs(60)),
10180            Some(SUPERVISOR_RESTART_WINDOW_MAX),
10181        ] {
10182            let s = SupervisorSpec {
10183                restart_window,
10184                ..SupervisorSpec::default()
10185            };
10186            let first = s.restart_window();
10187            let second = s.restart_window();
10188            assert_eq!(
10189                first, second,
10190                "SupervisorSpec::restart_window must be idempotent — two \
10191                 successive calls on the same &self must return the \
10192                 same Option<Duration>",
10193            );
10194            assert_eq!(
10195                first, restart_window,
10196                "SupervisorSpec::restart_window must return :supervisor \
10197                 :restart-window verbatim by copy — got {first:?}, \
10198                 expected {restart_window:?}",
10199            );
10200        }
10201    }
10202
10203    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
10204    //
10205    // The [`SupervisorSpec::children`] accessor lift is the seed of the
10206    // slice-return (`&[T]`) accessor discipline on the substrate — the four
10207    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
10208    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
10209    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
10210    // access at the time of this seed, and inherit this pin family's
10211    // discipline as future compounding runs migrate their consumers. The
10212    // three pins below cover (1) the accessor's byte-equal projection
10213    // against the raw field access across the empty / singleton / cohort
10214    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
10215    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
10216    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
10217    // consumer routing through the accessor on both arms, and (3) the
10218    // per-child validate loop's traversal reading the same slice-view the
10219    // accessor projects. Peer of the sibling M2
10220    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
10221    // two-consumer coherence pin on the per-`:supervisor`
10222    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
10223    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
10224
10225    #[test]
10226    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
10227        // The canonical per-`:supervisor` static-child-list scalar-shape
10228        // pin: [`SupervisorSpec::children`] must return the `:supervisor
10229        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
10230        // slice-view over the same backing buffer the raw
10231        // `self.children.as_slice()` field access borrows from, byte-
10232        // equal across every representative fixture in the accept-set —
10233        // the empty slice (the `SimpleOneForOne`-arm sentinel),
10234        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
10235        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
10236        // with the peer three restart-policy variants in play).
10237        //
10238        // Pins against a future silent detour that returned
10239        // `&Vec<ChildSpec>` (which would type-check but leak the
10240        // storage-side `Vec`'s grow/push/reserve surface no consumer of
10241        // the typed view reaches for), a fresh-allocated
10242        // `Vec<ChildSpec>` copy (which would type-check via a coercion
10243        // but silently break every downstream caller that relied on the
10244        // slice sharing the backing buffer's identity), or an
10245        // out-of-order or length-drifted projection (which would silently
10246        // split the per-child validate loop's traversal input from the
10247        // paired partition-dispatch `.is_empty()` probe's input).
10248        //
10249        // Peer of the sibling
10250        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
10251        // (eafb619) `Copy`-composite-enum byte-equal pin on the
10252        // per-`:supervisor` sibling-restart-strategy axis, extended onto
10253        // the per-`:supervisor` static-child-list `Vec`-carry axis.
10254        let fixtures: Vec<Vec<ChildSpec>> = vec![
10255            Vec::new(),
10256            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
10257            vec![
10258                child("worker", "^0.1", RestartPolicy::Permanent),
10259                child("cache-server", "^0.1", RestartPolicy::Transient),
10260            ],
10261            vec![
10262                child("worker", "^0.1", RestartPolicy::Permanent),
10263                child("cache-server", "^0.1", RestartPolicy::Transient),
10264                child("scratch-job", "^0.1", RestartPolicy::Temporary),
10265            ],
10266        ];
10267        for children in fixtures {
10268            let s = SupervisorSpec {
10269                children: children.clone(),
10270                ..SupervisorSpec::default()
10271            };
10272            assert_eq!(
10273                s.children(),
10274                children.as_slice(),
10275                "SupervisorSpec::children must return :supervisor \
10276                 :children verbatim (got {:?}, expected {:?})",
10277                s.children(),
10278                children.as_slice(),
10279            );
10280            assert_eq!(
10281                s.children(),
10282                s.children.as_slice(),
10283                "SupervisorSpec::children accessor and \
10284                 .children.as_slice() field access must byte-equal — \
10285                 the accessor is the substrate-primitive typed \
10286                 dispatch every downstream static-child-list consumer \
10287                 must route through",
10288            );
10289            assert_eq!(
10290                s.children().len(),
10291                s.children.len(),
10292                "SupervisorSpec::children().len() must byte-equal \
10293                 self.children.len() — a length-drift would silently \
10294                 split the paired partition-dispatch `.is_empty()` \
10295                 probe input from the per-child validate loop's \
10296                 traversal input",
10297            );
10298        }
10299    }
10300
10301    #[test]
10302    fn validate_reads_through_lifted_children_accessor() {
10303        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
10304        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
10305        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
10306        // when the accessor projects a non-empty slice under a
10307        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
10308        // `self.children().is_empty()` refusal probe (which must trip
10309        // [`SupervisorError::NoChildren`] when the accessor projects the
10310        // empty slice under any peer estrategia), and the per-child
10311        // validate loop's `for child in self.children()` traversal
10312        // (which must reach every entry in the same order the accessor
10313        // projects) must all key off the lifted accessor, so any future
10314        // rebrand on the typed slot's reader shape lands at exactly one
10315        // place. Pins the three-site coherence by exercising each
10316        // production consumer end-to-end: (1) the
10317        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
10318        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
10319        // refusal under the empty slice + non-`SimpleOneForOne`
10320        // estrategia across every peer variant, and (3) the per-child
10321        // duplicate-detection surface fires on the second entry of a
10322        // two-child cohort that shares a `:caixa` name (which requires
10323        // the loop to reach both entries — a first-entry-only projection
10324        // would silently pass since the dedup HashSet has room for the
10325        // first insert).
10326        //
10327        // Peer of the sibling M2
10328        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
10329        // two-consumer coherence pin on the per-`:supervisor`
10330        // sibling-restart-strategy axis, extended onto the
10331        // per-`:supervisor` static-child-list `Vec`-carry axis.
10332
10333        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
10334        // `SimpleOneForOne` estrategia must trip
10335        // `SimpleOneForOneWithStaticChildren`.
10336        let s = SupervisorSpec {
10337            estrategia: RestartStrategy::SimpleOneForOne,
10338            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
10339            ..SupervisorSpec::default()
10340        };
10341        assert_eq!(
10342            s.validate().unwrap_err(),
10343            SupervisorError::SimpleOneForOneWithStaticChildren,
10344            "SimpleOneForOne + non-empty children must trip \
10345             SimpleOneForOneWithStaticChildren — the accessor projects \
10346             a non-empty slice, and the SimpleOneForOne-arm refusal \
10347             probe reads through the lifted accessor",
10348        );
10349        assert!(
10350            !s.children().is_empty(),
10351            "the SimpleOneForOne-arm refusal input must be a non-empty \
10352             slice per the accessor's projection",
10353        );
10354
10355        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
10356        // under any peer estrategia must trip `NoChildren`.
10357        for estrategia in [
10358            RestartStrategy::OneForOne,
10359            RestartStrategy::OneForAll,
10360            RestartStrategy::RestForOne,
10361        ] {
10362            let s = SupervisorSpec {
10363                estrategia,
10364                children: Vec::new(),
10365                ..SupervisorSpec::default()
10366            };
10367            match s.validate().unwrap_err() {
10368                SupervisorError::NoChildren { estrategia: e } => {
10369                    assert_eq!(
10370                        e, estrategia,
10371                        "NoChildren.estrategia must carry the author-\
10372                         declared :supervisor :estrategia variant \
10373                         verbatim (got {e:?}, expected {estrategia:?})",
10374                    );
10375                }
10376                other => panic!(
10377                    "expected NoChildren, got {other:?} for \
10378                     estrategia={estrategia:?}"
10379                ),
10380            }
10381            assert!(
10382                s.children().is_empty(),
10383                "the non-SimpleOneForOne-arm refusal input must be the \
10384                 empty slice per the accessor's projection",
10385            );
10386        }
10387
10388        // (3) Per-child validate loop: a two-child cohort that shares a
10389        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
10390        // reach both entries through the accessor.
10391        let s = SupervisorSpec {
10392            estrategia: RestartStrategy::OneForOne,
10393            children: vec![
10394                child("worker", "^0.1", RestartPolicy::Permanent),
10395                child("worker", "^0.2", RestartPolicy::Transient),
10396            ],
10397            ..SupervisorSpec::default()
10398        };
10399        match s.validate().unwrap_err() {
10400            SupervisorError::DuplicateChildCaixa { caixa } => {
10401                assert_eq!(
10402                    caixa, "worker",
10403                    "DuplicateChildCaixa.caixa must carry the shared \
10404                     child `:caixa` name verbatim",
10405                );
10406            }
10407            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
10408        }
10409        assert_eq!(
10410            s.children().len(),
10411            2,
10412            "the per-child validate loop's traversal input must be a \
10413             two-element slice per the accessor's projection",
10414        );
10415    }
10416
10417    // Shared helper for the M2 per-`:children` per-slot-gate ≡
10418    // `validate` equivalence pins: builds an `OneForOne`-estrategia
10419    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
10420    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
10421    // bracket all pass cleanly so the sole failing surface is the
10422    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
10423    // pins the two-altitude equivalence on the paired probe.
10424    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
10425        let s = SupervisorSpec {
10426            estrategia: RestartStrategy::OneForOne,
10427            children,
10428            ..SupervisorSpec::default()
10429        };
10430        let via_gate = s.validate_children().unwrap_err();
10431        let via_validate = s.validate().unwrap_err();
10432        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
10433        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
10434        assert_eq!(
10435            via_gate, via_validate,
10436            "per-slot gate ≡ validate() must discriminate the same \
10437             refusal shape",
10438        );
10439    }
10440
10441    #[test]
10442    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
10443        // Fail-before-pass-after equivalence pin on the M2
10444        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
10445        // convergence — sibling of the M3 mesh-slot
10446        // `validate_membros_*` / `validate_contratos_*` /
10447        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
10448        // peer per-entry axes. Sweeps four of the five refusal shapes
10449        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
10450        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
10451        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
10452        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
10453        // duplicate-`:caixa` fan-out. Companion pin
10454        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
10455        // covers `ChildVersaoInvalid` (whose parser-owned reason string
10456        // needs pattern-matching, not equality) and the clean-pass
10457        // canonical fixture; together the two pins guarantee the
10458        // per-slot gate and `validate` discriminate the same set on
10459        // every per-child-covered input.
10460        assert_validate_children_matches_gate(
10461            vec![child("", "^0.1", RestartPolicy::Permanent)],
10462            &SupervisorError::EmptyChildName,
10463        );
10464        assert_validate_children_matches_gate(
10465            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
10466            &SupervisorError::ChildCaixaInvalid {
10467                caixa: "Worker".into(),
10468                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
10469            },
10470        );
10471        assert_validate_children_matches_gate(
10472            vec![child("worker", "", RestartPolicy::Permanent)],
10473            &SupervisorError::EmptyChildVersion {
10474                caixa: "worker".into(),
10475            },
10476        );
10477        assert_validate_children_matches_gate(
10478            vec![
10479                child("worker", "^0.1", RestartPolicy::Permanent),
10480                child("worker", "^0.2", RestartPolicy::Transient),
10481            ],
10482            &SupervisorError::DuplicateChildCaixa {
10483                caixa: "worker".into(),
10484            },
10485        );
10486    }
10487
10488    #[test]
10489    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
10490        // Second half of the two-altitude equivalence pin — covers the
10491        // one refusal shape whose reason string is parser-owned
10492        // (`ChildVersaoInvalid`, whose reason comes from the shared
10493        // [`crate::version::parse_requirement`] impl and may drift) and
10494        // the clean-pass canonical fixture. Sibling pin
10495        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
10496        // covers the four equality-comparable refusal shapes.
10497        let s_bad_versao = SupervisorSpec {
10498            estrategia: RestartStrategy::OneForOne,
10499            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
10500            ..SupervisorSpec::default()
10501        };
10502        let via_gate = s_bad_versao.validate_children().unwrap_err();
10503        let via_validate = s_bad_versao.validate().unwrap_err();
10504        match (&via_gate, &via_validate) {
10505            (
10506                SupervisorError::ChildVersaoInvalid {
10507                    caixa: cg,
10508                    versao: vg,
10509                    ..
10510                },
10511                SupervisorError::ChildVersaoInvalid {
10512                    caixa: cv,
10513                    versao: vv,
10514                    ..
10515                },
10516            ) => {
10517                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
10518                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
10519                assert_eq!(cv, "worker", "validate() :caixa carrier");
10520                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
10521            }
10522            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
10523        }
10524        assert_eq!(
10525            via_gate, via_validate,
10526            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
10527        );
10528
10529        let s_ok = SupervisorSpec {
10530            estrategia: RestartStrategy::OneForOne,
10531            children: vec![
10532                child("worker-a", "^0.1", RestartPolicy::Permanent),
10533                child("worker-b", "~0.2.3", RestartPolicy::Transient),
10534                child("collector", "*", RestartPolicy::Temporary),
10535            ],
10536            ..SupervisorSpec::default()
10537        };
10538        s_ok.validate_children()
10539            .expect("per-slot gate must accept the clean-pass fixture");
10540        s_ok.validate()
10541            .expect("validate() must accept the clean-pass fixture");
10542    }
10543
10544    #[test]
10545    fn validate_children_is_self_contained_on_children_slot() {
10546        // Self-containment pin: [`SupervisorSpec::validate_children`]
10547        // resolves the per-child cascade against `&self` alone, without
10548        // depending on the peer `:estrategia`/`:max-restarts`/
10549        // `:restart-window` gates having run first — same posture the M3
10550        // peer per-slot gates carry (`validate_membros`,
10551        // `validate_contratos`, `validate_entrada`, `validate_placement`,
10552        // routing through their own oracles rather than borrowing state
10553        // threaded down from `validate`). A future consumer that reaches
10554        // the per-slot gate directly on a spec whose peer slots would
10555        // fail `validate` still surfaces the per-child refusal, not the
10556        // peer refusal.
10557        //
10558        // Construct a spec whose `:max-restarts` is `0` (which would
10559        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
10560        // the partition-dispatch) and whose `:children` carries a
10561        // `DuplicateChildCaixa` shape: the per-slot gate called directly
10562        // must surface `DuplicateChildCaixa`, proving it does not depend
10563        // on the peer `:max-restarts` gate running first.
10564        let s = SupervisorSpec {
10565            estrategia: RestartStrategy::OneForOne,
10566            max_restarts: 0,
10567            restart_window: Some(Duration::from_secs(60)),
10568            children: vec![
10569                child("worker", "^0.1", RestartPolicy::Permanent),
10570                child("worker", "^0.2", RestartPolicy::Transient),
10571            ],
10572        };
10573        assert_eq!(
10574            s.validate_children().unwrap_err(),
10575            SupervisorError::DuplicateChildCaixa {
10576                caixa: "worker".into(),
10577            },
10578            "per-slot gate must resolve per-child refusal directly against \
10579             `&self` — a dependency on the peer `:max-restarts` gate \
10580             running first would surface ZeroMaxRestarts here instead",
10581        );
10582        // The peer gate is still the surface `validate` reaches — pin
10583        // the ordering to establish that `validate_children` truly runs
10584        // last in `validate`'s dispatch, so a direct call bypasses the
10585        // peer gates on any spec whose per-child cascade would fail.
10586        assert_eq!(
10587            s.validate().unwrap_err(),
10588            SupervisorError::ZeroMaxRestarts,
10589            "validate() must surface the peer `:max-restarts` gate before \
10590             reaching the per-child cascade — this pins the dispatch \
10591             ordering the per-slot gate's self-containment complements",
10592        );
10593    }
10594
10595    #[test]
10596    fn child_spec_restart_accessor_is_const_fn() {
10597        // The [`ChildSpec::restart`] per-`:children` restart-decision-
10598        // policy `Copy`-return scalar accessor is declared
10599        // `#[must_use] pub const fn` — matching the sibling M2
10600        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
10601        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
10602        // both converted in this commit), the sibling M2
10603        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
10604        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
10605        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
10606        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
10607        // `Copy`-return `pub const fn` scalar accessors on the sibling
10608        // M3 surface. Pin the `const`-eval posture here so a future
10609        // accidental downgrade to non-`const` (an added runtime helper
10610        // reachable only from a non-`const` context, an
10611        // `Option<RestartPolicy>`-shape migration on the per-child
10612        // restart-decision axis once heterogeneous per-cluster
10613        // restart-policy overlays land that would silently drop the
10614        // `const` qualifier, a manual hand-rolled shadow) trips at
10615        // caixa-core build time rather than surfacing as a downstream
10616        // `const`-context regression far from the declaration.
10617        //
10618        // Same shape as the sibling M3
10619        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
10620        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
10621        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
10622        // accessor axis — the load-bearing witness lives in the
10623        // module-scope `const fn` wrapper `restart_via_const_fn` below:
10624        // a body that calls [`ChildSpec::restart`] under a `const fn`
10625        // signature is well-formed only when the callee is itself
10626        // `const fn`, so any future accidental downgrade of
10627        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
10628        // build time (const-eval E0015 `cannot call non-const method`),
10629        // strictly stronger than a runtime `assert!(CONST)` and
10630        // side-stepping the destructor-in-const restriction that
10631        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
10632        // items on `ChildSpec`'s `String` carriers.
10633        //
10634        // The runtime body sweeps every closed-set [`RestartPolicy`]
10635        // arm and asserts the wrapped and direct dispatches agree.
10636        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
10637            c.restart()
10638        }
10639        for restart in [
10640            RestartPolicy::Permanent,
10641            RestartPolicy::Transient,
10642            RestartPolicy::Temporary,
10643        ] {
10644            let c = ChildSpec {
10645                caixa: "worker".into(),
10646                versao: "^0.1".into(),
10647                restart,
10648            };
10649            assert_eq!(
10650                restart_via_const_fn(&c),
10651                c.restart(),
10652                "const-fn-wrapped and direct dispatch on \
10653                 ChildSpec::restart must agree for {restart:?}",
10654            );
10655            assert_eq!(
10656                c.restart(),
10657                restart,
10658                "ChildSpec::restart must return the storage-side \
10659                 RestartPolicy verbatim for {restart:?} (a violation \
10660                 means the accessor stopped being a raw field-return \
10661                 copy)",
10662            );
10663        }
10664    }
10665
10666    #[test]
10667    fn supervisor_spec_estrategia_accessor_is_const_fn() {
10668        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
10669        // sibling-restart-strategy `Copy`-return scalar accessor is
10670        // declared `#[must_use] pub const fn` — matching the sibling M2
10671        // per-`:children` [`ChildSpec::restart`] (pinned by
10672        // [`child_spec_restart_accessor_is_const_fn`] above, both
10673        // converted in this commit), the sibling M2 per-`:supervisor`
10674        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
10675        // accessor already `pub const fn`, and mirroring the peer M3
10676        // mesh-slot per-`:placement`
10677        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
10678        // `pub const fn` scalar accessor whose method-name discipline
10679        // the [`SupervisorSpec::estrategia`] method was authored to
10680        // match. Pin the `const`-eval posture here so a future
10681        // accidental downgrade to non-`const` (an added runtime helper
10682        // reachable only from a non-`const` context, an
10683        // `Option<RestartStrategy>`-shape migration once the substrate
10684        // grows per-cluster strategy overlays that would silently drop
10685        // the `const` qualifier, a manual hand-rolled shadow) trips at
10686        // caixa-core build time rather than surfacing as a downstream
10687        // `const`-context regression far from the declaration.
10688        //
10689        // Same shape as the sibling
10690        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
10691        // load-bearing witness lives in the module-scope `const fn`
10692        // wrapper `estrategia_via_const_fn` below: a body that calls
10693        // [`SupervisorSpec::estrategia`] under a `const fn` signature
10694        // is well-formed only when the callee is itself `const fn`,
10695        // side-stepping the destructor-in-const restriction that would
10696        // otherwise block a direct
10697        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
10698        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
10699        // carriers.
10700        //
10701        // The runtime body sweeps every closed-set [`RestartStrategy`]
10702        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
10703        // direct dispatches agree.
10704        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
10705            s.estrategia()
10706        }
10707        for &estrategia in RestartStrategy::ALL {
10708            let s = SupervisorSpec {
10709                estrategia,
10710                max_restarts: 5,
10711                restart_window: Some(Duration::from_secs(60)),
10712                children: Vec::new(),
10713            };
10714            assert_eq!(
10715                estrategia_via_const_fn(&s),
10716                s.estrategia(),
10717                "const-fn-wrapped and direct dispatch on \
10718                 SupervisorSpec::estrategia must agree for {estrategia:?}",
10719            );
10720            assert_eq!(
10721                s.estrategia(),
10722                estrategia,
10723                "SupervisorSpec::estrategia must return the storage-side \
10724                 RestartStrategy verbatim for {estrategia:?} (a violation \
10725                 means the accessor stopped being a raw field-return \
10726                 copy)",
10727            );
10728        }
10729    }
10730
10731    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
10732    // macro definition (see the paired doc-block above the macro
10733    // definition) — every generated `<ctor>(caixa: &str) -> Self`
10734    // constructor folds the uniform `Self::<Variant> { caixa:
10735    // caixa.to_string() }` one-field struct-literal onto one substrate
10736    // primitive. The three per-variant equivalence pins below
10737    // (fail-before-pass-after by construction — a byte-mismatched macro
10738    // arm would trip its equivalence pin first) lock each generated
10739    // constructor to its struct-literal peer under `PartialEq`, so
10740    // every wire-up in [`SupervisorSpec::validate_children`] and
10741    // [`validate_no_self_supervision`] on that variant produces a
10742    // byte-equal `SupervisorError` to the pre-lift open-coded
10743    // struct-literal. The cross-axis pin that follows (non-default
10744    // caixa name) routes the sole constructor input axis through
10745    // `.to_string()`, so the fold does not silently collapse onto a
10746    // fixed name.
10747    //
10748    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
10749    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
10750    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
10751    // `missing_entry_ctor_matches_struct_literal_wrap` /
10752    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
10753    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
10754    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
10755    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
10756    // on the six sibling ctor families the recent trajectory closed
10757    // on the peer `LayoutError` / `AplicacaoError` envelopes.
10758
10759    #[test]
10760    fn empty_child_version_ctor_matches_struct_literal_wrap() {
10761        assert_eq!(
10762            SupervisorError::empty_child_version("worker"),
10763            SupervisorError::EmptyChildVersion {
10764                caixa: "worker".to_string(),
10765            },
10766            "generated empty_child_version ctor must produce byte-equal \
10767             SupervisorError to the open-coded struct-literal wrap on the \
10768             same &str fixture",
10769        );
10770    }
10771
10772    #[test]
10773    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
10774        assert_eq!(
10775            SupervisorError::duplicate_child_caixa("worker"),
10776            SupervisorError::DuplicateChildCaixa {
10777                caixa: "worker".to_string(),
10778            },
10779            "generated duplicate_child_caixa ctor must produce byte-equal \
10780             SupervisorError to the open-coded struct-literal wrap on the \
10781             same &str fixture",
10782        );
10783    }
10784
10785    #[test]
10786    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
10787        assert_eq!(
10788            SupervisorError::child_supervises_self("orquestra"),
10789            SupervisorError::ChildSupervisesSelf {
10790                caixa: "orquestra".to_string(),
10791            },
10792            "generated child_supervises_self ctor must produce byte-equal \
10793             SupervisorError to the open-coded struct-literal wrap on the \
10794             same &str fixture",
10795        );
10796    }
10797
10798    // Per-variant equivalence pins for the two lifted
10799    // [`SupervisorError::child_caixa_invalid`] /
10800    // [`SupervisorError::child_versao_invalid`] inherent constructors
10801    // (fail-before-pass-after by construction — a byte-mismatched ctor body
10802    // would trip its equivalence pin first). Each pins the ctor output to
10803    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
10804    // in [`SupervisorSpec::validate_children`] on the two variants
10805    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
10806    // struct-literal on the same scalar fixtures. Peers of the sibling
10807    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
10808    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
10809    // the peer `AplicacaoError` envelope's
10810    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
10811
10812    #[test]
10813    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
10814        let caixa = "Worker";
10815        let reason = "sample reason text";
10816        assert_eq!(
10817            SupervisorError::child_caixa_invalid(caixa, reason),
10818            SupervisorError::ChildCaixaInvalid {
10819                caixa: caixa.to_string(),
10820                reason: reason.to_string(),
10821            },
10822            "lifted child_caixa_invalid ctor must produce byte-equal \
10823             SupervisorError to the open-coded struct-literal wrap on the \
10824             same (&str, reason) fixture",
10825        );
10826    }
10827
10828    #[test]
10829    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
10830        let caixa = "worker";
10831        let versao = "not-a-req";
10832        let reason = "sample reason text";
10833        assert_eq!(
10834            SupervisorError::child_versao_invalid(caixa, versao, reason),
10835            SupervisorError::ChildVersaoInvalid {
10836                caixa: caixa.to_string(),
10837                versao: versao.to_string(),
10838                reason: reason.to_string(),
10839            },
10840            "lifted child_versao_invalid ctor must produce byte-equal \
10841             SupervisorError to the open-coded struct-literal wrap on the \
10842             same (&str, &str, reason) fixture",
10843        );
10844    }
10845
10846    #[test]
10847    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
10848        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
10849        // against a `&str`-literal vs. `format!(…)` reason input to pin
10850        // both constructors accept the `impl Into<String>` bound
10851        // uniformly, so neither wire-up site drifts under a per-arm
10852        // wrapper transformation on the caller-side `reason` axis. Peer
10853        // of the sibling
10854        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
10855        // sweep on the peer `AplicacaoError` envelope.
10856        let via_literal = "literal reason text";
10857        let via_format = format!("{} reason text", "literal");
10858        assert_eq!(
10859            SupervisorError::child_caixa_invalid("Worker", via_literal),
10860            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
10861        );
10862        assert_eq!(
10863            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
10864            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
10865        );
10866    }
10867
10868    #[test]
10869    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
10870        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
10871        // &str`) through a non-default fixture name against every
10872        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
10873        // so any wrapper-side lowercase / trim / truncate / re-order on
10874        // the `caixa.to_string()` sole-field construction surfaces
10875        // here rather than at a downstream diagnostic-shape mismatch.
10876        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
10877        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
10878        // through_to_string` / `contrato_target_ctors_route_edge_
10879        // triple_through_verbatim` / `contrato_empty_pair_ctors_
10880        // route_edge_pair_through_verbatim` cross-axis routing pins on
10881        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
10882        // here onto the `SupervisorError` `{ caixa: String }` envelope
10883        // so every substrate-primitive ctor family in caixa-core
10884        // guarantees the sole-field construction routes the caller's
10885        // `&str` through `.to_string()` verbatim.
10886        let name = "cache-v2";
10887        assert_eq!(
10888            SupervisorError::empty_child_version(name),
10889            SupervisorError::EmptyChildVersion {
10890                caixa: name.to_string(),
10891            },
10892        );
10893        assert_eq!(
10894            SupervisorError::duplicate_child_caixa(name),
10895            SupervisorError::DuplicateChildCaixa {
10896                caixa: name.to_string(),
10897            },
10898        );
10899        assert_eq!(
10900            SupervisorError::child_supervises_self(name),
10901            SupervisorError::ChildSupervisesSelf {
10902                caixa: name.to_string(),
10903            },
10904        );
10905    }
10906
10907    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
10908    //
10909    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
10910    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
10911    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
10912    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
10913    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
10914    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
10915    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
10916    // / silent constant-substitution on any one variant surfaces here rather
10917    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
10918    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
10919    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
10920    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
10921    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
10922    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
10923    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
10924    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
10925    #[test]
10926    fn no_children_ctor_matches_struct_literal_wrap() {
10927        let estrategia = RestartStrategy::OneForAll;
10928        assert_eq!(
10929            SupervisorError::no_children(estrategia),
10930            SupervisorError::NoChildren { estrategia },
10931            "generated no_children ctor must produce byte-equal \
10932             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
10933             on the same `Copy`-`RestartStrategy` fixture",
10934        );
10935    }
10936
10937    #[test]
10938    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
10939        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
10940        assert_eq!(
10941            SupervisorError::max_restarts_exceeds_cap(max_restarts),
10942            SupervisorError::MaxRestartsExceedsCap { max_restarts },
10943            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
10944             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
10945             struct-literal wrap on the same `Copy`-`u32` fixture",
10946        );
10947    }
10948
10949    #[test]
10950    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
10951        let window = Duration::from_micros(1_500);
10952        assert_eq!(
10953            SupervisorError::restart_window_not_canonical(window),
10954            SupervisorError::RestartWindowNotCanonical { window },
10955            "generated restart_window_not_canonical ctor must produce \
10956             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
10957             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
10958        );
10959    }
10960
10961    #[test]
10962    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
10963        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
10964        assert_eq!(
10965            SupervisorError::restart_window_exceeds_cap(window),
10966            SupervisorError::RestartWindowExceedsCap { window },
10967            "generated restart_window_exceeds_cap ctor must produce \
10968             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
10969             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
10970        );
10971    }
10972
10973    #[test]
10974    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
10975        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
10976        // constructor input axis through a non-default `Copy` fixture against
10977        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
10978        // side silent `.into()` / silent constant-substitution / silent field
10979        // re-name away from the canonical `estrategia | max_restarts | window`
10980        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
10981        // axis silently rerouted through some other `Copy` coercion, surfaces
10982        // here rather than at a downstream per-`:supervisor` diagnostic-shape
10983        // drift. Peer of the sibling
10984        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
10985        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
10986        // envelope's per-`:politicas` per-axis ctor family, extended here onto
10987        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
10988        // variant family folded onto a substrate primitive.
10989        //
10990        // Fixtures picked out of each variant's accept-set boundary rather
10991        // than the default value so a silent constant-substitution to a per-
10992        // variant sentinel surfaces here on the structural-equality assertion.
10993        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
10994        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
10995        // isn't the `SimpleOneForOne` arm the sibling
10996        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
10997        // `max_restarts` fixture picks an above-cap magnitude the cap arm
10998        // rejects; the two `Duration` fixtures pick the sub-millisecond and
10999        // above-cap ends of the `:restart-window` canonical-form + cap
11000        // bracket respectively.
11001        let estrategia = RestartStrategy::RestForOne;
11002        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
11003        let sub_ms = Duration::from_micros(1_500);
11004        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
11005        assert_eq!(
11006            SupervisorError::no_children(estrategia),
11007            SupervisorError::NoChildren { estrategia },
11008        );
11009        assert_eq!(
11010            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
11011            SupervisorError::MaxRestartsExceedsCap {
11012                max_restarts: above_cap_restarts,
11013            },
11014        );
11015        assert_eq!(
11016            SupervisorError::restart_window_not_canonical(sub_ms),
11017            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
11018        );
11019        assert_eq!(
11020            SupervisorError::restart_window_exceeds_cap(above_hour),
11021            SupervisorError::RestartWindowExceedsCap { window: above_hour },
11022        );
11023    }
11024
11025    #[test]
11026    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
11027        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
11028        // generated ctor `const fn` so a caller can pin a `SupervisorError`
11029        // at compile time — the same zero-runtime-work property the pre-lift
11030        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
11031        // its `Copy`-pass-through construction path (no `.to_string()` /
11032        // `.into()` allocation, no branching). If any future edit silently
11033        // drops the `const` qualifier from the macro body the per-arm `const`
11034        // bindings below fail to compile, which surfaces the regression at
11035        // the substrate-primitive definition rather than at some downstream
11036        // consumer that had come to rely on the `const`-constructibility.
11037        // Peer of the sibling
11038        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
11039        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
11040        // per-`:politicas` per-axis ctor family.
11041        const NO_CHILDREN: SupervisorError =
11042            SupervisorError::no_children(RestartStrategy::OneForAll);
11043        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
11044        const WINDOW_NC: SupervisorError =
11045            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
11046        const WINDOW_CAP: SupervisorError =
11047            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
11048        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
11049        assert!(matches!(
11050            MAX_RESTARTS_CAP,
11051            SupervisorError::MaxRestartsExceedsCap { .. }
11052        ));
11053        assert!(matches!(
11054            WINDOW_NC,
11055            SupervisorError::RestartWindowNotCanonical { .. }
11056        ));
11057        assert!(matches!(
11058            WINDOW_CAP,
11059            SupervisorError::RestartWindowExceedsCap { .. }
11060        ));
11061    }
11062}