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/// Per-child restart policy.
705///
706/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
707#[derive(
708    Serialize,
709    Deserialize,
710    Debug,
711    Clone,
712    Copy,
713    PartialEq,
714    Eq,
715    Hash,
716    gen_platform::TypedDispatcher,
717    gen_platform::Discriminant,
718    gen_platform::IsVariant,
719    gen_platform::FromStrKind,
720)]
721pub enum RestartPolicy {
722    /// Always restart the child, regardless of how it died. Used for
723    /// long-running services that must always be up.
724    Permanent,
725    /// Never restart. Used for one-shot work whose completion is
726    /// itself the success signal (`oneShot` triggers map here).
727    Temporary,
728    /// Restart only when the child died *abnormally* (non-zero exit
729    /// or unhandled exception). A clean exit completes the child.
730    Transient,
731}
732
733impl Default for RestartPolicy {
734    fn default() -> Self {
735        // Route the [`Default for RestartPolicy`] impl's return arm through
736        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
737        // `pub const` rather than a raw `Self::Permanent` arm — one source
738        // of truth for the Erlang/OTP-canonical `permanent` worker-child
739        // default across the two production consumers that currently
740        // dispatch on it (this impl at the [`RestartPolicy::default`] call
741        // and the serde-side `#[serde(default)]` on
742        // [`ChildSpec::restart`] that resolves an author-omitted
743        // `:children :restart` slot through `RestartPolicy::default()`).
744        // Peer of the sibling per-`:supervisor` axis
745        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
746        // route (95ffacc) — the two impls now share one substrate-primitive
747        // lift discipline, so any future coherent rebrand of the OTP-shape
748        // supervisor+child default set migrates through typed constants in
749        // lockstep instead of splitting a lifted supervisor half against
750        // an open-coded child half. Pinned by
751        // `restart_policy_default_routes_through_lifted_default` +
752        // `child_spec_serde_default_restart_routes_through_lifted_default`
753        // in the tests module.
754        SUPERVISOR_CHILD_RESTART_DEFAULT
755    }
756}
757
758impl RestartPolicy {
759    /// Exhaustive iteration surface for every consumer that walks the
760    /// closed three-arm [`RestartPolicy`] discriminator set (the future
761    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
762    /// per-child admission-webhook rejection body naming the accepted-
763    /// `:restart` list, a future `feira supervisor --restart …` CLI
764    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
765    /// over the slice, the future `feira app graph` per-child restart
766    /// column, any future round-trip fuzz harness that sweeps every
767    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
768    /// theory
769    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
770    /// might reach for once the three canonical OTP restart policies
771    /// stop covering the substrate's discovered load-shape) extends
772    /// this slice as one edit and every consumer picks up the new entry
773    /// by construction; the compiler-checked exhaustiveness on the
774    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
775    /// is the build-time guarantee that no arm forgets to grow.
776    ///
777    /// Peer of the sibling closed-set typed enums'
778    /// [`RestartStrategy::ALL`] (4eec29c) /
779    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
780    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
781    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
782    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
783    /// surfaces — the sixth (and the third and final M2 OTP-shape)
784    /// closed-set typed enum on the caixa surface to converge onto the
785    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
786    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
787    /// sibling-restart-strategy axis; this closes the per-child
788    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
789    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
790
791    /// Canonical PascalCase discriminator scalar this variant serializes
792    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
793    /// arms return the paired
794    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
795    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
796    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
797    /// constants so every substrate consumer that dispatches on the
798    /// per-child restart-decision policy (the future wasm-operator's
799    /// per-child post-exit restart-decision branch, the future M4
800    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
801    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
802    /// reconciliation scheduler's per-child-policy fan-out) reads the
803    /// same byte-string the `Serialize` derive emits — the pin test in
804    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
805    /// asserts the two paths agree, peer of the M2
806    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
807    /// sibling-restart-strategy axis and the M3
808    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
809    /// per-Aplicacao distribution-strategy axis — the third of three
810    /// OTP-shaped closed-enum discriminator axes on the caixa typed
811    /// surface to converge onto the same three-path-convergence
812    /// (`Serialize` derive → `as_str` helper → lifted constant)
813    /// drift-detection posture.
814    #[must_use]
815    pub const fn as_str(self) -> &'static str {
816        match self {
817            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
818            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
819            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
820        }
821    }
822
823    /// Substrate-canonical reverse projection on the `:children :restart`
824    /// closed-set axis — parses the `PascalCase` discriminator scalar
825    /// back to the typed variant, or `None` when `s` is outside the
826    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
827    /// the same lifted
828    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
829    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
830    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
831    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
832    /// of the round-trip migrate through one caixa-core edit on any
833    /// future arm addition.
834    ///
835    /// Prior to this lift the substrate carried only the forward
836    /// `Self → &str` projection on the OTP per-child restart-policy
837    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
838    /// impl routed through it, the `Serialize` derive that emits the
839    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
840    /// plus the kebab-case dispatcher-catalog identity via
841    /// [`Self::discriminant`] — every non-serde consumer that wanted to
842    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
843    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
844    /// "Transient" => …, _ => … }` cascade that expressed no
845    /// compile-time link back to the typed variant's canonical lifted
846    /// constant. A future variant rename or per-arm serde-attribute
847    /// drift would silently split the wire byte-string one non-serde
848    /// consumer parsed from the one the emitter wrote, with the failure
849    /// surfacing at the operator's reconcile posture (a `:temporary`
850    /// `oneShot` child being restarted on clean exit, treating the
851    /// successful-completion signal as failure and re-running the
852    /// completion-terminal one-shot indefinitely; a `:transient` child
853    /// that clean-exited being restarted, masking the clean-completion
854    /// contract) far from the rebrand commit and with no field naming
855    /// the drift.
856    ///
857    /// Distinct axis from the [`std::str::FromStr`] impl the
858    /// [`gen_platform::FromStrKind`] derive already installs on this
859    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
860    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
861    /// `"transient"` — the inverse of [`Self::discriminant`]), while
862    /// this method inverts the `PascalCase` wire byte-string
863    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
864    /// catalog identity live in kebab-case (where every peer catalog
865    /// identifier already lives) without forcing a wire-format rename
866    /// on the tatara-lisp author surface (`:restart Permanent`,
867    /// `PascalCase`) — the same two-axis distinction the sibling
868    /// [`RestartStrategy::from_wire`] (4eec29c) /
869    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
870    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
871    /// carry on their peer closed-set typed-enum wire round-trips.
872    ///
873    /// Same closed-set-reverse-projection discipline the sibling
874    /// [`RestartStrategy::from_wire`] (4eec29c) /
875    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
876    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
877    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
878    /// carry on the peer wire-side `str → Self` axes — extended onto
879    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
880    /// sixth substrate-side closed-set typed enum (and the third and
881    /// final OTP-shape closed-enum discriminator axis) to converge on
882    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
883    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
884    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
885    /// derive already installs on the sibling kebab-case axis. Returns
886    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
887    /// shapes: the caller picks the diagnostic form appropriate for
888    /// its use site.
889    #[must_use]
890    pub fn from_wire(s: &str) -> Option<Self> {
891        match s {
892            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
893            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
894            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
895            _ => None,
896        }
897    }
898}
899
900/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
901/// pretty-printed byte-string every consumer that formats the policy as
902/// user-facing text lands on (the future wasm-operator's per-child
903/// post-exit restart-decision diagnostic line, the future `feira app
904/// graph` per-child restart column, the future M4
905/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
906/// admission-webhook rejection body) reaches for the same lifted
907/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
908/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
909/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
910/// wire-format `Serialize` derive already emits under
911/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
912/// [`RestartPolicy::as_str`] helper already returns.
913///
914/// Pre-convergence the two paths structurally disagreed — the
915/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
916/// route (now retired here) sent [`std::fmt::Display`] through the
917/// gen-platform discriminant catalog string, which arrives kebab-case as
918/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
919/// (whose variant names each collapse to their own lowercase form under
920/// the kebab-case transform), while the wire format ran as `PascalCase`
921/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
922/// serde derive. Every consumer that formatted the policy for a
923/// diagnostic line, a graph column, or a rejection body under
924/// `format!("{v}")` therefore landed under a different byte-string than
925/// the wire format the operator's per-child-policy dispatch keyed off —
926/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
927/// diagnostic quoting `"permanent"` while the wire scalar the operator
928/// probed was `"Permanent"`) surfaced as a confused correlate at
929/// operator-log time far from the two-declaration site.
930///
931/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
932/// path: every `format!("{v}")` call reaches the same lifted
933/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
934/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
935/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
936/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
937/// byte-string per variant. A future variant rename or
938/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
939/// exactly one place, structurally.
940///
941/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
942/// (from `#[derive(gen_platform::Discriminant)]`) still returns
943/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
944/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
945/// registration keys the catalog off the same kebab identity. The two
946/// naming worlds now live on separate typed methods (`Display` /
947/// `as_str` for the wire byte-string, `discriminant` for the catalog
948/// identity) rather than sharing one `Display` route that structurally
949/// disagrees with the wire format.
950///
951/// Pin tests
952/// [`tests::restart_policy_display_routes_through_as_str_helper`]
953/// and
954/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
955/// assert the three paths agree byte-for-byte on every variant, so a
956/// future variant rename or per-arm serde attribute drift is a build
957/// error visible at caixa-core test time, not a silent per-consumer
958/// dispatch miss at apply / reconcile time.
959///
960/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
961/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
962/// and the sibling [`RestartStrategy`] `Display` impl on the
963/// per-supervisor sibling-restart-strategy axis — same three-path-
964/// convergence discipline, extended to close the third and final of
965/// three OTP-shaped closed-enum discriminator axes on the caixa typed
966/// surface.
967impl std::fmt::Display for RestartPolicy {
968    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
969        f.write_str(self.as_str())
970    }
971}
972
973/// Substrate-canonical [`AsRef<str>`] projection on the M2
974/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
975/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
976/// scalar accessor the paired [`std::fmt::Display`] impl and the
977/// un-`rename`d [`serde::Serialize`] derive already key off, so any
978/// future consumer that binds a [`RestartPolicy`] through the
979/// standard-library `impl AsRef<str>` bound (a future
980/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
981/// composes the emitted `PascalCase` wire scalar into a
982/// [`std::process::Command::arg`] shell-out of the future
983/// wasm-operator's per-child admission gate, a per-child structured-
984/// log recorder on the future `caixa-operator`'s hierarchical
985/// reconciliation surface that accepts `impl AsRef<str>` at the
986/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
987/// lookup keyed on the restart-policy wire byte through
988/// `map.get::<str>(policy.as_ref())` on a future per-policy
989/// dispatch table) reaches the paired
990/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
991/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
992/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
993/// lifted-const through one substrate-primitive dispatch rather
994/// than an open-coded `.as_str()` projection at every wire-up.
995///
996/// Peer of the sibling [`std::fmt::Display`] impl on the same
997/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
998/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
999/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1000/// byte-string per instance by construction. A future variant rename
1001/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1002/// enum reaches every one of the three paths (plus the wire-format
1003/// `Serialize` derive that already routes through the same lifted
1004/// const) through exactly one caixa-core edit.
1005///
1006/// Same "route the trait impl through the substrate-primitive
1007/// accessor" discipline the sibling [`crate::CaixaVersion`]
1008/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1009/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1010/// the axis onto the paired per-child-restart-decision-policy
1011/// sibling on the same M2 `:supervisor` slot (the second M2
1012/// OTP-shape closed-set typed enum to converge onto the standard-
1013/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1014/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1015/// primitive so a caller who has one has both; before this lift,
1016/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1017/// [`AsRef<str>`] impl the convention names.
1018///
1019/// Pinned load-bearing by
1020/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1021/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1022/// three-arm closed set) and
1023/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1024/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1025/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1026/// arm) — any future silent detour that routes the impl through a
1027/// divergent projection (a per-arm inline `match self { … }`
1028/// re-inlining that opens a compile-time link to the un-lifted
1029/// arm-literal, a swap onto the kebab-case
1030/// [`gen_platform::Discriminant`] catalog identity that would
1031/// collide the wire axis with the dispatcher-catalog axis) trips at
1032/// caixa-core test time under `assert_eq!` rather than at a
1033/// downstream `impl AsRef<str>`-bound consumer's silent split.
1034impl AsRef<str> for RestartPolicy {
1035    fn as_ref(&self) -> &str {
1036        self.as_str()
1037    }
1038}
1039
1040/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1041/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1042/// byte-for-byte through the paired substrate-primitive
1043/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1044/// consumer that binds a `PascalCase` `:children :restart` wire
1045/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1046/// axis (a future [`caixa-feira`] `feira supervisor --restart
1047/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1048/// `let restart: RestartPolicy = s.try_into()?`, a future
1049/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1050/// `spec.children[*].restart: String` field through
1051/// `RestartPolicy::try_from(&s)?`, a generic
1052/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1053/// set typed enums) reaches the same three-arm accept-set the sibling
1054/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1055/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1056/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1057/// … }` cascade whose arm-set has no compile-time link back to the
1058/// substrate primitive.
1059///
1060/// Complements the pre-existing forward-projection triple
1061/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1062/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1063/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1064/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1065/// caller who can project *out to* a `&str` can also project *in from*
1066/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1067/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1068/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1069/// trigger under a `FromStr` impl and to avoid colliding with the
1070/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1071/// already installs on the paired *kebab-case dispatcher-catalog* axis
1072/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1073/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1074/// idiomatic reverse axis on the *`PascalCase` wire* half without
1075/// disturbing either the method-named `from_wire` shape every sibling
1076/// closed-set typed enum on the substrate already carries or the
1077/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1078/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1079///
1080/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1081/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1082/// caller picks the diagnostic form appropriate for its use site (a
1083/// future `feira supervisor --restart` arg-parse composes its own
1084/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1085/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1086/// wraps the `Err(())` outcome with the accepted-set enumeration for
1087/// operator diagnostics, a `Result::map_err` at the call site lifts the
1088/// unit-error to a per-verb error type). Same shape the peer
1089/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1090/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1091/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1092/// their peer closed-set typed enums' reverse projections.
1093///
1094/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1095/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1096/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1097/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1098/// might reach for once the three canonical OTP restart policies stop
1099/// covering the substrate's discovered load-shape) grows the trait-
1100/// idiomatic axis by construction — one caixa-core edit on
1101/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1102/// projection every existing consumer keys off and the trait-idiomatic
1103/// reverse projection this impl exposes, without a coordinated rewrite
1104/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1105///
1106/// Extends the substrate-wide closed-set-enum reverse-projection family
1107/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1108/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1109/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1110/// closed-enum discriminator axis on the caixa surface — the paired
1111/// per-child `:children :restart` closed set the future wasm-operator's
1112/// hierarchical reconciliation scheduler's per-child post-exit
1113/// restart-decision branch keys off end-to-end.
1114///
1115/// Pinned load-bearing by
1116/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1117/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1118/// three-arm accept-set),
1119/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1120/// (rejection witness against silent accept-set widening), and
1121/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1122/// (cross-axis partition pin locking the trait and method-named
1123/// projections onto one accept-set).
1124impl TryFrom<&str> for RestartPolicy {
1125    type Error = ();
1126
1127    fn try_from(s: &str) -> Result<Self, Self::Error> {
1128        Self::from_wire(s).ok_or(())
1129    }
1130}
1131
1132/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1133/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1134/// byte-for-byte through the paired substrate-primitive
1135/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1136/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1137/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1138/// &str` with `'static` lifetime, so the trait's return-type promise is
1139/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1140/// literal.
1141///
1142/// Every future consumer that specifically needs `&'static str` lifetime
1143/// bytes on the per-child restart-decision axis (a
1144/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1145/// arm's typing demands `&'static str`, a
1146/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1147/// on the future M4 admission-webhook rejection body where the
1148/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1149/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1150/// or error formatter that requires the `'static` bound) reaches the same
1151/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1152/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1153/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1154/// primitive dispatch rather than an open-coded per-arm literal cascade
1155/// whose arm-set has no compile-time link back to the substrate primitive.
1156///
1157/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1158/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1159/// the second (and second-of-two-in-M2) closed-set typed enum on the
1160/// caixa surface to converge onto the paired trait-idiomatic forward-
1161/// projection axis. With this lift the paired per-child
1162/// `:children :restart` closed-set typed enum carries the full sibling
1163/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1164/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1165/// lift) plus the round-trip witness through both the trait-idiomatic
1166/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1167/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1168/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1169/// (an OTP-`intrinsic` fourth arm the theory
1170/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1171/// might reach for once the three canonical OTP restart policies stop
1172/// covering the substrate's discovered load-shape) grows the trait-
1173/// idiomatic forward axis by construction: one caixa-core edit on
1174/// [`RestartPolicy::as_str`] extends every one of the five sibling
1175/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1176/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1177/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1178/// bytes) without a coordinated rewrite across every future
1179/// `Into<&'static str>`-bound consumer's arm-set.
1180///
1181/// Pinned load-bearing by
1182/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1183/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1184/// three-arm emit-set, plus a `const`-context materialization witness for
1185/// the `&'static str` lifetime promise) and
1186/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1187/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1188/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1189/// round-trip witness through the paired trait-idiomatic reverse-
1190/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1191/// `policy.into::<&'static str>()` output re-parses back through
1192/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1193/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1194impl From<RestartPolicy> for &'static str {
1195    fn from(policy: RestartPolicy) -> &'static str {
1196        policy.as_str()
1197    }
1198}
1199
1200/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
1201/// *borrowed* input onto the `&'static str` axis — the borrowed-input
1202/// companion to the paired owned-input [`From<RestartPolicy> for
1203/// &'static str`] impl immediately above. Routes byte-for-byte through
1204/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
1205/// fn` accessor so every consumer that binds a `&RestartPolicy`
1206/// through the standard-library `.into()` / [`From<&Self> for &'static
1207/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
1208/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
1209/// whose iterator over `&'static [RestartPolicy]` yields
1210/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
1211/// [`From<RestartPolicy>`] axis alone forces every call site through
1212/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
1213/// rather than the direct trait-idiomatic projection; a future generic
1214/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
1215/// that walks the `iter().map(Into::into)` shape verbatim across every
1216/// substrate-wide closed-set typed enum; the future wasm-operator's
1217/// per-child post-exit restart-decision diagnostic line that composes
1218/// the accepted-set enumeration from an iterated
1219/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1220/// per-arm `match p { … }` cascade; a future
1221/// `HashMap::<&'static str, RestartPolicy>::from_iter(
1222///     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
1223/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
1224/// cannot compose without this borrowed-input axis in place) reaches
1225/// the same three-arm lifted
1226/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1227/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1228/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1229/// paired owned-input [`From<RestartPolicy> for &'static str`], the
1230/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
1231/// [`RestartPolicy::as_str`] surfaces already return.
1232///
1233/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
1234/// forward-projection family opened on [`crate::dep::DepList`]
1235/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
1236/// [`crate::CaixaDialeto`] (807b0b5), and the paired
1237/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
1238/// (e941836). Rust's `From` trait does not auto-derive the
1239/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
1240/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
1241/// exist in `core`), so every closed-set typed enum that carries the
1242/// owned-input axis but not the borrowed-input axis forces every
1243/// borrowed-input call site through a `.copied()` /
1244/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
1245/// type bounds have no compile-time link to the substrate primitive.
1246/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
1247/// OTP-shape peer to converge onto this campaign — sibling of the
1248/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
1249/// with this lift both closed-set typed enums on the M2 `:supervisor`
1250/// slot now carry the full sibling quintet ([`std::fmt::Display`],
1251/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
1252/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
1253/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
1254/// forward-projection axis on the M2 OTP-shape slot as a unit.
1255///
1256/// Same three-path convergence discipline as the paired owned-input
1257/// impl (this borrowed-input axis, the paired owned-input
1258/// [`From<RestartPolicy> for &'static str`], and
1259/// [`RestartPolicy::as_str`] all route through the same lifted
1260/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
1261/// variant rename or per-arm serde-attribute drift reaches every one
1262/// of the six sibling forward-projection paths
1263/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1264/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
1265/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
1266/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
1267/// edit.
1268///
1269/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
1270/// parse share the same `PascalCase` vocabulary by construction, so
1271/// the borrowed-input forward axis and the reverse axis compose
1272/// directly — the round-trip witness pin below locks this direct
1273/// composition without the intermediate wire-vocab hop the peer
1274/// [`crate::CaixaKind`] axis pair requires.
1275///
1276/// Pinned load-bearing by
1277/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
1278/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1279/// three-arm emit-set via a borrowed input, plus a `const`-context
1280/// materialization witness for the `&'static str` lifetime promise,
1281/// plus a blanket `.into()` shape) and
1282/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
1283/// (cross-axis partition pin against the paired owned-input
1284/// [`From<RestartPolicy> for &'static str`] impl, plus a
1285/// `.iter().map(Into::into)` pipe witness over
1286/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1287/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
1288/// Self` round-trip without the wire-vocab intermediate the peer
1289/// [`crate::CaixaKind`] axis pair requires).
1290impl From<&RestartPolicy> for &'static str {
1291    fn from(policy: &RestartPolicy) -> &'static str {
1292        policy.as_str()
1293    }
1294}
1295
1296/// Trait-idiomatic *owned-`String`* forward projection on the second
1297/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
1298/// owned-heap-string companion to the paired `&'static str`-returning
1299/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
1300/// for &'static str`] impls immediately above. Routes byte-for-byte
1301/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
1302/// const fn` accessor (via [`str::to_owned`]) so every consumer that
1303/// binds a [`RestartPolicy`] through the standard-library `.into()` /
1304/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
1305/// future `serde_json::Value::String(policy.into())` structured-payload
1306/// composer where the `Value::String` arm typing demands an owned
1307/// [`String`] and the sibling [`&'static str`]-returning axis forces
1308/// an explicit `.to_owned()` / `String::from` restatement at every
1309/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
1310/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
1311/// lookup where the map's key type is owned [`String`] rather than
1312/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
1313/// composer on the future M4 admission-webhook rejection body's
1314/// owned-arm, the future wasm-operator's per-child post-exit
1315/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
1316/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
1317/// — reaches the same three-arm lifted
1318/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1319/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1320/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1321/// paired [`std::fmt::Display`], [`AsRef<str>`],
1322/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
1323/// forward-projection impls already return.
1324///
1325/// Extends the trait-idiomatic *owned-`String`* forward-projection
1326/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
1327/// the caixa surface — mirror of the first-mover
1328/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
1329/// axis on the sibling supervisor-level strategy enum. Rust's standard
1330/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
1331/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
1332/// every closed-set typed enum that carries the paired `AsRef<str>` /
1333/// `Display` / `From<Self> for &'static str` triple but not the
1334/// owned-[`String`] axis forces every owned-string call site through a
1335/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
1336/// detour whose type bounds have no compile-time link to the
1337/// substrate primitive.
1338///
1339/// Deliberately routes through the human-readable
1340/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1341/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1342/// the diagnostic byte-string share the same vocabulary by
1343/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1344/// two axes diverge), so the owned-[`String`] projection lands
1345/// byte-identically on both the wire vocabulary the paired
1346/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
1347/// [`RestartPolicy::as_str`] helper returns, and — because the paired
1348/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
1349/// axis parses the same `PascalCase` vocabulary — the direct two-way
1350/// `Self → String → Self` round-trip composes without the wire-vocab
1351/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
1352/// axis pair requires.
1353///
1354/// Pinned load-bearing by
1355/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
1356/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1357/// three-arm emit-set, plus a blanket `.into::<String>()` shape
1358/// witness) and
1359/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
1360/// (cross-axis partition pin against the paired owned-input
1361/// [`From<RestartPolicy> for &'static str`] impl and the sibling
1362/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
1363/// plus a `.iter().copied().map(String::from)` pipe witness over
1364/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1365/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
1366/// borrow that closes the two-way `Self → String → Self` round-trip
1367/// on the trait-idiomatic owned-[`String`] forward + reverse axis
1368/// pair).
1369impl From<RestartPolicy> for String {
1370    fn from(policy: RestartPolicy) -> String {
1371        policy.as_str().to_owned()
1372    }
1373}
1374
1375// Fleet-wide dispatcher-catalog registrations for caixa's OTP
1376// supervisor surface — two more typed shadows over Erlang/OTP
1377// primitives the substrate now mechanically tracks (see
1378// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
1379// theory/TYPED-ABSORPTION.md for the absorption arc).
1380gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
1381gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
1382
1383/// One child entry in the supervisor's `:children` list.
1384///
1385/// Every child references another caixa by `:caixa <nome>` + version
1386/// constraint. The supervisor materializes one ComputeUnit per entry.
1387#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1388#[serde(rename_all = "camelCase")]
1389pub struct ChildSpec {
1390    /// The child caixa's `:nome`. Must resolve via the same dependency
1391    /// resolution path as `:deps` (caixa-resolver).
1392    pub caixa: String,
1393
1394    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
1395    /// [`crate::dep::Dep::versao`].
1396    pub versao: String,
1397
1398    /// Restart policy — an author-omitted slot degrades onto the
1399    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
1400    /// (`permanent`, the Erlang/OTP worker-child default) through the
1401    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
1402    /// to.
1403    #[serde(default)]
1404    pub restart: RestartPolicy,
1405}
1406
1407impl ChildSpec {
1408    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
1409    /// accessor every consumer that reads the OTP-shape supervised
1410    /// child's identity keys off — returns the author-declared
1411    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
1412    /// from the typed slot's own [`String`] storage.
1413    ///
1414    /// The `:children :caixa` slot carries the DNS-1123 label — the
1415    /// child caixa's `:nome` — that every emitted cluster artifact
1416    /// derives its `metadata.name` from verbatim: the rendered
1417    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
1418    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
1419    /// identity, and the per-child K8s Service `metadata.name` the
1420    /// future wasm-operator (M3) provisions for inter-child supervision-
1421    /// tree wiring. Every downstream consumer that fans on the child's
1422    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
1423    /// per-child DNS-1123 gate at
1424    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
1425    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
1426    /// [`validate_no_self_supervision`] cross-slot equality check
1427    /// against the parent's `:nome`, every `SupervisorError` variant
1428    /// carrying the offending child caixa verbatim for `feira lint`
1429    /// rendering, the future wasm-operator's hierarchical reconciliation
1430    /// scheduler's per-child ComputeUnit-name projection, the future M4
1431    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1432    /// admission webhook).
1433    ///
1434    /// Prior to this lift the `.caixa` byte-string was accessed inline
1435    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
1436    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
1437    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
1438    /// carriers' `child.caixa.clone()`, the dedup key's
1439    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
1440    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
1441    /// field-accesses that expressed no compile-time link back to the
1442    /// typed slot. A future extension of the `:children :caixa` axis to
1443    /// a richer author surface (a per-cluster alias table the operator
1444    /// pins through a future `:placement`-scoped slot on the supervisor
1445    /// tree, a namespace-qualified rewrite the M4 CR materializer
1446    /// applies per-CR, a per-child overlay from the future `:children
1447    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1448    /// acknowledges) would have had to be threaded through every
1449    /// open-coded copy in lockstep or one consumer would silently
1450    /// disagree with the peers on which caixa a given child resolves to
1451    /// — a child-set lookup that treated the name as `"cart-worker"`
1452    /// while the peer duplicate-detector treated it as
1453    /// `"tenant-a/cart-worker"` would silently split the
1454    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
1455    /// self-supervision detector's parent-equality check, a two-consumer
1456    /// split at the validator far from the source `caixa.lisp` with no
1457    /// field naming the identity-drift root cause. Lifting the resolution
1458    /// rule to a typed method on the substrate primitive means every
1459    /// downstream consumer of the Supervisor's per-`:children` identity
1460    /// surface reaches for exactly one typed dispatch — the resolver's
1461    /// accept-set migrates as a unit on any future axis addition.
1462    ///
1463    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
1464    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
1465    /// mesh-slot surface — same "one typed dispatch on the substrate
1466    /// primitive, thin projections at each consumer" discipline extended
1467    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
1468    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
1469    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
1470    /// accessor discipline for the shared substrate concept "another
1471    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
1472    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
1473    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
1474    /// slot family's typed-accessor discipline now spans both the
1475    /// upgrade axis (`:upgrade-from`) and the supervision axis
1476    /// (`:children`), matching the closed M3 mesh-slot accessor family's
1477    /// shape. Named `nome()` to match the tatara-lisp author-surface
1478    /// term the field's docstring already reaches for ("The child
1479    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
1480    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
1481    /// discipline the substrate already carries — the accessor's name
1482    /// maps directly onto the canonical caixa-identity vocabulary rather
1483    /// than shadowing the field's storage-side `caixa` label.
1484    #[must_use]
1485    pub const fn nome(&self) -> &str {
1486        self.caixa.as_str()
1487    }
1488
1489    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
1490    /// requirement scalar accessor every consumer that reads the OTP-shape
1491    /// supervised child's version pin keys off — returns the author-declared
1492    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
1493    /// the typed slot's own [`String`] storage.
1494    ///
1495    /// The `:children :versao` slot carries the Cargo-shaped semver
1496    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
1497    /// which release of the supervised child caixa the OTP-shape supervisor
1498    /// tree materializes against — the same requirement grammar the peer
1499    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
1500    /// shared [`crate::render::require_valid_versao_requirement`] cascade
1501    /// and the shared [`crate::version::parse_requirement`] parser. Every
1502    /// downstream consumer that fans on the child's version pin keys off
1503    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
1504    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
1505    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
1506    /// for `feira lint` rendering, every future per-cluster version-lock
1507    /// overlay the caixa-operator's hierarchical reconciliation scheduler
1508    /// pins through a future `:placement`-scoped supervisor-tree slot, the
1509    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1510    /// per-child version resolver, the future wasm-operator's per-child
1511    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
1512    ///
1513    /// Prior to this lift the `.versao` byte-string was accessed inline at
1514    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
1515    /// [`SupervisorSpec::validate`] requirement-gate call
1516    /// `require_valid_versao_requirement(&child.versao, …)` and the
1517    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
1518    /// `versao: child.versao.clone()` — two open-coded field-accesses that
1519    /// expressed no compile-time link back to the typed slot. A future
1520    /// extension of the `:children :versao` axis to a richer author surface
1521    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1522    /// flow, a lacre-projected concrete-version rewrite the operator
1523    /// materializes at CR-admission time, a future `:children :versao-lock`
1524    /// per-cluster override slot the wasm-operator's hierarchical
1525    /// reconciliation scheduler authors per-CR) would have had to be
1526    /// threaded through both open-coded copies in lockstep or one consumer
1527    /// would silently disagree with the peer on which release constraint a
1528    /// given child resolves to — the requirement-gate call reading
1529    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
1530    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
1531    /// the actual gate rejection input, a two-consumer split at the
1532    /// validator far from the source `caixa.lisp` with no field naming the
1533    /// version-pin drift root cause. Lifting the resolution rule to a typed
1534    /// method on the substrate primitive means every downstream
1535    /// requirement-facing consumer of the Supervisor's per-`:children`
1536    /// version-pin surface reaches for exactly one typed dispatch — the
1537    /// resolver's accept-set migrates as a unit on any future axis addition.
1538    ///
1539    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
1540    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
1541    /// surface — same "one typed dispatch on the substrate primitive, thin
1542    /// projections at each consumer" discipline extended onto the M2
1543    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
1544    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
1545    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
1546    /// one accessor discipline for the shared substrate concept "another
1547    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
1548    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
1549    /// `:nome` scalar accessor — the pair
1550    /// `(nome(), versao_requirement())` jointly projects the
1551    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
1552    /// that fans on per-child identity + version pin keys off, closing the
1553    /// last unlifted per-`:children` `String`-carry axis so every downstream
1554    /// per-`:children` reader now routes through a typed dispatch on the
1555    /// substrate primitive. Named `versao_requirement()` rather than
1556    /// `versao()` because the field's storage-side `.versao` label is
1557    /// already the author-surface term (`:versao`); the accessor's name
1558    /// carries the semantic role — the semver *requirement* string the
1559    /// shared [`crate::version::parse_requirement`] entry-point consumes —
1560    /// so a raw field access and a typed dispatch read differently at every
1561    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
1562    /// naming discipline verbatim.
1563    #[must_use]
1564    pub const fn versao_requirement(&self) -> &str {
1565        self.versao.as_str()
1566    }
1567
1568    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
1569    /// per-child post-exit restart-decision policy scalar accessor every
1570    /// consumer that dispatches on the supervised child's post-exit
1571    /// reconcile posture keys off — returns the author-declared
1572    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
1573    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
1574    /// storage.
1575    ///
1576    /// The `:children :restart` slot carries the closed-set OTP-shaped
1577    /// per-child restart-decision policy discriminator
1578    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
1579    /// worker-child default; [`RestartPolicy::Transient`] — restart only
1580    /// on abnormal exit, the OTP `transient` clean-completion-aware
1581    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
1582    /// `temporary` one-shot default) that every downstream consumer of
1583    /// the Supervisor's per-child post-exit reconcile branch keys off.
1584    /// Every future downstream consumer that fans on the per-child
1585    /// restart-decision keys off this scalar (the future `feira app
1586    /// graph` per-child restart column, the future wasm-operator's
1587    /// per-child post-exit restart-decision branch, the future M4
1588    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1589    /// admission webhook, the `caixa-operator`'s hierarchical
1590    /// reconciliation scheduler's per-child post-exit reconcile branch,
1591    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
1592    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1593    /// pin threads through).
1594    ///
1595    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
1596    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
1597    /// scalar accessor and the M3 mesh-slot
1598    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
1599    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
1600    /// — same "one typed dispatch on the substrate primitive,
1601    /// `Copy`-projected closed-set enum-arm discriminator that partitions
1602    /// the downstream renderer's per-arm fan-out" discipline extended
1603    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
1604    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
1605    /// [`ChildSpec`] type — companion to the sibling per-`:children`
1606    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
1607    /// and the per-`:children` [`ChildSpec::versao_requirement`]
1608    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
1609    /// on the sibling `String`-carry axes. The triple
1610    /// `(nome(), versao_requirement(), restart())` jointly projects the
1611    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
1612    /// tree consumer that fans on per-child identity + version pin +
1613    /// restart-decision keys off, closing the last unlifted per-`:children`
1614    /// axis so every downstream per-`:children` reader now routes through
1615    /// a typed dispatch on the substrate primitive. Named `restart()` to
1616    /// match the storage field's name and the author-surface
1617    /// `:children :restart` slot term verbatim; the accessor's identity
1618    /// name maps onto the canonical OTP-shape per-child restart-decision-
1619    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
1620    /// carries.
1621    ///
1622    /// Declared `pub const fn` to close the last non-`const`
1623    /// `Copy`-return raw-field-getter posture on the M2
1624    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
1625    /// of the sibling M2 per-`:supervisor`
1626    /// [`SupervisorSpec::estrategia`] (converted in this commit)
1627    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
1628    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1629    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
1630    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
1631    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
1632    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
1633    /// downstream substrate-side `const`-context consumer of the
1634    /// per-`:children` restart-decision-policy scalar (a future
1635    /// module-scope `const _:() = assert!(matches!(child.restart(),
1636    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
1637    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1638    /// admission-webhook `const fn` per-child restart-decision floor
1639    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
1640    /// composer over the substrate primitive that fans on the per-child
1641    /// restart-decision policy at compile time) now reaches through the
1642    /// same typed dispatch on the substrate primitive at const-eval
1643    /// time as at runtime. A future non-`Copy`-return promotion of the
1644    /// scalar (an `Option<RestartPolicy>`-shape migration on the
1645    /// per-child restart-decision axis once heterogeneous per-cluster
1646    /// restart-policy overlays land, a per-tenant restart-policy-alias
1647    /// table the M4 CR materializer resolves per-CR) that would drop
1648    /// the `const` qualifier fails the fail-before-pass-after pin
1649    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
1650    /// build time rather than surfacing as a downstream consumer
1651    /// regression.
1652    #[must_use]
1653    pub const fn restart(&self) -> RestartPolicy {
1654        self.restart
1655    }
1656}
1657
1658/// Supervisor-typed slots that live alongside the standard Caixa
1659/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
1660/// the manifest stays a single typed form; this struct exists for
1661/// validation + conversion.
1662#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1663#[serde(rename_all = "camelCase")]
1664pub struct SupervisorSpec {
1665    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
1666    #[serde(default)]
1667    pub estrategia: RestartStrategy,
1668
1669    /// Max restarts within [`Self::restart_window`] before the
1670    /// supervisor itself terminates (and its parent supervisor decides
1671    /// what to do). Default 5.
1672    #[serde(default = "default_max_restarts")]
1673    pub max_restarts: u32,
1674
1675    /// Sliding window for `max_restarts`. Authored as a duration
1676    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
1677    /// is rejected by [`Self::validate`] — Erlang/OTP's
1678    /// `MaxIntensity / Period` invariant requires a positive window
1679    /// (a zero-period supervisor either trips on the first failure or
1680    /// never trips, depending on operator interpretation, neither of
1681    /// which is the author's intent). Omit the slot to express "no
1682    /// reset"; carry a positive duration to express the sliding window.
1683    #[serde(
1684        default,
1685        skip_serializing_if = "Option::is_none",
1686        with = "duration_codec"
1687    )]
1688    pub restart_window: Option<Duration>,
1689
1690    /// Static children. Empty for `SimpleOneForOne` (children added
1691    /// dynamically); required for the other three strategies.
1692    #[serde(default)]
1693    pub children: Vec<ChildSpec>,
1694}
1695
1696const fn default_max_restarts() -> u32 {
1697    // Route the private serde-`#[serde(default = "…")]` helper through
1698    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
1699    // `pub const` rather than the raw `5` literal — one source of truth
1700    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
1701    // default across the two production consumers that currently
1702    // dispatch on it (this helper via `#[serde(default = "…")]` on
1703    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
1704    // impl at line 962). Pinned by
1705    // `default_max_restarts_helper_routes_through_lifted_default` +
1706    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
1707    // in the tests module; peer of the sibling caixa-core
1708    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
1709    // that now routes its author-omitted `:max-restarts` arm through
1710    // the same lifted constant.
1711    SUPERVISOR_MAX_RESTARTS_DEFAULT
1712}
1713
1714/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
1715/// count default for the `:supervisor :max-restarts` axis — the
1716/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
1717/// Erlang's worker-supervisor default, extracted as a typed `pub const`
1718/// so every substrate-side consumer that resolves "what
1719/// [`SupervisorSpec::max_restarts`] value does an author-omitted
1720/// `:max-restarts` slot degrade onto?" reaches for exactly one
1721/// substrate-primitive `u32`.
1722///
1723/// The `:max-restarts` default axis has two production consumers on the
1724/// substrate side today (both prior to this lift folded onto raw `5`
1725/// literals with no compile-time link back to a shared truth): the
1726/// serde-`#[serde(default = "default_max_restarts")]` helper on
1727/// [`SupervisorSpec::max_restarts`] that every author-omitted
1728/// `:supervisor :max-restarts` slot lands in past the derive-macro's
1729/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
1730/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
1731/// the composed [`SupervisorSpec`] altitude reaches through
1732/// (`feira app graph`, the future wasm-operator's per-supervisor
1733/// restart-intensity counter, the future M4
1734/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1735/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
1736/// A pair of open-coded `5`s across two files that expressed no
1737/// compile-time link back to the shared OTP-canonical default — a
1738/// future rebrand of the default (a tightening to Elixir's
1739/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
1740/// the operator pins through a future
1741/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
1742/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1743/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
1744/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
1745/// per-child-cohort roadmap lands) would have had to be threaded
1746/// through both open-coded copies in lockstep or the wire-format
1747/// author-omitted arm and the view-construction author-omitted arm
1748/// would silently disagree on which restart-budget an omitted
1749/// `:max-restarts` resolves to (an author writing `:supervisor
1750/// (:max-restarts ())` would round-trip through serde with the new
1751/// default while `supervisor_view` silently continued to compose the
1752/// stale `5`, or vice versa), a two-consumer split at the composition
1753/// boundary far from the source `caixa.lisp` with no field naming the
1754/// default-drift root cause. Lifting the resolution rule to a typed
1755/// `pub const` on the substrate primitive means every downstream
1756/// consumer of the per-Supervisor default-restart-budget-count surface
1757/// reaches for exactly one substrate-primitive `u32` — the resolver's
1758/// accepted value migrates as a unit on any future axis change.
1759///
1760/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1761/// worker-supervisor default (the closest canonical OTP-shape
1762/// production reference the substrate carries, matching the sibling
1763/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
1764/// this constant with on the paired sliding-window axis). Two orders of
1765/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
1766/// (the upper bracket on the same axis, sibling of this lower default;
1767/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
1768/// axis and now share one accessor discipline on the substrate) and
1769/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
1770/// restart floor — the "one restart, then escalate" default is
1771/// deliberately loose enough to absorb a short burst of transient
1772/// child failures without escalating past the supervisor's parent
1773/// while remaining tight enough to trip the `MaxIntensity / Period`
1774/// ratio's escalation on a genuinely-stuck child within the sibling
1775/// `60s` sliding window.
1776///
1777/// Lifted as a typed `pub const` so the bound has exactly one source
1778/// of truth — the serde-side wire-format author-omitted arm at
1779/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
1780/// struct-literal default field, and the caixa-core
1781/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
1782/// arm all read from one place. Same shape every other typed default
1783/// in this crate carries (the sibling
1784/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
1785/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
1786/// sibling `:restart-window` axis, and the peer
1787/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1788/// per-renderer defaults on the caixa-flux / caixa-helm rendering
1789/// axes).
1790pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
1791
1792/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
1793/// validated [`SupervisorSpec::max_restarts`] past
1794/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
1795///
1796/// The typed field is `u32` (the zero-floor arm
1797/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
1798/// so a programmatic struct literal
1799/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
1800/// author-surface form (`:max-restarts 4294967295` or any
1801/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
1802/// cleanly through serde — a structurally unbounded `u32` ceiling. The
1803/// runtime substrate consuming the value (Erlang/OTP's
1804/// `MaxIntensity / Period` ratio, the future wasm-operator's
1805/// per-supervisor restart-intensity counter, the M4
1806/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
1807/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
1808/// escalation threshold is structurally so high that no realistic
1809/// restarts-per-`:restart-window` traffic shape can reach it, the
1810/// supervisor never escalates to its parent, and a bad child can loop
1811/// inside the window indefinitely with the parent supervisor structurally
1812/// never receiving the "this subtree has exceeded its restart budget"
1813/// signal the typed slot is meant to express — the canonical
1814/// "supervisor intensity declared, no escalation" footgun, exactly the
1815/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
1816/// on the `:politicas :circuit-breaker :max-failures` axis (both are
1817/// "trip the next-higher protection layer after N events in a rolling
1818/// window" counters with identical degenerate-at-the-high-end shape).
1819///
1820/// The `1000` ceiling matches the sibling
1821/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
1822/// peer — same "events-per-window trip threshold" semantics, same `u32`
1823/// type, same no-op-at-the-high-end failure mode) so the M4
1824/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
1825/// and the future wasm-operator's per-supervisor restart-intensity
1826/// counter reach for either field knowing the value is in `1..=1000`
1827/// without re-validating at the reconciler layer. The cap sits two
1828/// orders of magnitude above every documented Erlang/OTP production
1829/// playbook recommendation (Learn You Some Erlang's
1830/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
1831/// `max_restarts: 3` default, OTP's `supervisor` callback module
1832/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
1833/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
1834/// default) and below the clearly-pathological "effectively no
1835/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
1836/// author can plausibly want at hyperscale (a long-running supervisor
1837/// over a very-flaky pool tolerating thousands of transient restarts
1838/// before escalating), but a hard wall above which the typed policy is
1839/// structurally a no-op carried verbatim on every emitted child-restart
1840/// reconciliation contract.
1841///
1842/// Lifted as a typed `pub const` so the bound has exactly one source of
1843/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1844/// materializer's admission webhook and the wasm-operator-side
1845/// per-supervisor restart-intensity reconciler read from one place. Same
1846/// shape every other typed upper bound in this crate carries
1847/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1848/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1849/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1850/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1851/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1852/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1853pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
1854
1855/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
1856/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
1857/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
1858/// (inclusive on both ends, integer-millisecond magnitudes by the
1859/// canonical-form gate immediately preceding).
1860///
1861/// The typed field is `Option<Duration>` (the zero-floor arm
1862/// [`SupervisorError::RestartWindowZero`] already rejects
1863/// `Some(Duration::ZERO)`, and the canonical-form arm
1864/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
1865/// sub-millisecond residue), so a programmatic struct literal
1866/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
1867/// .. }` — 24h) and the equivalent author-surface form
1868/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
1869/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
1870/// cleanly through serde — a structurally unbounded `Duration` ceiling.
1871/// A `:restart-window` value far above the documented Erlang/OTP
1872/// `MaxIntensity / Period` production-playbook band (Learn You Some
1873/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
1874/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
1875/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
1876/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
1877/// degenerates the supervisor's restart-intensity counter into a
1878/// lifetime counter: the rolling failure-counting window is structurally
1879/// so long that transient restarts are never forgotten, so the
1880/// `MaxIntensity / Period` ratio degenerates from "trip the parent
1881/// supervisor when the child has exceeded its restart budget *within
1882/// the recent window*" to "trip the parent when the child has exceeded
1883/// its restart budget *over its lifetime*" — every transient restart
1884/// counts against the budget forever, the supervisor's reset semantic
1885/// never reaches the child, and the typed `:restart-window` slot
1886/// becomes a no-op rolling window carried on every emitted hierarchical
1887/// reconciliation contract. The canonical
1888/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
1889/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
1890/// `:politicas :circuit-breaker :window` axis with identical shape (both
1891/// are "rolling failure-counting window with a per-`Period` reset" Duration
1892/// axes whose lifetime-counter degenerate at the high end is the same
1893/// "the reset semantic never fires" CSE invariant violation).
1894///
1895/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
1896/// the shared duration codec emits (`"<n>h"` for any integer-hour
1897/// magnitude) — every value in the canonical authoring form's
1898/// `<integer><unit>` grammar at or below this cap renders to a clean
1899/// canonical string — and matches the three sibling typed-`Duration`
1900/// caps already lifted to this surface
1901/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1902/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
1903/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
1904/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
1905/// per-supervisor `:supervisor :restart-window` — now share a single
1906/// uniform top edge at the codec's largest emitted unit so the next
1907/// typed-slot wiring (the future wasm-operator's per-supervisor
1908/// `MaxIntensity / Period` reconciler, the M4
1909/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1910/// webhook, the `caixa-operator`'s hierarchical reconciliation
1911/// scheduler) reaches for any of the four knowing the value is in
1912/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
1913/// two orders of magnitude above every documented Erlang/OTP / Elixir /
1914/// Riak Core / RabbitMQ production-playbook recommendation band
1915/// (`5s..=300s`) and below the clearly-pathological "rolling window
1916/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
1917/// a value the author can plausibly want for a very-low-traffic
1918/// long-tail failure-restart window over a hyperscale-flaky child pool,
1919/// but a hard wall above which the rolling-window contract is
1920/// structurally a lifetime-counter contract.
1921///
1922/// Lifted as a typed `pub const` so the bound has exactly one source
1923/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1924/// materializer's admission webhook, the wasm-operator-side
1925/// per-supervisor `MaxIntensity / Period` reconciler, and the
1926/// `caixa-operator`'s hierarchical reconciliation scheduler all read
1927/// from one place. Same shape every other typed upper bound in this
1928/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
1929/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1930/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1931/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1932/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1933/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1934/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
1935/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1936/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1937pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
1938
1939/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
1940/// default for the `:supervisor :restart-window` axis — the canonical
1941/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
1942/// worker-supervisor default, extracted as a typed `pub const` so every
1943/// substrate-side consumer that resolves "what
1944/// [`SupervisorSpec::restart_window`] value does an author-omitted
1945/// `:restart-window` slot degrade onto?" reaches for exactly one
1946/// substrate-primitive [`Duration`].
1947///
1948/// The `:restart-window` default axis has one production consumer on the
1949/// substrate side today: the [`Default for SupervisorSpec`] impl's
1950/// struct-literal `restart_window` field, which prior to this lift folded
1951/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
1952/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
1953/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
1954/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
1955/// *not* fall back to this default on the sibling `:restart-window` axis
1956/// — an author-omitted `:supervisor :restart-window` composes to
1957/// `restart_window: None` (the shared codec's soft-swallow shape),
1958/// keeping author-declared intent ("no reset — never escalate on rolling
1959/// window") distinct from the [`Default for SupervisorSpec`] "canonical
1960/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
1961/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
1962/// default was split across two files with no compile-time link between
1963/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
1964/// `MaxIntensity` half at the substrate primitive while the `Period`
1965/// half rode as an open-coded literal at the composition site, so a
1966/// future coherent rebrand of the paired canonical (a tightening to
1967/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
1968/// per-cluster overlay the operator pins through a future
1969/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
1970/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1971/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
1972/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
1973/// roadmap lands) would have had to migrate the `MaxIntensity` half
1974/// through the lifted constant and the `Period` half through a raw
1975/// literal in lockstep or the two halves of the same OTP-canonical
1976/// default would silently drift out of pairing. Lifting the resolution
1977/// rule to a typed `pub const` on the substrate primitive means the
1978/// paired OTP-canonical default migrates as one unit on any future
1979/// axis change.
1980///
1981/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1982/// worker-supervisor default (the closest canonical OTP-shape
1983/// production reference the substrate carries, matching the paired
1984/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
1985/// constant is the `Period` denominator of on the same
1986/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
1987/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
1988/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
1989/// this lower default; both are typed [`Duration`] const bounds on the
1990/// `:supervisor :restart-window` axis and now share one accessor
1991/// discipline on the substrate) and above the OTP-`supervisor`
1992/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
1993/// rolling window" default is deliberately loose enough to absorb a
1994/// short burst of transient child failures without escalating past the
1995/// supervisor's parent while remaining tight enough for the paired
1996/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
1997/// stuck child within a human-scale observation window.
1998///
1999/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2000/// exactly one source of truth on each half — the sibling
2001/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
2002/// `Period` `60s` half now share the same substrate-primitive lift
2003/// discipline. Same shape every other typed default in this crate
2004/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
2005/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
2006/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
2007/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
2008/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
2009/// caixa-flux / caixa-helm rendering axes).
2010pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
2011
2012/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
2013/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
2014/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
2015/// worker-supervisor default, extracted as a typed `pub const` so every
2016/// substrate-side consumer that resolves "what
2017/// [`SupervisorSpec::estrategia`] variant does an author-omitted
2018/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
2019/// primitive [`RestartStrategy`].
2020///
2021/// The `:estrategia` default axis has three production consumers on the
2022/// substrate side today: the [`Default for RestartStrategy`] impl's
2023/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
2024/// `estrategia` field, and the
2025/// [`crate::manifest::Caixa::supervisor_view`] fold's
2026/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
2027/// collapse arm — three entry points onto the same OTP-canonical
2028/// `one_for_one` value that prior to this lift folded onto a raw
2029/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
2030/// implicit `RestartStrategy::default()` routes at the sibling consumers,
2031/// with no compile-time link back to the paired
2032/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
2033/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
2034/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
2035/// triple was split across three altitudes with no compile-time link
2036/// between the halves: the `MaxIntensity` half rode through the lifted
2037/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
2038/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2039/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
2040/// discriminator at the [`Default for RestartStrategy`] impl, so a future
2041/// coherent rebrand of the triple (Elixir's `{:one_for_one,
2042/// max_restarts: 3, max_seconds: 5}` — same strategy, different
2043/// intensity/period; an OTP `rest_for_one` widening once the substrate
2044/// discovers startup-order-coupled child cohorts as the more common
2045/// worker-supervisor default; a per-cluster overlay the operator pins
2046/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
2047/// §III.2 supervision-canary roadmap acknowledges) would have had to
2048/// migrate the `MaxIntensity` + `Period` halves through the lifted
2049/// constants and the `one_for_one` half through an open-coded arm in
2050/// lockstep or the three halves of the same OTP-canonical default would
2051/// silently drift out of pairing. Lifting the resolution rule to a typed
2052/// `pub const` on the substrate primitive means the paired OTP-canonical
2053/// worker-supervisor default migrates as one unit on any future axis
2054/// change.
2055///
2056/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
2057/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
2058/// closest canonical OTP-shape production reference the substrate
2059/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
2060/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2061/// `60s` `Period` half). The `one_for_one` strategy — restart only the
2062/// failed child, leaving siblings untouched — is the default for tree-of-
2063/// independent-workers use cases the substrate's [`RestartStrategy`]
2064/// discriminator's own docstring already carries as the default arm; it
2065/// composes with the `{5, 60}` restart-intensity ratio to name the same
2066/// substrate-canonical "canonical worker-supervisor" shape the paired
2067/// halves close on their respective axes.
2068///
2069/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2070/// exactly one source of truth on each of its three halves — the sibling
2071/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
2072/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
2073/// this `one_for_one` strategy half now share the same substrate-
2074/// primitive lift discipline. Same shape every other typed default in
2075/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
2076/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
2077/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
2078/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
2079/// upper caps on the paired sibling axes, and the peer
2080/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2081/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
2082pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
2083
2084/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
2085/// default for the `:children :restart` axis — the OTP `permanent`
2086/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
2087/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
2088/// `pub const` so every substrate-side consumer that resolves "what
2089/// [`ChildSpec::restart`] variant does an author-omitted `:children
2090/// :restart` slot degrade onto?" reaches for exactly one substrate-
2091/// primitive [`RestartPolicy`].
2092///
2093/// Completes the OTP-shape supervisor-tree default set at the substrate
2094/// primitive. The per-`:supervisor` axis already carries all three of its
2095/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2096/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
2097/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2098/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
2099/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
2100/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
2101/// the M2 `:supervisor` slot family. The split mattered because the two
2102/// axes resolve *together* on every author-omitted supervisor: a
2103/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
2104/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
2105/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
2106/// `permanent` through an open-coded enum arm, so a future coherent
2107/// rebrand of the OTP-shape default set (an Elixir-shaped
2108/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
2109/// per-cluster overlay the operator pins through the MESH-COMPOSITION
2110/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
2111/// once the substrate discovers clean-completion-aware children as the
2112/// more common child shape) would have had to migrate three halves
2113/// through typed constants and the fourth through a raw enum arm in
2114/// lockstep or the supervisor-level and child-level defaults would
2115/// silently drift apart.
2116///
2117/// The `:children :restart` default axis has two production consumers on
2118/// the substrate side today: the [`Default for RestartPolicy`] impl's
2119/// return arm, and the serde-side `#[serde(default)]` on
2120/// [`ChildSpec::restart`] that resolves an author-omitted `:children
2121/// :restart` slot through that same impl. Both now key off this one
2122/// substrate primitive, so the future wasm-operator's per-child post-exit
2123/// restart-decision branch, the future M4
2124/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2125/// admission webhook, and the `caixa-operator`'s hierarchical
2126/// reconciliation scheduler's per-child fan-out all reach for one typed
2127/// identifier when they resolve an omitted per-child restart posture.
2128///
2129/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
2130/// worker-child restart type — always restart the child regardless of how
2131/// it died, the canonical posture for long-running services that must
2132/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2133/// `one_for_one` tree-of-independent-workers strategy this constant pairs
2134/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
2135/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
2136/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
2137/// [`RestartPolicy::Temporary`] — never restart) express deliberate
2138/// one-shot / clean-completion-aware postures an author declares
2139/// explicitly, never a posture an omitted slot should silently assume.
2140pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
2141
2142/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
2143/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
2144/// `pub const fn` constructor rather than a struct-literal cascade over
2145/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
2146/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2147/// lifted consts — one source of truth for the Erlang/OTP-canonical
2148/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
2149/// paths every downstream consumer already reaches through (the
2150/// hand-authored-until-now [`Default::default`] the
2151/// `..SupervisorSpec::default()` struct-update-syntax on every
2152/// one-axis-under-test fixture in this crate's test module rests on,
2153/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
2154/// every `const`-context consumer reaches through).
2155///
2156/// Extends the [`Default`]-through-const-ctor fold discipline the
2157/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
2158/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
2159/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
2160/// and [`crate::BehaviorSpec`]
2161/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
2162/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
2163/// typed-slot spec family — extended here onto the M2 supervisor-slot
2164/// [`SupervisorSpec`] whose canonical baseline is not "everything
2165/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
2166/// supervisor triple. The `empty()` peer's naming did not fit
2167/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
2168/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
2169/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
2170/// the sibling `Option`-only slots fold to), so this peer is named
2171/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
2172/// existing per-arm pin tests
2173/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
2174/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
2175/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2176/// already reach for. Pinned load-bearing by
2177/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
2178/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
2179/// [`PartialEq`], sharpening the sibling
2180/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
2181/// pins from a per-field lift into a whole-struct one-source-of-truth
2182/// pin — the derived-until-now [`Default::default`] and the
2183/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
2184/// construction, not by coincidence).
2185impl Default for SupervisorSpec {
2186    #[inline]
2187    fn default() -> Self {
2188        Self::otp_canonical()
2189    }
2190}
2191
2192impl SupervisorSpec {
2193    /// `const`-context peer of the [`Default for SupervisorSpec`]
2194    /// impl (which routes through this constructor) — returns the
2195    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
2196    /// baseline this crate reaches for in every fixture-builder
2197    /// `..SupervisorSpec::default()` struct-update expression and
2198    /// every downstream `SupervisorSpec::default()` seed.
2199    ///
2200    /// Each field routes through the same substrate-canonical
2201    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
2202    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
2203    /// per-arm pin tests
2204    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
2205    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
2206    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2207    /// already assert, so a future coherent rebrand of the OTP-canonical
2208    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
2209    /// cluster overlay via a future `:restart-window-overrides` slot, a
2210    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
2211    /// absorption roadmap acknowledges) migrates through three typed
2212    /// constants in lockstep, and the paired [`Default`] impl inherits
2213    /// every future extension by construction.
2214    ///
2215    /// `pub const fn` rather than the derived-style `Default::default`
2216    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
2217    /// [`Default::default`] is not `const` on stable Rust, and
2218    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
2219    /// every consumer through a [`Clone::clone`]. The `pub const fn`
2220    /// discipline lets `const`-context callers construct the OTP-
2221    /// canonical baseline at compile time without runtime dispatch on
2222    /// the derived [`Default::default`], the same posture the sibling
2223    /// [`crate::LimitsSpec::empty`] (9739971) /
2224    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
2225    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
2226    /// spec `pub const fn` constructors carry on the sibling
2227    /// "everything `None`" baseline axis.
2228    ///
2229    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
2230    /// of the derived-style [`Default`]" family — sibling of the
2231    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
2232    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
2233    /// baseline" trio, extended here onto the M2 supervisor-slot
2234    /// [`SupervisorSpec`] whose canonical baseline is not "everything
2235    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
2236    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
2237    /// than `empty()` to name the actual invariant the return value
2238    /// pins — the same phrasing already used in the per-arm pin tests
2239    /// on this file. Pinned load-bearing by
2240    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
2241    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
2242    #[must_use]
2243    pub const fn otp_canonical() -> Self {
2244        Self {
2245            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
2246            max_restarts: default_max_restarts(),
2247            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2248            children: Vec::new(),
2249        }
2250    }
2251
2252    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
2253    /// sibling-restart-strategy scalar accessor every consumer that
2254    /// dispatches on the supervisor's per-sibling restart-decision shape
2255    /// keys off — returns the author-declared `:supervisor :estrategia`
2256    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
2257    /// the typed slot's own [`RestartStrategy`] storage.
2258    ///
2259    /// The `:supervisor :estrategia` slot carries the closed-set
2260    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
2261    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
2262    /// [`RestartStrategy::OneForAll`] — restart every child on any child
2263    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
2264    /// [`RestartStrategy::RestForOne`] — restart the failed child and
2265    /// every child started after it, the Erlang/OTP `rest_for_one`
2266    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
2267    /// dynamic children of the same shape, the Erlang/OTP
2268    /// `simple_one_for_one` per-session default) that every downstream
2269    /// consumer of the Supervisor's per-sibling restart-decision fan-out
2270    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
2271    /// paired coherently with the sibling `:children` axis
2272    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
2273    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
2274    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
2275    /// downstream consumer that reads the strategy keys off this scalar
2276    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2277    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
2278    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
2279    /// `estrategia:` field, the future `feira app graph` per-Supervisor
2280    /// strategy print line, the future wasm-operator's per-supervisor
2281    /// sibling-restart-strategy branch, the future M4
2282    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
2283    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
2284    /// reconciliation scheduler's per-strategy fan-out).
2285    ///
2286    /// Prior to this lift the `.estrategia` field was accessed inline at
2287    /// two production sites in `caixa-core/src/supervisor.rs` — the
2288    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2289    /// `match self.estrategia { … }` partition dispatch, and the
2290    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
2291    /// carrier at `estrategia: self.estrategia` — two open-coded
2292    /// field-accesses that expressed no compile-time link back to the
2293    /// typed slot. A future extension of the `:supervisor :estrategia`
2294    /// axis to a richer author surface (a per-cluster strategy override
2295    /// the operator pins through a future `:supervisor :estrategia-overrides`
2296    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2297    /// acknowledges, a per-tenant strategy-alias table the M4 CR
2298    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
2299    /// derivation the future adaptive-supervision engine computes from
2300    /// child-failure-history topology, a per-child-cohort strategy split
2301    /// the future `RestForCohort` extension acknowledged by the
2302    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
2303    /// would have had to be threaded through every open-coded copy in
2304    /// lockstep — one consumer reading the raw variant while a peer read
2305    /// the operator-resolved variant would silently split the
2306    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
2307    /// the actual partition-dispatch input the empty-children refusal
2308    /// arm reached under, a two-consumer split at the validator far from
2309    /// the source `caixa.lisp` with no field naming the strategy-drift
2310    /// root cause. Lifting the resolution rule to a typed method on the
2311    /// substrate primitive means every downstream consumer of the
2312    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
2313    /// reaches for exactly one typed dispatch — the resolver's accept-set
2314    /// migrates as a unit on any future axis addition.
2315    ///
2316    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
2317    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
2318    /// per-`:placement` distribution-strategy axis — same "one typed
2319    /// dispatch on the substrate primitive, thin projections at each
2320    /// consumer" discipline extended onto the M2 supervisor-slot
2321    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
2322    /// scalar axis. The two typed axes (`Placement::estrategia` on the
2323    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
2324    /// Supervisor side) now share one accessor discipline for the shared
2325    /// substrate concept "a `Copy`-projected closed-set enum-arm
2326    /// discriminator that partitions the downstream renderer's per-arm
2327    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
2328    /// `SupervisorSpec` type — companion to the sibling per-`:children`
2329    /// [`crate::ChildSpec::nome`] (57c61d0) /
2330    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2331    /// scalar accessors on the sibling per-`:children` `String`-carry
2332    /// axes. Named `estrategia()` to match the storage field's name and
2333    /// the peer [`crate::Placement::estrategia`] method-name discipline
2334    /// verbatim; the accessor's identity name maps onto the canonical
2335    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
2336    /// docstring already carries.
2337    ///
2338    /// Declared `pub const fn` to close the M2 supervisor-slot
2339    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
2340    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
2341    /// (converted in this commit) `Copy`-composite-enum accessor, peer
2342    /// of the sibling M2 per-`:supervisor`
2343    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2344    /// already lifted, and mirror of the peer M3 mesh-slot
2345    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
2346    /// `Copy`-return `pub const fn` scalar accessor whose method-name
2347    /// discipline this accessor was authored to match. Every downstream
2348    /// substrate-side `const`-context consumer of the per-`:supervisor`
2349    /// sibling-restart-strategy scalar (a future module-scope `const
2350    /// _:() = assert!(matches!(sup.estrategia(),
2351    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
2352    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2353    /// admission-webhook `const fn` per-supervisor strategy-arm floor
2354    /// over a typed [`SupervisorSpec`], any future `const fn`
2355    /// supervisor-tree composer over the substrate primitive that fans
2356    /// on the sibling-restart-strategy at compile time) now reaches
2357    /// through the same typed dispatch on the substrate primitive at
2358    /// const-eval time as at runtime. A future non-`Copy`-return
2359    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
2360    /// migration once the substrate grows per-cluster strategy overlays
2361    /// the [`SupervisorSpec`] docstring already anticipates, a
2362    /// per-tenant strategy-alias table the M4 CR materializer resolves
2363    /// per-CR) that would drop the `const` qualifier fails the
2364    /// fail-before-pass-after pin
2365    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
2366    /// caixa-core build time rather than surfacing as a downstream
2367    /// consumer regression.
2368    #[must_use]
2369    pub const fn estrategia(&self) -> RestartStrategy {
2370        self.estrategia
2371    }
2372
2373    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
2374    /// `MaxIntensity` restart-budget scalar accessor every consumer that
2375    /// reads the supervisor's per-`:restart-window` restart-budget count
2376    /// keys off — returns the author-declared `:supervisor :max-restarts`
2377    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
2378    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
2379    /// borrow of `&self` past the call). Non-optional (the `u32` field
2380    /// carries the restart-budget count as a required axis with a
2381    /// [`default_max_restarts`]-supplied default; the zero-floor arm
2382    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
2383    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
2384    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
2385    ///
2386    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
2387    /// `MaxIntensity` restart-budget count that pairs with the sibling
2388    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
2389    /// restart-intensity ratio the supervisor trips its own escalation on
2390    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
2391    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
2392    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
2393    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
2394    /// upper-cap bracket at
2395    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
2396    /// wasm-operator's per-supervisor restart-intensity counter's
2397    /// budget-vs-count comparator, the future M4
2398    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2399    /// webhook, the `caixa-operator`'s hierarchical reconciliation
2400    /// scheduler's per-supervisor escalation-decision branch, every
2401    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
2402    /// offending count verbatim for `feira lint` rendering).
2403    ///
2404    /// Prior to this lift the `.max_restarts` field was accessed inline at
2405    /// one production site in `caixa-core/src/supervisor.rs` — the
2406    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
2407    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
2408    /// that expressed no compile-time link back to the typed slot. A
2409    /// future extension of the `:max-restarts` axis to a richer author
2410    /// surface (a per-cluster restart-budget override the operator pins
2411    /// through a future `:supervisor :max-restarts-overrides` slot the
2412    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
2413    /// a per-tenant restart-budget-alias table the M4 CR materializer
2414    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
2415    /// the future adaptive-supervision engine computes from child-failure-
2416    /// history topology, a promotion of the plain `u32` count to a richer
2417    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
2418    /// budget-partition slot comes into scope) would have had to be
2419    /// threaded through every open-coded copy in lockstep or the validate
2420    /// gate and the future M4 emit path would silently disagree on which
2421    /// restart-budget count a given supervisor resolves to — an author's
2422    /// `:max-restarts 5` would satisfy validate while the emit path
2423    /// silently read a drifted other value (a `:max-restarts 10000`
2424    /// no-op supervisor at the emit boundary would carry the author's
2425    /// declared `5` verbatim in `feira lint` output while the future
2426    /// wasm-operator's restart-intensity counter operated under the
2427    /// drifted count), a two-consumer split at the validator far from the
2428    /// source `caixa.lisp` with no field naming the restart-budget-drift
2429    /// root cause. Lifting the resolution rule to a typed method on the
2430    /// substrate primitive means every downstream consumer of the
2431    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
2432    /// for exactly one typed dispatch — the resolver's accept-set migrates
2433    /// as a unit on any future axis addition.
2434    ///
2435    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
2436    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
2437    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
2438    /// outlier-detection trip-threshold axis — same "one typed dispatch on
2439    /// the substrate primitive, thin projections at each consumer"
2440    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
2441    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
2442    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
2443    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
2444    /// one accessor discipline for the shared substrate concept "a
2445    /// `Copy`-projected required `u32` count that trips the next-higher
2446    /// protection layer after N events in a rolling window" — both are
2447    /// counters with identical degenerate-at-the-high-end shape and share
2448    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
2449    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
2450    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
2451    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
2452    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
2453    /// the storage field's name verbatim and the peer
2454    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
2455    /// accessor's identity maps onto the canonical OTP-shape supervision
2456    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
2457    /// already carries.
2458    #[must_use]
2459    pub const fn max_restarts(&self) -> u32 {
2460        self.max_restarts
2461    }
2462
2463    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
2464    /// `Period` sliding-window scalar accessor every consumer of the
2465    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
2466    /// keys off — returns the author-declared `:supervisor :restart-window`
2467    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
2468    /// the typed slot's own `Option<Duration>` storage (`Duration` is
2469    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
2470    /// value; no borrow of `&self` past the call). `None` when the slot is
2471    /// absent (the canonical "never reset — every restart across the
2472    /// supervisor's lifetime counts against the sibling `:max-restarts`
2473    /// budget" sentinel the field's own docstring names and the peer
2474    /// `validate_accepts_none_restart_window` pin locks in on the
2475    /// [`SupervisorSpec::validate`] entry-side).
2476    ///
2477    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
2478    /// `Period` sliding-observation-interval that pairs with the sibling
2479    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
2480    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
2481    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
2482    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
2483    /// default). The typed slot's `Option<Duration>` accept-set —
2484    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
2485    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
2486    /// `Period > 0`; a zero period either trips on the first failure or
2487    /// never trips depending on operator interpretation, neither of which
2488    /// is the author's intent — omit the slot to express "no reset";
2489    /// carry a positive duration to express the sliding window),
2490    /// integer-millisecond canonical form enforced through
2491    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
2492    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
2493    /// future wasm-operator's per-supervisor restart-intensity counter
2494    /// quantizes at milliseconds), upper-bounded by
2495    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
2496    /// supervisor rolling window any operationally-reachable supervisor
2497    /// can honor without spanning multiple scheduler epochs the
2498    /// hierarchical-reconciliation scheduler treats as independent) —
2499    /// maps onto the future wasm-operator (M3) per-supervisor
2500    /// restart-intensity counter's rolling-observation-interval, the
2501    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2502    /// per-`spec.restartWindow` admission webhook, and the sibling
2503    /// `duration_codec`-serialized wire scalar every downstream consumer
2504    /// of the supervisor's per-`:supervisor` restart-intensity denominator
2505    /// keys off.
2506    ///
2507    /// Prior to this lift the `.restart_window` field was accessed inline
2508    /// at one production site in `caixa-core/src/supervisor.rs` — the
2509    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
2510    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
2511    /// open-coded field-access that expressed no compile-time link back to
2512    /// the typed slot. A future extension of the `:restart-window` axis to
2513    /// a richer author surface (a per-cluster restart-window override the
2514    /// operator pins through a future `:supervisor :restart-window-overrides`
2515    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2516    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
2517    /// materializer resolves per-CR, a per-supervisor dynamic
2518    /// restart-window derivation the future adaptive-supervision engine
2519    /// computes from child-failure-history topology, a promotion of the
2520    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
2521    /// pair once Erlang/OTP's per-child-cohort observation-interval-
2522    /// partition slot comes into scope) would have had to be threaded
2523    /// through every open-coded copy in lockstep or the validate gate and
2524    /// the future M4 emit path would silently disagree on which
2525    /// restart-window a given supervisor resolves to — an author's
2526    /// `:restart-window "60s"` would satisfy validate while the emit path
2527    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
2528    /// authored slot at the emit boundary would carry the author's
2529    /// declared window verbatim in `feira lint` output while the future
2530    /// wasm-operator's restart-intensity counter operated under a
2531    /// drifted window, or vice versa: an author's `:restart-window ()`
2532    /// would carry the "never reset" sentinel through validate while the
2533    /// emit path silently substituted a default sliding window), a
2534    /// two-consumer split at the validator far from the source
2535    /// `caixa.lisp` with no field naming the restart-window-drift root
2536    /// cause. Lifting the resolution rule to a typed method on the
2537    /// substrate primitive means every downstream consumer of the
2538    /// Supervisor's per-`:supervisor` restart-intensity-denominator
2539    /// surface reaches for exactly one typed dispatch — the resolver's
2540    /// accept-set migrates as a unit on any future axis addition.
2541    ///
2542    /// Third `Copy`-return accessor on the M2 supervisor-slot
2543    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
2544    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
2545    /// payload rather than a `Copy`-scalar, and the per-`:children`
2546    /// [`crate::ChildSpec::nome`] (57c61d0) /
2547    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2548    /// scalar accessors already close the per-element `String`-carry
2549    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
2550    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
2551    /// per-outermost-call wall-clock-deadline axis and the peer M3
2552    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
2553    /// accessor on the `:politicas` slot's per-call-deadline axis — all
2554    /// three share the shared substrate concept "a `Copy`-projected
2555    /// optional `Duration` that carries a positive integer-millisecond
2556    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
2557    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
2558    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
2559    /// bracket-helper the three axes each route through. Named
2560    /// `restart_window()` to match the storage field's name verbatim and
2561    /// the peer [`crate::LimitsSpec::wall_clock`] /
2562    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
2563    /// accessor's identity maps onto the canonical OTP-shape supervision
2564    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
2565    /// already carries.
2566    #[must_use]
2567    pub const fn restart_window(&self) -> Option<Duration> {
2568        self.restart_window
2569    }
2570
2571    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
2572    /// static-child-list slice accessor every consumer that walks the
2573    /// supervisor's declared child set keys off — returns the author-
2574    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
2575    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
2576    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
2577    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
2578    /// through). Non-optional: an empty slice is the load-bearing
2579    /// "author declared `:children ()`" sentinel every consumer of the
2580    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
2581    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
2582    /// three strategies require a non-empty slice — the paired
2583    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
2584    /// [`SupervisorError::NoChildren`] refusal cascade pins the
2585    /// partition on both arms).
2586    ///
2587    /// The `:supervisor :children` slot carries the OTP-shaped static
2588    /// child list the supervisor materializes one ComputeUnit per
2589    /// entry from — the Erlang/OTP `supervisor:init/1`'s
2590    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
2591    /// through the tatara-lisp `:children` author surface onto a typed
2592    /// `Vec<ChildSpec>` whose per-element `(nome(),
2593    /// versao_requirement(), restart)` triple the per-child
2594    /// [`SupervisorSpec::validate`] loop already gates through the
2595    /// lifted [`ChildSpec::nome`] (57c61d0) /
2596    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
2597    /// Every downstream consumer that fans on the static child list
2598    /// keys off this slice (the [`SupervisorSpec::validate`]
2599    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
2600    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
2601    /// per-child DNS-1123 / semver-requirement / duplicate-detection
2602    /// fan-out loop, every future wasm-operator (M3) per-supervisor
2603    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
2604    /// materialization loop, the future M4
2605    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2606    /// admission-webhook fan-out, the future `feira app graph`
2607    /// per-supervisor tree-print traversal).
2608    ///
2609    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
2610    /// inline at three production sites in `caixa-core/src/supervisor.rs`
2611    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
2612    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
2613    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
2614    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
2615    /// validate loop's `for child in &self.children` traversal head —
2616    /// three open-coded field-accesses that expressed no compile-time
2617    /// link back to the typed slot. A future extension of the
2618    /// `:supervisor :children` axis to a richer author surface (a
2619    /// per-cluster child-set overlay the operator pins through a future
2620    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
2621    /// supervision-canary roadmap acknowledges, a per-tenant
2622    /// child-set-alias table the M4 CR materializer resolves per-CR,
2623    /// a per-supervisor dynamic-child derivation the future adaptive-
2624    /// supervision engine computes from child-failure-history topology,
2625    /// a promotion of the plain `Vec<ChildSpec>` to a richer
2626    /// `{static, dynamic}` partition once Erlang/OTP's
2627    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
2628    /// would have had to be threaded through all three open-coded copies
2629    /// in lockstep or one consumer would silently disagree with the
2630    /// peers on which child-set a given supervisor resolves to — the
2631    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
2632    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
2633    /// would silently split the partition-dispatch's two-arm coherence
2634    /// (a supervisor that satisfies neither arm's precondition, or that
2635    /// satisfies both, at the cost of the paired
2636    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
2637    /// silently drifting from the per-child validate loop's actual
2638    /// traversal input), a three-consumer split at the validator far
2639    /// from the source `caixa.lisp` with no field naming the
2640    /// child-set-drift root cause. Lifting the resolution rule to a
2641    /// typed method on the substrate primitive means every downstream
2642    /// consumer of the Supervisor's per-`:supervisor` static-child-list
2643    /// surface reaches for exactly one typed dispatch — the resolver's
2644    /// accept-set migrates as a unit on any future axis addition.
2645    ///
2646    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
2647    /// — the seed for the same "one typed dispatch on the substrate
2648    /// primitive, thin projections at each consumer" discipline the
2649    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
2650    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
2651    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
2652    /// onto the first `Vec`-carry axis on the substrate. The four peer
2653    /// `Vec`-carry axes still unlifted at the time of this seed —
2654    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
2655    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
2656    /// (`Vec<Membro>` per-Aplicacao member list),
2657    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
2658    /// per-Aplicacao WIT-typed edge list),
2659    /// [`crate::UpgradeFromEntry::instructions`]
2660    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
2661    /// — inherit this accessor's discipline as future compounding runs
2662    /// migrate their consumers onto the shared slice-return shape.
2663    /// Fourth (and final) accessor on the M2 supervisor-slot
2664    /// `SupervisorSpec` type, sibling to the three `Copy`-return
2665    /// [`SupervisorSpec::estrategia`] (eafb619) /
2666    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
2667    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
2668    /// the last unlifted per-`:supervisor` field axis (the
2669    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
2670    /// per-`:supervisor` reader now routes through a typed dispatch on
2671    /// the substrate primitive. Named `children()` to match the storage
2672    /// field's name verbatim and the tatara-lisp author-surface term
2673    /// (`:children`) the field's own docstring already carries; the
2674    /// accessor's identity maps onto the canonical OTP-shape
2675    /// supervision vocabulary the [`SupervisorSpec::children`] field's
2676    /// docstring already reaches for ("Static children ..."). Returns
2677    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
2678    /// consumer of the child list treats it as a read-only sequence —
2679    /// the slice-view is the narrowest borrow that supports every
2680    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
2681    /// index, `.len()`) without leaking the backing `Vec`'s
2682    /// grow/push/reserve surface that no consumer of the typed view
2683    /// reaches for (the storage-side `Vec` remains reachable through
2684    /// the `pub children` field for the mutation-carrying
2685    /// `Caixa::supervisor_view` fold-in path in
2686    /// `manifest.rs:supervisor_view`).
2687    #[must_use]
2688    pub const fn children(&self) -> &[ChildSpec] {
2689        self.children.as_slice()
2690    }
2691
2692    /// Validate the supervisor's typed shape — strategy ↔ children
2693    /// invariants, max_restarts > 0, restart_window > 0 when set,
2694    /// per-child non-empty + duplicate-free names.
2695    ///
2696    /// Mirrors the value-shape discipline applied to every other
2697    /// typed slot:
2698    ///
2699    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
2700    ///     same "0 means the opposite of what you think" footgun
2701    ///     closed for `:politicas :timeout` (Envoy interprets a zero
2702    ///     timeout as `infinite`), `:politicas :circuit-breaker
2703    ///     :window`, and `:limits :wall-clock`. The
2704    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
2705    ///     `supervisor` requires `Period > 0`; a zero period either
2706    ///     trips on the first failure or never trips depending on
2707    ///     operator interpretation, neither of which is the
2708    ///     author's intent. Omit `:restart-window` to express "no
2709    ///     reset"; carry a positive duration to express the window.
2710    ///   - duplicate `:children` `:caixa` names are the same
2711    ///     graph-node-set / multiset distinction closed for
2712    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
2713    ///     and `:entrada :paths` (eb3456d). Two children with the
2714    ///     same `:caixa` materialize as two ComputeUnits with the
2715    ///     same name in the cluster's HelmRelease values, one
2716    ///     silently overwriting the other. Erlang/OTP's
2717    ///     `child_spec.id` is required-unique per supervisor;
2718    ///     pleme-io enforces the same set-not-multiset shape on
2719    ///     `:caixa` (the load-bearing identity in our renderer).
2720    pub fn validate(&self) -> Result<(), SupervisorError> {
2721        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
2722        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2723        // error carrier's `estrategia:` field through the lifted
2724        // [`SupervisorSpec::estrategia`] accessor rather than the raw
2725        // `self.estrategia` field access — the two production consumers
2726        // of the per-`:supervisor` sibling-restart-strategy scalar now
2727        // key off exactly one typed dispatch on the substrate primitive,
2728        // so any future rebrand on the axis (a per-cluster strategy
2729        // override the operator pins through a future `:supervisor
2730        // :estrategia-overrides` slot, a per-tenant strategy-alias table
2731        // the M4 CR materializer resolves per-CR) migrates as a single
2732        // caixa-core edit rather than a coordinated rewrite of the two
2733        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
2734        // (921fe1b) four-consumer migration on the per-`:placement`
2735        // distribution-strategy axis.
2736        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
2737        // dispatch's paired `.is_empty()` cross-slot refusal probes
2738        // (the `SimpleOneForOne`-arm
2739        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
2740        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2741        // refusal) through the lifted [`SupervisorSpec::children`]
2742        // slice-return accessor rather than the raw `self.children`
2743        // field access — the two paired production consumers of the
2744        // per-`:supervisor` static-child-list scalar-shape now key off
2745        // exactly one typed dispatch on the substrate primitive, so any
2746        // future rebrand on the axis (a per-cluster child-set overlay
2747        // the operator pins through a future `:supervisor
2748        // :children-overrides` slot, a per-tenant child-set-alias table
2749        // the M4 CR materializer resolves per-CR) migrates as a single
2750        // caixa-core edit rather than a coordinated rewrite of the
2751        // paired arms — first slice-return migration on any typed slot,
2752        // seed for the peer per-`:placement :clusters`,
2753        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
2754        // :instructions` `Vec`-carry axes.
2755        match self.estrategia() {
2756            RestartStrategy::SimpleOneForOne => {
2757                // SimpleOneForOne: children added at runtime. Static
2758                // list must be empty (one shape declared elsewhere).
2759                if !self.children().is_empty() {
2760                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
2761                }
2762            }
2763            _ => {
2764                if self.children().is_empty() {
2765                    return Err(SupervisorError::no_children(self.estrategia()));
2766                }
2767            }
2768        }
2769        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
2770        // axis. See [`crate::render::require_positive_bounded_u32`] for
2771        // the ordering discipline (zero-floor arm strictly precedes cap
2772        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
2773        // diagnostic with its counter-axis remediation directly named,
2774        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
2775        // cap-arm miss). Until this bracket landed the top edge ran all
2776        // the way to `u32::MAX` and a struct-literal
2777        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
2778        // equivalent author-surface `:max-restarts 100000` /
2779        // `:max-restarts 4294967295` typo landing in the slot) silently
2780        // passed validate. The runtime substrate consuming the value
2781        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
2782        // wasm-operator's per-supervisor restart-intensity counter, the
2783        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2784        // admission webhook) then turned a typed `:max-restarts`
2785        // policy into a no-op supervisor: the escalation threshold is
2786        // structurally so high that no realistic
2787        // restarts-per-`:restart-window` traffic shape can reach it,
2788        // the supervisor never escalates to its parent, and a bad
2789        // child can loop inside the window indefinitely with the
2790        // parent supervisor structurally never receiving the "this
2791        // subtree has exceeded its restart budget" signal the typed
2792        // slot is meant to express. The bracket set is
2793        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
2794        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
2795        // the sibling `:politicas :circuit-breaker :max-failures` axis:
2796        // both are "trip the next-higher protection layer after N
2797        // events in a rolling window" counters with identical
2798        // degenerate-at-the-high-end shape and now share one canonical
2799        // bracket helper. The bracket precedes the sibling
2800        // `:restart-window` zero-floor / canonical-millisecond arms so
2801        // an over-cap `max_restarts` paired with a structurally invalid
2802        // window surfaces the bracket diagnostic first, mirroring the
2803        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
2804        // ordering on the peer `:politicas :circuit-breaker` slot.
2805        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
2806        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
2807        // accessor rather than the raw `self.max_restarts` field access —
2808        // the one production consumer of the per-`:supervisor`
2809        // restart-budget-count scalar now keys off exactly one typed
2810        // dispatch on the substrate primitive, so any future rebrand on
2811        // the axis (a per-cluster restart-budget override the operator
2812        // pins through a future `:supervisor :max-restarts-overrides`
2813        // slot, a per-tenant restart-budget-alias table the M4 CR
2814        // materializer resolves per-CR) migrates as a single caixa-core
2815        // edit rather than a coordinated rewrite — sibling of the peer M3
2816        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
2817        // the per-`:politicas :circuit-breaker :max-failures` axis.
2818        crate::render::require_positive_bounded_u32(
2819            self.max_restarts(),
2820            SUPERVISOR_MAX_RESTARTS_MAX,
2821            || SupervisorError::ZeroMaxRestarts,
2822            SupervisorError::max_restarts_exceeds_cap,
2823        )?;
2824        // Route the [`SupervisorSpec::validate`] `:restart-window`
2825        // zero-floor + integer-millisecond canonical-form + upper-cap
2826        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
2827        // accessor rather than the raw `self.restart_window` field access —
2828        // the one production consumer of the per-`:supervisor`
2829        // restart-intensity-denominator scalar now keys off exactly one
2830        // typed dispatch on the substrate primitive, so any future rebrand
2831        // on the axis (a per-cluster restart-window override the operator
2832        // pins through a future `:supervisor :restart-window-overrides`
2833        // slot, a per-tenant restart-window-alias table the M4 CR
2834        // materializer resolves per-CR) migrates as a single caixa-core
2835        // edit rather than a coordinated rewrite — sibling of the peer M2
2836        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
2837        // on the per-`:limits :wall-clock` axis and the peer M3
2838        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
2839        // per-`:politicas :timeout` axis.
2840        if let Some(w) = self.restart_window() {
2841            // Zero-floor + integer-millisecond canonical-form +
2842            // upper-cap bracket on the typed `:restart-window` axis.
2843            // See
2844            // [`crate::render::require_positive_canonical_bounded_duration`]
2845            // for the full three-arm ordering discipline (zero-floor
2846            // strictly precedes canonical-form so `Duration::ZERO`
2847            // surfaces the self-locating `RestartWindowZero`
2848            // diagnostic; canonical-form strictly precedes the cap arm
2849            // so a sub-millisecond above-cap value surfaces the more
2850            // fundamental round-trip-shape diagnostic first) and the
2851            // three peer typed-`Duration` sites that share this
2852            // canonical bracket ([`crate::MeshPolicy::timeout`],
2853            // [`crate::CircuitBreaker::window`],
2854            // [`crate::LimitsSpec::wall_clock`]). Every validated
2855            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2856            // (1ms..=1h), integer-millisecond granularity.
2857            crate::render::require_positive_canonical_bounded_duration(
2858                w,
2859                SUPERVISOR_RESTART_WINDOW_MAX,
2860                || SupervisorError::RestartWindowZero,
2861                SupervisorError::restart_window_not_canonical,
2862                SupervisorError::restart_window_exceeds_cap,
2863            )?;
2864        }
2865        // Route the per-child DNS-1123 / semver-requirement / duplicate-
2866        // detection fan-out loop through the lifted named per-slot gate
2867        // [`SupervisorSpec::validate_children`] rather than an inline
2868        // three-per-child cascade — every future consumer that wants to
2869        // re-check only the `:children` slot's per-entry axes (the M4
2870        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2871        // admission webhook re-validating one added/renamed child, the
2872        // future wasm-operator's per-child dynamic-add re-validator on
2873        // the `SimpleOneForOne` runtime-add path once dynamic-children
2874        // graduate to a typed slot, a future partial re-validator on a
2875        // per-`:children`-entry patch) reaches every per-entry axis
2876        // through one dispatch rather than re-inlining the three-arm
2877        // cascade in lockstep with `validate` or paying the peer
2878        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
2879        // reach one entry check. Sibling of the peer M3 mesh-slot
2880        // per-slot gate family (`validate_membros` — the exact peer on
2881        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
2882        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
2883        // `validate_placement`; `validate_politicas` routing through
2884        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
2885        // per-slot gate discipline now spans both the M3 mesh-slot
2886        // family and the M2 `:children` per-child-cascade axis on one
2887        // shape: one named per-slot gate per typed per-entry loop.
2888        self.validate_children()?;
2889        Ok(())
2890    }
2891
2892    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
2893    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
2894    /// gate, and duplicate-`:caixa` dedup arm into one call every
2895    /// consumer that wants to re-validate one `:children` entry (or the
2896    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
2897    /// admits reaches through.
2898    ///
2899    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
2900    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
2901    /// three-per-entry shape (DNS-1123 name + semver-requirement +
2902    /// duplicate-`:caixa` dedup), lifted to one named substrate
2903    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2904    /// materializer's admission webhook re-checking one added or renamed
2905    /// child, the future wasm-operator's per-child dynamic-add
2906    /// re-validator on the `SimpleOneForOne` runtime-add path once
2907    /// dynamic-children graduate to a typed slot, a future partial
2908    /// re-validator on a per-`:children`-entry patch — each reaches the
2909    /// three per-entry axes through this one dispatch rather than
2910    /// re-inlining the three-arm cascade in lockstep with `validate`
2911    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
2912    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
2913    /// reach one entry check.
2914    ///
2915    /// Self-contained on `&self` — resolves its own dedup `HashSet`
2916    /// through [`SupervisorSpec::children`] rather than borrowing one
2917    /// threaded down from `validate`, the same posture the peer M3
2918    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
2919    /// [`crate::AplicacaoSpec::validate_contratos`],
2920    /// [`crate::AplicacaoSpec::validate_entrada`],
2921    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
2922    /// consumer that reaches this gate directly (without first calling
2923    /// `validate`) still runs the full per-child cascade — pinned by
2924    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2925    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2926    /// + `validate_children_is_self_contained_on_children_slot`.
2927    ///
2928    /// The three per-entry arms run in the same canonical order the
2929    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
2930    /// the diagnostic every author-declared per-`:children` entry surfaces
2931    /// through `validate` is byte-equal to the diagnostic this gate
2932    /// surfaces when called directly — the equivalence-pin pair
2933    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2934    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2935    /// asserts the two altitudes discriminate the same set on every
2936    /// per-entry-covered input.
2937    pub fn validate_children(&self) -> Result<(), SupervisorError> {
2938        let mut seen = std::collections::HashSet::new();
2939        for child in self.children() {
2940            // Every emitted cluster artifact's `metadata.name` for a
2941            // supervised child derives from this `:children :caixa` value
2942            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
2943            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
2944            // label value on every child's pod identity, and the per-
2945            // child K8s [`Service`][svc] `metadata.name` the future
2946            // wasm-operator (M3) provisions for inter-child supervision
2947            // tree wiring. Each apiserver-side schema on each landing
2948            // site enforces the DNS-1123 label rule on admission; a
2949            // structurally invalid child name (`"Worker"`, `"my_worker"`,
2950            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
2951            // UUID-shaped mistaken-identity slug) silently passes the
2952            // prior empty-/duplicate-only gate and the failure surfaces
2953            // at `kubectl apply` time as a `metadata.name: Invalid value`
2954            // rejection, far from the source caixa.lisp, with no field
2955            // naming the offending `:children` entry. Lifting the gate
2956            // to caixa-build time mirrors the `:membros :caixa` value-
2957            // shape trajectory (3f9d7a0) and the `:placement :clusters`
2958            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
2959            // identifier axis — the supervisor tree's child names —
2960            // through the lifted
2961            // [`crate::render::require_valid_dns_1123_label`] gate the
2962            // seven peer name axes (`:membros :caixa`, `:placement
2963            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
2964            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
2965            // route through, so drift between the eight axes' accepted
2966            // DNS-1123-label sets is structurally impossible.
2967            //
2968            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
2969            crate::render::require_valid_dns_1123_label(
2970                child.nome(),
2971                || SupervisorError::EmptyChildName,
2972                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
2973            )?;
2974            // The author surface for `:children :versao` is the same
2975            // Cargo-shaped semver requirement string `:deps :versao` and
2976            // `:membros :versao` carry — and the lacre pipeline resolves
2977            // all three axes through the same
2978            // [`crate::version::parse_requirement`] entry-point. The
2979            // shared [`crate::render::require_valid_versao_requirement`]
2980            // helper brackets the empty-first + parse cascade both peer
2981            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
2982            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
2983            // :versao`) route through, so drift between the three axes'
2984            // accepted requirement sets is structurally impossible and
2985            // the parse-side no-op the empty-first arm closes (semver's
2986            // empty parse yields an implicit `*`) lives in exactly one
2987            // predicate. Every `ChildSpec::versao` past validate is
2988            // round-trippable through [`crate::parse_requirement`]
2989            // without re-checking at the resolver layer, and the three
2990            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
2991            // are now structurally equivalent by construction.
2992            crate::render::require_valid_versao_requirement(
2993                child.versao_requirement(),
2994                || SupervisorError::empty_child_version(child.nome()),
2995                |reason| {
2996                    SupervisorError::child_versao_invalid(
2997                        child.nome(),
2998                        child.versao_requirement(),
2999                        reason,
3000                    )
3001                },
3002            )?;
3003            crate::render::insert_first_seen(&mut seen, child.nome(), || {
3004                SupervisorError::duplicate_child_caixa(child.nome())
3005            })?;
3006        }
3007        Ok(())
3008    }
3009}
3010
3011/// Cross-slot coherence gate on the supervision tree: no
3012/// `:children :caixa` entry may name the supervisor's own `:nome`.
3013///
3014/// A supervisor that lists itself as a child is a degenerate self-parent
3015/// — the supervision tree is a DAG rooted at the supervisor (OTP child
3016/// specs reference *distinct* child processes; a supervisor is never its
3017/// own child), and the wasm-operator's hierarchical reconciliation would
3018/// otherwise be handed a node that is its own parent: a one-node cycle it
3019/// either rejects far from the source `caixa.lisp` or recurses on. Because
3020/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
3021/// lacre closure root), a child whose `:caixa` equals the supervisor's
3022/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
3023///
3024/// Lives outside [`SupervisorSpec::validate`] because the typed view
3025/// carries the children but not the parent `:nome`; mirrors the
3026/// cross-slot precedence gate `validate_upgrade_from_against_versao`
3027/// (which likewise reads one slot against another at the
3028/// [`crate::layout`] wire-up site) and the mesh self-edge gate
3029/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
3030/// node to itself is structurally not a tree/mesh edge" discipline, here
3031/// on the supervision-tree axis.
3032pub fn validate_no_self_supervision(
3033    children: &[ChildSpec],
3034    parent_nome: &str,
3035) -> Result<(), SupervisorError> {
3036    for child in children {
3037        if child.nome() == parent_nome {
3038            return Err(SupervisorError::child_supervises_self(parent_nome));
3039        }
3040    }
3041    Ok(())
3042}
3043
3044#[derive(Debug, Error, PartialEq, Eq)]
3045pub enum SupervisorError {
3046    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
3047    NoChildren { estrategia: RestartStrategy },
3048    #[error(
3049        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
3050    )]
3051    SimpleOneForOneWithStaticChildren,
3052    #[error(":max-restarts must be > 0")]
3053    ZeroMaxRestarts,
3054    #[error(
3055        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
3056         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
3057         restart-intensity policy into a no-op supervisor: the escalation threshold is \
3058         structurally so high that no realistic restarts-per-:restart-window traffic shape \
3059         can reach it, so the supervisor never escalates to its parent and a bad child can \
3060         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
3061         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
3062         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3063         materializer's admission webhook) emits a `:max-restarts` declaration that is \
3064         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
3065         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
3066         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
3067         band) or restructure the supervision tree (split the flaky child into its own \
3068         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
3069    )]
3070    MaxRestartsExceedsCap { max_restarts: u32 },
3071    #[error(
3072        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
3073         requires Period > 0; a zero window either trips on the first failure or \
3074         never trips depending on operator interpretation. Omit :restart-window to \
3075         express `never reset`; carry a positive duration to express the window."
3076    )]
3077    RestartWindowZero,
3078    #[error(
3079        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
3080         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
3081         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
3082         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
3083         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
3084    )]
3085    RestartWindowNotCanonical { window: Duration },
3086    #[error(
3087        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
3088         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
3089         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
3090         failure-counting window is structurally so long that transient restarts are never \
3091         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
3092         when the child has exceeded its restart budget within the recent window` to `trip the \
3093         parent when the child has exceeded its restart budget over its lifetime`, and the \
3094         supervisor's reset semantic never reaches the child — every typed-slot consumer \
3095         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
3096         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3097         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
3098         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
3099         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
3100         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
3101         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
3102         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
3103         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
3104         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
3105         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
3106         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
3107         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
3108         hiding it behind a rolling-window declaration the cap arm rejects)"
3109    )]
3110    RestartWindowExceedsCap { window: Duration },
3111    #[error("child entry has empty :caixa name")]
3112    EmptyChildName,
3113    #[error(
3114        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
3115         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
3116         name / label value the child name lands in — the per-child \
3117         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
3118         label value, and the future wasm-operator per-child Service `metadata.name` \
3119         — each apiserver-side schema rejects names that don't match; use a \
3120         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
3121    )]
3122    ChildCaixaInvalid { caixa: String, reason: String },
3123    #[error("child {caixa:?} has empty :versao constraint")]
3124    EmptyChildVersion { caixa: String },
3125    #[error(
3126        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
3127         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
3128         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
3129         `:membros :versao` carry; the lacre pipeline resolves all three \
3130         through the same parser)"
3131    )]
3132    ChildVersaoInvalid {
3133        caixa: String,
3134        versao: String,
3135        reason: String,
3136    },
3137    #[error(
3138        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
3139         child_spec.id per supervisor; duplicate children materialize as duplicate \
3140         ComputeUnits in the rendered chart, one silently overwriting the other)"
3141    )]
3142    DuplicateChildCaixa { caixa: String },
3143    #[error(
3144        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
3145         never its own child (the supervision tree is a DAG rooted at the supervisor; \
3146         OTP child specs reference distinct child processes). Since every :nome is a \
3147         globally-unique substrate identity, a child naming the supervisor's own :nome \
3148         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
3149         self-referential :children entry or rename it to the actual child caixa."
3150    )]
3151    ChildSupervisesSelf { caixa: String },
3152}
3153
3154// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
3155// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
3156// and [`validate_no_self_supervision`] onto one substrate primitive per
3157// typed variant — the sibling on `SupervisorError` of the four uniform-shape
3158// `LayoutError`-envelope constructor families the peer
3159// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
3160// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
3161// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
3162// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
3163// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
3164// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
3165// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
3166// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
3167// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
3168// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
3169// variants on `{ de, para }`) already at that discipline on the peer
3170// `AplicacaoError` envelopes.
3171//
3172// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
3173// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
3174// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
3175// self-supervision arm) opened the identical
3176// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
3177// the exact "same block re-inlined at every consumer" shape the PRIME
3178// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
3179// `AplicacaoError` families each closed on their sibling envelopes. The
3180// three variants share one `{ caixa: String }` shape, so the fold routes
3181// each wire-up site through one dispatch per typed variant.
3182//
3183// The macro below generates one static constructor per variant of shape
3184// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
3185// collapses onto one dispatch:
3186// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
3187// struct-literal on the same `&str` fixture. The uniform one-field
3188// construction (`caixa: caixa.to_string()`) is spelled once — inside the
3189// macro — rather than at every wire-up site. Every constructor is
3190// `#[must_use]` so a caller who mistakenly discards the constructed error
3191// trips a compile warning at the wire-up site.
3192//
3193// Every future consumer that wants to construct one of these three
3194// variants outside `SupervisorSpec::validate_children` /
3195// `validate_no_self_supervision` — a deferred
3196// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3197// webhook re-checking one added/renamed child, a future
3198// `feira validate --supervisor` per-caixa admission verb, a per-child
3199// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
3200// once dynamic-children graduate to a typed slot, a per-Supervisor
3201// overlay resolver rejecting a duplicate/self-supervising child against
3202// a cluster-local snapshot — now reaches each variant through one call
3203// rather than re-inlining the three-line struct-literal in lockstep
3204// with the three in-crate wire-up sites.
3205macro_rules! supervisor_caixa_only_ctors {
3206    ($($ctor:ident => $variant:ident),* $(,)?) => {
3207        impl SupervisorError {
3208            $(
3209                #[doc = concat!(
3210                    "Construct a [`SupervisorError::",
3211                    stringify!($variant),
3212                    "`] naming the offending `:children :caixa` (or ",
3213                    "supervisor `:nome`, on the self-supervision arm). ",
3214                    "Folds the uniform `Self::",
3215                    stringify!($variant),
3216                    " { caixa: caixa.to_string() }` one-field ",
3217                    "struct-literal onto one substrate primitive so ",
3218                    "every [`SupervisorSpec::validate_children`] / ",
3219                    "[`validate_no_self_supervision`] wire-up on this ",
3220                    "variant reads through one dispatch rather than the ",
3221                    "pre-lift open-coded struct-literal block."
3222                )]
3223                #[must_use]
3224                pub fn $ctor(caixa: &str) -> Self {
3225                    Self::$variant { caixa: caixa.to_string() }
3226                }
3227            )*
3228        }
3229    };
3230}
3231
3232supervisor_caixa_only_ctors! {
3233    empty_child_version => EmptyChildVersion,
3234    duplicate_child_caixa => DuplicateChildCaixa,
3235    child_supervises_self => ChildSupervisesSelf,
3236}
3237
3238// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
3239// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
3240// one substrate primitive per typed variant — the M2 supervisor-side siblings
3241// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
3242// already lifted through the sibling
3243// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
3244// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
3245// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
3246// String }` two-slot shape the peer seven-variant
3247// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
3248// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
3249// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
3250// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
3251// variant carries the `{ caixa: String, versao: String, reason: String }`
3252// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
3253// carries on the same `:versao` value-shape.
3254//
3255// Each of the two wire-up sites opened the same closure-shaped
3256// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
3257// [versao: child.versao_requirement().to_string(),] reason }` block inside
3258// the paired [`crate::render::require_valid_dns_1123_label`] and
3259// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
3260// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
3261// as a bug, on the same altitude the peer `AplicacaoError` /
3262// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
3263// families already closed on their sibling envelopes.
3264//
3265// The two `#[must_use]` inherent constructors below fold each wire-up onto
3266// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
3267// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
3268// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
3269// The uniform per-field `.to_string()` / `.into()` construction is spelled
3270// once — inside each ctor body — rather than at every wire-up site. The
3271// `reason: impl Into<String>` bound accepts both `&str` literals and
3272// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
3273// diagnostic shape at the lift, matching the peer
3274// [`aplicacao_field_reason_ctors!`] and
3275// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
3276// sibling envelopes.
3277//
3278// Every future consumer that wants to construct one of these two variants
3279// outside `SupervisorSpec::validate_children` — a deferred
3280// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
3281// re-checking one added/renamed child's `:caixa` or `:versao`, a future
3282// `feira validate --supervisor` per-caixa admission verb, a per-child
3283// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
3284// dynamic-children graduate to a typed slot, a per-Supervisor overlay
3285// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
3286// cluster-local snapshot — now reaches each variant through one call rather
3287// than re-inlining the per-shape struct-literal block in lockstep with the
3288// two in-crate wire-up sites.
3289impl SupervisorError {
3290    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
3291    /// offending `:children :caixa` value under the given `reason`. Folds
3292    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
3293    /// reason: reason.into() }` two-slot struct-literal onto one substrate
3294    /// primitive so every wire-up on this variant reads through one
3295    /// dispatch, matching the peer
3296    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
3297    /// sibling `AplicacaoError { caixa: String, reason: String }`
3298    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
3299    /// outputs through the `impl Into<String>` bound.
3300    #[must_use]
3301    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
3302        Self::ChildCaixaInvalid {
3303            caixa: caixa.to_string(),
3304            reason: reason.into(),
3305        }
3306    }
3307
3308    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
3309    /// offending `:children :caixa` and its `:versao` requirement under
3310    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
3311    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
3312    /// reason.into() }` three-slot struct-literal onto one substrate
3313    /// primitive so every wire-up on this variant reads through one
3314    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
3315    /// { caixa, versao, reason }` three-slot axis on the peer
3316    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
3317    /// and `format!(…)` outputs through the `impl Into<String>` bound.
3318    #[must_use]
3319    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
3320        Self::ChildVersaoInvalid {
3321            caixa: caixa.to_string(),
3322            versao: versao.to_string(),
3323            reason: reason.into(),
3324        }
3325    }
3326}
3327
3328// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
3329// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
3330// three bracket-arms — one struct-literal at the `:children`-empty
3331// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
3332// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
3333// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
3334// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
3335// [`crate::render::require_positive_canonical_bounded_duration`]
3336// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
3337// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
3338// primitive per typed variant, matching the sibling
3339// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
3340// variants on the same `{ <field>: Duration | u32 }` shape) at that
3341// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
3342// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
3343// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
3344// wire-up site through one dispatch per typed variant without a runtime-
3345// work delta.
3346//
3347// Each of the four wire-up sites opened the identical
3348// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
3349// exact "same block re-inlined at every consumer" shape the PRIME
3350// DIRECTIVE names as a bug, on the same altitude the peer
3351// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
3352// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
3353// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
3354// the fold routes each wire-up site through one dispatch per typed
3355// variant.
3356//
3357// The macro below generates one static constructor per variant of shape
3358// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
3359// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
3360// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
3361// fixture — as a direct call at the [`SupervisorSpec::validate`]
3362// `:children`-empty refusal, or as a bare function pointer in the
3363// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
3364// [`crate::render::require_positive_bounded_u32`] /
3365// [`crate::render::require_positive_canonical_bounded_duration`] gate
3366// carries — rather than the pre-lift open-coded one-line closure over
3367// the same one-field struct-literal. `const fn` preserves the `Copy`-
3368// pass-through's zero-runtime-work property verbatim. Every constructor
3369// is `#[must_use]` so a caller who mistakenly discards the constructed
3370// error trips a compile warning at the wire-up site.
3371//
3372// Every future consumer that wants to construct one of these four
3373// variants outside `SupervisorSpec::validate` — a deferred
3374// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3375// webhook re-checking one edited `:estrategia` / `:max-restarts` /
3376// `:restart-window` slot against the cap + canonical-form cascade, a
3377// future `feira validate --supervisor` per-caixa admission verb re-
3378// running the shape gates on demand, a per-Supervisor overlay resolver
3379// rejecting an author-supplied slot against a cluster-local snapshot —
3380// now reaches each variant through one call rather than re-inlining the
3381// per-shape struct-literal block in lockstep with the four in-crate
3382// wire-up sites.
3383macro_rules! supervisor_scalar_ctors {
3384    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
3385        impl SupervisorError {
3386            $(
3387                #[doc = concat!(
3388                    "Construct a [`SupervisorError::",
3389                    stringify!($variant),
3390                    "`] naming the offending per-`:supervisor` `",
3391                    stringify!($field),
3392                    "` scalar. Folds the uniform `Self::",
3393                    stringify!($variant),
3394                    " { ",
3395                    stringify!($field),
3396                    " }` one-field `Copy`-pass-through struct-literal onto ",
3397                    "one substrate primitive so every per-axis wire-up on ",
3398                    "this variant reads through one dispatch — as a direct ",
3399                    "call (`SupervisorError::",
3400                    stringify!($ctor),
3401                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
3402                    "the same `Copy`-`",
3403                    stringify!($ty),
3404                    "` fixture) or as a bare function pointer in the ",
3405                    "`impl FnOnce(",
3406                    stringify!($ty),
3407                    ") -> SupervisorError` bracket-closure slot every ",
3408                    "`crate::render::require_positive_bounded_*` / ",
3409                    "`crate::render::require_positive_canonical_bounded_*` ",
3410                    "gate carries — rather than the pre-lift open-coded ",
3411                    "one-line closure over the same one-field struct-",
3412                    "literal. `const fn` preserves the `Copy`-pass-through's ",
3413                    "zero-runtime-work property verbatim."
3414                )]
3415                #[must_use]
3416                pub const fn $ctor($field: $ty) -> Self {
3417                    Self::$variant { $field }
3418                }
3419            )*
3420        }
3421    };
3422}
3423
3424supervisor_scalar_ctors! {
3425    no_children => NoChildren { estrategia: RestartStrategy },
3426    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
3427    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
3428    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
3429}
3430
3431/// Shared duration string codec for the typed slots that take a
3432/// duration (`restart_window`, `MeshPolicy::timeout`,
3433/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
3434/// reuse it without duplicating the parser.
3435pub mod duration_codec {
3436    use super::Duration;
3437    use serde::{Deserializer, Serializer};
3438
3439    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
3440        // Route through the canonical [`crate::render::serialize_option_via_str`]
3441        // — the substrate-side single-owner primitive for the forward
3442        // arm of the typed-magnitude codec family. See its docstring
3443        // for the full sibling roster.
3444        crate::render::serialize_option_via_str(v, s, render)
3445    }
3446
3447    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
3448        // Route through the canonical [`crate::render::deserialize_option_via_str`]
3449        // — the substrate-side single-owner primitive for the reverse
3450        // arm of the typed-magnitude codec family. See its docstring
3451        // for the full sibling roster.
3452        crate::render::deserialize_option_via_str(d, parse)
3453    }
3454
3455    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
3456        // Paired whitespace-rejection arm — same canonical-form
3457        // render-determinism discipline as the peer
3458        // `limits::parse_byte_size` / `limits::parse_duration` /
3459        // `limits::parse_millicores` /
3460        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
3461        // byte-scan closes the WhatWG-conformant whitespace bytes
3462        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
3463        // `char::is_whitespace` scan closes the strictly-complementary
3464        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
3465        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
3466        // codepoints) that `str::trim` at parse entry silently strips.
3467        // Either drift class would round-trip through `render` to a
3468        // *different* canonical form on next emit — breaking the
3469        // THEORY.md Part V render-determinism contract on three typed-
3470        // duration slots at once (`:supervisor :restart-window`,
3471        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
3472        // via the shared codec.
3473        //
3474        // Routed through the lifted [`crate::render::reject_whitespace`]
3475        // primitive — the substrate-side single-owner paired-arm gate
3476        // every typed-magnitude codec in caixa-core shares.
3477        crate::render::reject_whitespace::<String, _, _>(
3478            s,
3479            |b| {
3480                format!(
3481                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
3482                 authoring form for the typed duration slots routed through this shared codec \
3483                 (`:supervisor :restart-window`, `:politicas :timeout`, \
3484                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3485                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
3486                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
3487                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
3488                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
3489                 Part V render-determinism contract every typed slot carries. Strip every \
3490                 whitespace byte (write `\"30s\"` verbatim)"
3491                )
3492            },
3493            |ch| {
3494                format!(
3495                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
3496                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
3497                 duration slots routed through this shared codec (`:supervisor \
3498                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
3499                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
3500                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
3501                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
3502                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
3503                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
3504                 `White_Space` property, strictly wider than the ASCII byte set) silently \
3505                 strips it at parse entry, and the value round-trips through `render` to \
3506                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
3507                 the THEORY.md Part V render-determinism contract every typed slot \
3508                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
3509                 verbatim with only ASCII bytes)",
3510                    cp = ch as u32
3511                )
3512            },
3513        )?;
3514        let s = s.trim();
3515        // Routed through the lifted
3516        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
3517        // the single-owner split every ASCII-alphabetic-unit typed-
3518        // magnitude codec in caixa-core (`limits::parse_byte_size` /
3519        // `limits::parse_duration` / this shared duration codec) shares.
3520        // See its docstring for the full sibling roster on the same
3521        // primitive altitude.
3522        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
3523        let num_trim = num_part.trim();
3524        // The canonical authoring form for every typed slot routed
3525        // through this shared codec — `:supervisor :restart-window`,
3526        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
3527        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
3528        // non-negative integer with no decimal point and no leading
3529        // sign, so the parser's accepted set must match for
3530        // serialize/deserialize to round-trip without canonical-form
3531        // drift. Until this gate landed the parser accepted any
3532        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
3533        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
3534        // tripped the value to a *different* canonical string on the
3535        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
3536        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
3537        // — breaking the THEORY.md Part V render-determinism contract
3538        // on three typed slots at once. Same canonical-form discipline
3539        // `crate::limits::parse_duration` (818dd38, the immediate
3540        // predecessor on the peer `:limits :wall-clock` codec) applies;
3541        // this gate lifts the discipline onto the shared codec that
3542        // backs the remaining three typed-duration slots in caixa-core.
3543        //
3544        // Strict canonical form: every byte of the magnitude is an
3545        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
3546        // inputs the gate distinguishes "non-canonical-but-numeric"
3547        // (parses as f64 or i64 — surfaced with a self-locating
3548        // diagnostic naming the canonical authoring form, the
3549        // round-trip drift each rejected shape would produce on first
3550        // serialize, and the canonical-form remediation) from
3551        // "garbage" (parses as neither — surfaced with the existing
3552        // narrower "bad duration magnitude" wording so its diagnostic
3553        // shape remains stable for the parser-shape footgun case).
3554        // The pre-existing `num < 0.0` arm is now unreachable — the
3555        // digit-only gate strictly precedes magnitude parsing, and a
3556        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
3557        // non-canonical-but-numeric branch with the `-30` named
3558        // verbatim in the diagnostic rather than the prior
3559        // value-laundered "negative duration in \"-30s\"" wording.
3560        //
3561        // Routed through the lifted
3562        // [`crate::render::is_digit_only_magnitude`] predicate — the
3563        // same source of truth the four peer typed-magnitude codec
3564        // sites share.
3565        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
3566        if !digit_only {
3567            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
3568            if numeric {
3569                return Err(format!(
3570                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
3571                     canonical authoring form for the typed duration slots routed through \
3572                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3573                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3574                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
3575                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
3576                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
3577                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
3578                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
3579                     THEORY.md Part V render-determinism contract every typed slot carries. \
3580                     Pick an integer magnitude in the unit that divides cleanly (write \
3581                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
3582                ));
3583            }
3584            return Err(format!("bad duration magnitude in {s:?}"));
3585        }
3586        // Leading-zero arm — peer with the `rate_limit_codec` leading-
3587        // zero arm (4f46830) on the same canonical-form render-
3588        // determinism axis. The digit-only gate accepts `"030s"`,
3589        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
3590        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
3591        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
3592        // *different* canonical string on the next emit, breaking the
3593        // THEORY.md Part V render-determinism contract the same way
3594        // `"+30s"` did before the leading-`+` arm landed. The single-
3595        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
3596        // losslessly through `render` (`render(Duration::ZERO)` emits
3597        // `"0s"`) — the downstream semantic-zero gates (e.g.
3598        // `SupervisorError::ZeroRestartWindow` on
3599        // `:supervisor :restart-window`,
3600        // `AplicacaoError::PolicyTimeoutZero` /
3601        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
3602        // duration slots) refuse zero-magnitude authoring at the typed-
3603        // validate layer above, so the single-byte `"0"` stays in the
3604        // accepted set at this codec layer and the diagnostic
3605        // partitioning between canonical-form drift (this arm) and
3606        // semantic-zero (the downstream gates) remains stable.
3607        // Peer with the future leading-zero arms on the two remaining
3608        // typed-magnitude codecs the trajectory acknowledges:
3609        // `limits::parse_duration` backing `:limits :wall-clock`,
3610        // `limits::parse_byte_size` backing `:limits :memory` — each
3611        // carries the same canonical-form-drift class today; this
3612        // gate lands the discipline on the shared duration codec
3613        // first because the `rate_limit_codec` predecessor on the
3614        // same canonical-form-drift axis is the closest peer on the
3615        // trajectory.
3616        //
3617        // Routed through the lifted
3618        // [`crate::render::is_leading_zero_padded_magnitude`]
3619        // predicate — the same source of truth the four peer
3620        // typed-magnitude codec sites share.
3621        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
3622            return Err(format!(
3623                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
3624                 canonical authoring form for the typed duration slots routed through \
3625                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3626                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3627                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
3628                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
3629                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
3630                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
3631                 serialize — breaking the THEORY.md Part V render-determinism contract \
3632                 every typed slot carries. Strip the leading zeros (write \
3633                 `\"30s\"` instead of `\"030s\"`)"
3634            ));
3635        }
3636        // The digit-only gate guarantees every byte is `[0-9]`, and
3637        // the leading-zero arm above guarantees the magnitude is
3638        // either the single byte `"0"` or starts with `[1-9]`, so
3639        // the only way `u64::from_str` can fail here is overflow (the
3640        // magnitude exceeds `u64::MAX`). Surface that with an
3641        // overflow-shaped wording so the diagnostic names the offending
3642        // magnitude verbatim rather than collapsing onto the
3643        // non-canonical arm. The codec now operates on `u64` end-to-end
3644        // — every accepted magnitude is integer-exact; no f64 mantissa
3645        // drift between author-supplied magnitude and the consumer's
3646        // `Duration` value. Same shape `crate::limits::parse_duration`
3647        // (818dd38) carries on the peer `:limits :wall-clock` axis.
3648        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
3649            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
3650        })?;
3651        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
3652        // unit-arm dispatch through the canonical
3653        // [`crate::render::duration_from_integer_magnitude_and_unit`]
3654        // primitive — the substrate-side single-owner unit-dispatch
3655        // table every typed-duration codec in caixa-core routes
3656        // through (peer: `crate::limits::parse_duration` backing
3657        // `:limits :wall-clock`). Every unit conversion is integer-
3658        // exact for an integer magnitude; overflow surfaces via the
3659        // typed `DurationUnitError::Overflow { multiplier }`
3660        // discriminant so this arm reconstructs the pre-lift
3661        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
3662        // wording verbatim from `num` / `unit_trim` / the returned
3663        // `multiplier`, and the unknown-unit arm reconstructs the
3664        // pre-lift `"unknown duration unit \"<other>\""` wording from
3665        // the caller-scoped `unit_trim`. Load-bearing pinned by
3666        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
3667        let unit_trim = unit.trim();
3668        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
3669            |e| match e {
3670                crate::render::DurationUnitError::Overflow { multiplier } => format!(
3671                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
3672                ),
3673                crate::render::DurationUnitError::UnknownUnit => {
3674                    format!("unknown duration unit {unit_trim:?}")
3675                }
3676            },
3677        )?;
3678        Ok(dur)
3679    }
3680
3681    /// Render a [`Duration`] in the canonical pleme-io duration string
3682    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
3683    /// caixa typed-duration slot serializes to and the same form K8s
3684    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
3685    /// EnvoyConfig per-route timeouts both expect (an integer
3686    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
3687    /// `+`). Lifted to `pub` so caixa-side renderers
3688    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
3689    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
3690    /// emitter, the future caixa-otel collector pipeline emitter) can
3691    /// consume the same canonical formatter without re-inlining the
3692    /// magnitude/unit decision tree (and inheriting the same drift
3693    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
3694    /// downstream apply-time parsing in non-obvious ways).
3695    pub fn render(d: Duration) -> String {
3696        let total_ms = d.as_millis();
3697        if total_ms == 0 {
3698            return "0s".into();
3699        }
3700        if total_ms.is_multiple_of(3600 * 1000) {
3701            return format!("{}h", total_ms / (3600 * 1000));
3702        }
3703        if total_ms.is_multiple_of(60 * 1000) {
3704            return format!("{}m", total_ms / (60 * 1000));
3705        }
3706        if total_ms.is_multiple_of(1000) {
3707            return format!("{}s", total_ms / 1000);
3708        }
3709        format!("{total_ms}ms")
3710    }
3711
3712    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
3713    ///
3714    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
3715    /// largest divisor unit, so any sub-millisecond residue
3716    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
3717    /// §V.2.7 render-determinism contract:
3718    ///
3719    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
3720    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
3721    ///     `1_000_000` ns ≠ original `1_500_000` ns;
3722    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
3723    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
3724    ///     on every typed-`Duration` slot then rejects on re-validate.
3725    ///
3726    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
3727    /// the codec's round-trippable accepted set lives in exactly one place —
3728    /// every typed-`Duration` slot that routes through this shared codec
3729    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
3730    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
3731    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
3732    /// every typed-`Duration` slot whose own codec shares the same
3733    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
3734    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
3735    /// pair) calls this predicate from its `validate()` to bracket the
3736    /// accepted set against the codec's accepted set, structurally. Drift
3737    /// between the codec's granularity and any typed slot's accepted set is
3738    /// then a single-source-of-truth edit at this predicate rather than a
3739    /// silent round-trip break the next consumer discovers at apply time.
3740    ///
3741    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
3742    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
3743    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
3744    /// family — same "typed-slot's valid set matches its codec's accepted
3745    /// set, structurally" discipline carried at the codec layer.
3746    #[must_use]
3747    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
3748        d.subsec_nanos().is_multiple_of(1_000_000)
3749    }
3750}
3751
3752/// Required-Duration variant for fields that aren't Option<Duration>.
3753pub mod duration_codec_required {
3754    use super::Duration;
3755    use serde::{Deserialize, Deserializer, Serializer};
3756
3757    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
3758        s.serialize_str(&super::duration_codec::render(*v))
3759    }
3760
3761    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
3762        let s = String::deserialize(d)?;
3763        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
3764    }
3765}
3766
3767#[cfg(test)]
3768mod tests {
3769    use super::*;
3770
3771    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
3772        ChildSpec {
3773            caixa: name.into(),
3774            versao: ver.into(),
3775            restart,
3776        }
3777    }
3778
3779    #[test]
3780    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
3781        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
3782        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
3783        // posture. Each accessor projects the per-`:children :caixa`
3784        // / per-`:children :versao` [`String`] storage through the
3785        // `pub const fn` [`String::as_str`] (const-stable since Rust
3786        // 1.87, well within the workspace MSRV) — any future
3787        // accidental downgrade to non-`const` fails the corresponding
3788        // `<name>_via_const_fn` wrapper at caixa-core build time with
3789        // E0015 (`cannot call non-const method`), strictly stronger
3790        // than a runtime `assert!`. Sibling of the peer
3791        // per-M2/M3/universal-axis `String → &str` scalar-accessor
3792        // family pins on the sibling `const`-eval-surface passes
3793        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
3794        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
3795        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
3796        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
3797        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
3798        // [`crate::aplicacao::Entrada::destination`] at the M3
3799        // ingress axis,
3800        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
3801        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
3802        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
3803        // axis, and the per-`:contratos`
3804        // [`crate::aplicacao::WitContract::source`] /
3805        // [`crate::aplicacao::WitContract::destination`] /
3806        // [`crate::aplicacao::WitContract::world_ref`] trio the
3807        // sibling pin at 279823b already anchors).
3808        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
3809            c.nome()
3810        }
3811        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
3812            c.versao_requirement()
3813        }
3814        for (caixa, versao) in [
3815            ("worker-a", "^0.1"),
3816            ("worker-b", "~0.2.3"),
3817            ("collector", "*"),
3818        ] {
3819            let c = child(caixa, versao, RestartPolicy::Permanent);
3820            assert_eq!(nome_via_const_fn(&c), c.nome());
3821            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
3822            assert_eq!(c.nome(), caixa);
3823            assert_eq!(c.versao_requirement(), versao);
3824        }
3825    }
3826
3827    #[test]
3828    fn supervisor_children_slice_return_accessor_is_const_fn() {
3829        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
3830        // `const`-eval-surface posture. The accessor destructures the
3831        // per-`:children` `Vec<ChildSpec>` storage through the
3832        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
3833        // 1.66, well within the workspace MSRV) — any future
3834        // accidental downgrade to non-`const` fails
3835        // `children_via_const_fn` at caixa-core build time with E0015
3836        // (`cannot call non-const method`), strictly stronger than a
3837        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
3838        // `Vec → &[T]` slice-return accessor family pin
3839        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
3840        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
3841        // per-`:membros` / per-`:contratos` slice-return axes, and of
3842        // the peer M2 upgrade-appup axis pin
3843        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
3844        // on the per-`:upgrade-from :instructions` slice-return axis.
3845        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
3846            s.children()
3847        }
3848        // Sweep both the empty-children (leaf-supervisor with no
3849        // static children — the `SimpleOneForOne` dynamic-child
3850        // arm's canonical shape) and the populated-children
3851        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
3852        // arm's canonical shape) axes so the accessor carries a
3853        // const-dispatch pin on both arms.
3854        let s_empty = SupervisorSpec {
3855            estrategia: RestartStrategy::SimpleOneForOne,
3856            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3857            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3858            children: vec![],
3859        };
3860        assert!(children_via_const_fn(&s_empty).is_empty());
3861        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
3862        let s_full = SupervisorSpec {
3863            estrategia: RestartStrategy::OneForOne,
3864            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3865            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3866            children: vec![
3867                child("worker-a", "^0.1", RestartPolicy::Permanent),
3868                child("worker-b", "~0.2.3", RestartPolicy::Transient),
3869                child("collector", "*", RestartPolicy::Temporary),
3870            ],
3871        };
3872        assert_eq!(children_via_const_fn(&s_full).len(), 3);
3873        assert_eq!(children_via_const_fn(&s_full), s_full.children());
3874    }
3875
3876    #[test]
3877    fn default_has_one_for_one_and_5_restarts_in_60s() {
3878        let s = SupervisorSpec::default();
3879        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
3880        assert_eq!(s.max_restarts, 5);
3881        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
3882        assert!(s.children.is_empty());
3883    }
3884
3885    #[test]
3886    fn validate_one_for_one_requires_children() {
3887        let mut s = SupervisorSpec::default();
3888        s.children = vec![];
3889        assert!(matches!(
3890            s.validate().unwrap_err(),
3891            SupervisorError::NoChildren { .. }
3892        ));
3893        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
3894        s.validate().unwrap();
3895    }
3896
3897    #[test]
3898    fn validate_simple_one_for_one_forbids_static_children() {
3899        let mut s = SupervisorSpec {
3900            estrategia: RestartStrategy::SimpleOneForOne,
3901            ..SupervisorSpec::default()
3902        };
3903        s.children
3904            .push(child("w", "^0.1", RestartPolicy::Permanent));
3905        assert_eq!(
3906            s.validate().unwrap_err(),
3907            SupervisorError::SimpleOneForOneWithStaticChildren
3908        );
3909        s.children.clear();
3910        s.validate().unwrap();
3911    }
3912
3913    #[test]
3914    fn validate_rejects_zero_max_restarts() {
3915        let s = SupervisorSpec {
3916            max_restarts: 0,
3917            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3918            ..SupervisorSpec::default()
3919        };
3920        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
3921    }
3922
3923    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
3924    //
3925    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
3926    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
3927    // `:supervisor :max-restarts` axis — both fields are "trip the
3928    // next-higher protection layer after N events in a rolling window"
3929    // counters with identical degenerate-at-the-high-end shape, so the
3930    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
3931    // exactly as it lies in `1..=1000` on the breaker side.
3932
3933    #[test]
3934    fn validate_rejects_max_restarts_above_cap() {
3935        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
3936        // 1` is structurally one past the cap and silently passed
3937        // validate on every pre-gate codebase because the typed slot's
3938        // only check was the zero-floor arm. The no-op-supervisor vector
3939        // only surfaced at the runtime substrate (Erlang/OTP
3940        // MaxIntensity/Period ratio, the future wasm-operator's
3941        // per-supervisor restart-intensity counter) far from the source
3942        // caixa.lisp with no field naming the offending supervisor.
3943        let s = SupervisorSpec {
3944            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3945            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3946            ..SupervisorSpec::default()
3947        };
3948        assert_eq!(
3949            s.validate().unwrap_err(),
3950            SupervisorError::MaxRestartsExceedsCap {
3951                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3952            }
3953        );
3954    }
3955
3956    #[test]
3957    fn validate_rejects_max_restarts_far_above_cap() {
3958        // The `u32::MAX` worst case — the four-billion-restart
3959        // threshold a typo (`:max-restarts 4294967295`) or a
3960        // struct-literal copy-paste lands in the slot. Pin the cap
3961        // arm's coverage explicitly across the full `u32` overflow so
3962        // a future relaxation that drops the upper bound surfaces
3963        // here. Same shape every other typed-cap arm on this surface
3964        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
3965        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
3966        let s = SupervisorSpec {
3967            max_restarts: u32::MAX,
3968            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3969            ..SupervisorSpec::default()
3970        };
3971        assert_eq!(
3972            s.validate().unwrap_err(),
3973            SupervisorError::MaxRestartsExceedsCap {
3974                max_restarts: u32::MAX,
3975            }
3976        );
3977    }
3978
3979    #[test]
3980    fn validate_accepts_max_restarts_at_cap() {
3981        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
3982        // must validate. The cap is inclusive on the top edge,
3983        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
3984        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
3985        // discipline on the sibling capped axes. Pin the boundary
3986        // explicitly so a future off-by-one tightening
3987        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
3988        // here as a test failure rather than a silent contract
3989        // narrowing.
3990        let s = SupervisorSpec {
3991            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
3992            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3993            ..SupervisorSpec::default()
3994        };
3995        s.validate()
3996            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
3997    }
3998
3999    #[test]
4000    fn validate_accepts_max_restarts_typical_values() {
4001        // The documented production-playbook band positive-control
4002        // sweep — every value Erlang/OTP / Elixir / Riak Core /
4003        // RabbitMQ recommend (1..=100) must pass, plus a sweep
4004        // through the hyperscale band (200, 500, 1000) the cap
4005        // accepts. Pin the inclusive validated set explicitly so a
4006        // future tightening of the ceiling surfaces here.
4007        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
4008            let s = SupervisorSpec {
4009                max_restarts: n,
4010                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4011                ..SupervisorSpec::default()
4012            };
4013            s.validate()
4014                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
4015        }
4016    }
4017
4018    #[test]
4019    fn zero_max_restarts_takes_precedence_over_cap() {
4020        // The cross-arm ordering pin: `0` is structurally outside
4021        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
4022        // (cap), but the zero-floor diagnostic is the more
4023        // self-locating one (it directly names the counter-axis
4024        // remediation), so the validate gate must fire on zero first.
4025        // Same shape every other zero-then-shape ordering on this
4026        // surface uses (PolicyRetriesZero then
4027        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
4028        // PolicyBreakerMaxFailuresExceedsCap).
4029        let s = SupervisorSpec {
4030            max_restarts: 0,
4031            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4032            ..SupervisorSpec::default()
4033        };
4034        assert_eq!(
4035            s.validate().unwrap_err(),
4036            SupervisorError::ZeroMaxRestarts,
4037            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
4038        );
4039    }
4040
4041    #[test]
4042    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
4043        // The cross-arm ordering pin between the cap and the sibling
4044        // `:restart-window` gates (zero-window, canonical-window). A
4045        // supervisor carrying both an over-cap `max_restarts` AND a
4046        // structurally invalid window (zero, sub-ms) must surface the
4047        // cap diagnostic first — the cap arm is wired immediately
4048        // after the zero-restart arm and strictly before the window
4049        // arms, so the offending value the diagnostic names matches
4050        // the order the author would discover the gates by reading
4051        // top-to-bottom through `SupervisorSpec::validate`. Pin the
4052        // order so a future refactor that reorders the arms surfaces
4053        // here as a test failure rather than a silent diagnostic
4054        // regression. Peer of
4055        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
4056        // on the sibling `:politicas :circuit-breaker` slot.
4057        let s = SupervisorSpec {
4058            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4059            restart_window: Some(Duration::ZERO),
4060            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4061            ..SupervisorSpec::default()
4062        };
4063        assert_eq!(
4064            s.validate().unwrap_err(),
4065            SupervisorError::MaxRestartsExceedsCap {
4066                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4067            },
4068            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4069        );
4070    }
4071
4072    #[test]
4073    fn max_restarts_cap_diagnostic_carries_offending_value() {
4074        // The diagnostic-shape pin: the offending `u32` is carried
4075        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
4076        // variant so the surfaced error message names the value the
4077        // author wrote (`":supervisor :max-restarts (50000) exceeds the
4078        // supervisor-policy ceiling …"`), not just the cap. Same
4079        // self-locating diagnostic shape every other typed-cap arm on
4080        // this surface carries
4081        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
4082        // the offending failure count verbatim,
4083        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
4084        // retries count verbatim).
4085        let s = SupervisorSpec {
4086            max_restarts: 50_000,
4087            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4088            ..SupervisorSpec::default()
4089        };
4090        let err = s.validate().unwrap_err();
4091        assert!(
4092            matches!(
4093                err,
4094                SupervisorError::MaxRestartsExceedsCap {
4095                    max_restarts: 50_000
4096                }
4097            ),
4098            "got {err:?}"
4099        );
4100        let msg = err.to_string();
4101        assert!(
4102            msg.contains("50000"),
4103            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
4104        );
4105    }
4106
4107    #[test]
4108    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
4109        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
4110        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
4111        // half of Learn You Some Erlang's worker-supervisor default,
4112        // sibling of the `60s` `Period` half that the paired
4113        // [`Default for SupervisorSpec`] impl already pins on the
4114        // sibling `restart_window` axis. Pinning the literal here
4115        // surfaces a future rebrand (a tightening to Elixir's `3`,
4116        // a widening to a per-cluster overlay the operator pins
4117        // through a future `:max-restarts-overrides` slot) as a
4118        // deliberate test edit, not a silent contract migration.
4119        // Peer of the sibling
4120        // [`supervisor_max_restarts_cap_pins_canonical_value`]
4121        // upper-bracket pin on the same axis.
4122        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
4123    }
4124
4125    #[test]
4126    fn default_max_restarts_helper_routes_through_lifted_default() {
4127        // Composition pin: the private `default_max_restarts()`
4128        // serde-`#[serde(default = "…")]` helper on
4129        // [`SupervisorSpec::max_restarts`] must route through the
4130        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4131        // typed `pub const` rather than a raw `5` literal. Prior to
4132        // the lift the helper carried an inline `5` with no compile-
4133        // time link back to the shared default, so the wire-format
4134        // author-omitted arm and the caixa-core
4135        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
4136        // arm could silently split on any future default rebrand.
4137        // Byte-parity against the lifted constant closes the split.
4138        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
4139    }
4140
4141    #[test]
4142    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
4143        // Composition pin: the [`Default for SupervisorSpec`] impl's
4144        // struct-literal `max_restarts` field must route through the
4145        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4146        // typed `pub const` (via the private helper this test's
4147        // sibling `default_max_restarts_helper_routes_through_lifted_default`
4148        // already pins onto the constant). Structurally: every
4149        // `SupervisorSpec::default()` call must yield a
4150        // `max_restarts` field byte-equal to the lifted constant
4151        // (the two paired defaults — the serde-side wire-format arm
4152        // and the struct-literal default arm — cannot silently split
4153        // on any future default rebrand). Peer of the sibling
4154        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
4155        // — this pin closes the byte-parity arm on the two paired
4156        // altitude entry points onto the shared substrate constant.
4157        assert_eq!(
4158            SupervisorSpec::default().max_restarts(),
4159            SUPERVISOR_MAX_RESTARTS_DEFAULT,
4160        );
4161    }
4162
4163    #[test]
4164    fn supervisor_restart_window_default_pins_otp_canonical_value() {
4165        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
4166        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
4167        // Learn You Some Erlang's worker-supervisor default, paired
4168        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
4169        // `MaxIntensity` half this constant is the sliding-window
4170        // denominator of on the same `MaxIntensity / Period`
4171        // restart-intensity ratio. Pinning the literal here surfaces a
4172        // future coherent rebrand of the paired default (Elixir's
4173        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
4174        // the operator pins through a future
4175        // `:restart-window-overrides` slot) as a deliberate test edit,
4176        // not a silent contract migration. Peer of the sibling
4177        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
4178        // paired-half pin on the same OTP-canonical default and the
4179        // [`supervisor_restart_window_cap_pins_canonical_value`]
4180        // upper-bracket pin on the same axis.
4181        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
4182    }
4183
4184    #[test]
4185    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
4186        // Composition pin: the [`Default for SupervisorSpec`] impl's
4187        // struct-literal `restart_window` field must route through the
4188        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4189        // typed `pub const` rather than a raw
4190        // `Duration::from_secs(60)` literal. Prior to this lift the
4191        // paired `{intensity, 5, 60}` OTP-canonical default was split
4192        // across two altitudes with no compile-time link between the
4193        // halves — the `MaxIntensity` half rode through the lifted
4194        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
4195        // `Period` half rode as an open-coded literal at the
4196        // composition site, so a future coherent rebrand of the paired
4197        // canonical would have had to migrate one half through the
4198        // constant and the other through a raw literal in lockstep.
4199        // Byte-parity against the lifted constant on the `Period` half
4200        // closes the split — the paired OTP-canonical default now
4201        // migrates as one unit on any future axis change. Peer of the
4202        // sibling
4203        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4204        // byte-parity pin on the paired `MaxIntensity` half.
4205        assert_eq!(
4206            SupervisorSpec::default().restart_window(),
4207            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4208        );
4209    }
4210
4211    #[test]
4212    fn supervisor_estrategia_default_pins_otp_canonical_value() {
4213        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
4214        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
4215        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
4216        // canonical default, paired with the sibling
4217        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
4218        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
4219        // this constant is the strategy discriminator of on the same
4220        // OTP-canonical worker-supervisor default. Pinning the arm here
4221        // surfaces a future coherent rebrand of the paired triple (Elixir's
4222        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
4223        // intensity/period axes leaving this strategy arm untouched, an OTP
4224        // `rest_for_one` widening once the substrate discovers startup-
4225        // order-coupled child cohorts as the more common worker-supervisor
4226        // shape, a per-cluster overlay the operator pins through a future
4227        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
4228        // supervision-canary roadmap acknowledges) as a deliberate test
4229        // edit, not a silent contract migration. Peer of the sibling
4230        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
4231        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4232        // paired-half pins on the same OTP-canonical default.
4233        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
4234    }
4235
4236    #[test]
4237    fn restart_strategy_default_routes_through_lifted_default() {
4238        // Composition pin: the [`Default for RestartStrategy`] impl's
4239        // return arm must route through the substrate-canonical
4240        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
4241        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
4242        // an inline `Self::OneForOne` with no compile-time link back to
4243        // the shared OTP-canonical `one_for_one` strategy the paired
4244        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
4245        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
4246        // `.unwrap_or_default()` (now
4247        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
4248        // so a future rebrand of the OTP-canonical strategy default (an
4249        // OTP `rest_for_one` widening once the substrate discovers
4250        // startup-order-coupled child cohorts as the more common worker-
4251        // supervisor shape, a per-cluster overlay the operator pins
4252        // through a future `:estrategia-overrides` slot) would have had to
4253        // be threaded through the `Default` impl and the two peer routes
4254        // in lockstep or the three consumers would silently split. Byte-
4255        // parity against the lifted constant closes the split. Peer of
4256        // the sibling
4257        // [`default_max_restarts_helper_routes_through_lifted_default`] +
4258        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4259        // composition pins on the paired `MaxIntensity` + `Period` halves.
4260        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
4261    }
4262
4263    #[test]
4264    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
4265        // Composition pin: the [`Default for SupervisorSpec`] impl's
4266        // struct-literal `estrategia` field must route through the
4267        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
4268        // `pub const` (either directly, or via the
4269        // [`RestartStrategy::default`] impl that the sibling
4270        // `restart_strategy_default_routes_through_lifted_default` pin
4271        // already routes onto the constant). Structurally: every
4272        // `SupervisorSpec::default()` call must yield an `estrategia`
4273        // field byte-equal to the lifted constant (the three paired
4274        // defaults — the [`Default for RestartStrategy`] impl arm, the
4275        // struct-literal default arm here, and the
4276        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
4277        // silently split on any future default rebrand). Peer of the
4278        // sibling
4279        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4280        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4281        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
4282        // of the same `SupervisorSpec::default()` composed altitude.
4283        assert_eq!(
4284            SupervisorSpec::default().estrategia(),
4285            SUPERVISOR_ESTRATEGIA_DEFAULT,
4286        );
4287    }
4288
4289    #[test]
4290    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
4291        // Composition pin: the [`Default for SupervisorSpec`] impl must
4292        // route through the substrate-canonical
4293        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
4294        // rather than a re-hand-authored struct-literal cascade. Sharpens
4295        // the sibling per-arm
4296        // `supervisor_spec_default_*_routes_through_lifted_default` pins
4297        // from a per-field lift into a whole-struct one-source-of-truth
4298        // pin — the derived-until-now [`Default::default`] and the
4299        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
4300        // construction, not by coincidence.
4301        //
4302        // A future extension of the OTP-canonical baseline (a fifth
4303        // `restart_intensity` field the Erlang/OTP `#supervisor` record
4304        // grows, a per-child-cohort split of the `restart_window` /
4305        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
4306        // CR materializer's admission-time overlay pass) reaches both
4307        // paths through exactly one edit on
4308        // [`SupervisorSpec::otp_canonical`] — the derived path could
4309        // silently disagree with the constructor's shape on any new
4310        // field whose [`Default::default`] resolves to a different arm
4311        // than the OTP-canonical baseline the constructor names, while
4312        // this delegated impl reaches the constructor directly and
4313        // picks up every future extension by construction.
4314        //
4315        // Fourth peer on the M2 / M3 typed-slot-spec
4316        // [`Default`]-through-const-ctor fold family — sibling of the
4317        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
4318        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
4319        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
4320        // (91641a4), and [`crate::BehaviorSpec`]
4321        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
4322        // per-`Option`-only-typed-slot folds — extended here onto the
4323        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
4324        // is not "everything `None`" but the Erlang/OTP-canonical
4325        // `{one_for_one, 5, 60}` worker-supervisor triple.
4326        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
4327    }
4328
4329    #[test]
4330    fn supervisor_spec_otp_canonical_byte_equals_default() {
4331        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
4332        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
4333        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
4334        // pin already asserts against the [`Default::default`] path.
4335        // Sharpens the pair-invariant into a per-constructor pin so a
4336        // future extension of [`SupervisorSpec`] with a fifth field
4337        // whose OTP-canonical shape is non-`Default::default`-equivalent
4338        // trips at caixa-core test time rather than at a downstream
4339        // consumer that composed [`SupervisorSpec::otp_canonical`] with
4340        // [`SupervisorSpec::validate`] as its "canonical baseline
4341        // seed".
4342        let canonical = SupervisorSpec::otp_canonical();
4343        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
4344        assert_eq!(canonical.max_restarts, 5);
4345        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
4346        assert!(canonical.children.is_empty());
4347    }
4348
4349    #[test]
4350    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
4351        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
4352        // remain callable from a `const`-bound position so downstream
4353        // `const`-context callers wanting a canonical OTP-baseline seed
4354        // can construct one at compile time without runtime dispatch on
4355        // the derived [`Default::default`]. Peer of the sibling
4356        // `pub const fn` [`crate::LimitsSpec::empty`] /
4357        // [`crate::aplicacao::MeshPolicy::empty`] /
4358        // [`crate::BehaviorSpec::empty`] constructors on the sibling
4359        // typed-slot-spec `pub const fn` axis. If a future edit breaks
4360        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
4361        // (a non-`const` field-default helper, a non-`const`-stable
4362        // container type promotion), this evaluation fails at
4363        // build time on this file rather than at a downstream
4364        // `const`-context call site.
4365        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
4366        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
4367        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
4368        assert_eq!(
4369            CANONICAL.restart_window,
4370            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4371        );
4372        assert!(CANONICAL.children.is_empty());
4373    }
4374
4375    #[test]
4376    fn supervisor_child_restart_default_pins_otp_canonical_value() {
4377        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
4378        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
4379        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
4380        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
4381        // half of the same OTP-shape supervisor-tree default set whose
4382        // per-`:supervisor` halves the sibling
4383        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
4384        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
4385        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
4386        // arm here surfaces a future rebrand of the per-child default (an
4387        // OTP-`transient` widening once the substrate discovers clean-
4388        // completion-aware children as the more common child shape, a
4389        // per-cluster overlay the operator pins through a future
4390        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
4391        // supervision-canary roadmap acknowledges) as a deliberate test
4392        // edit, not a silent contract migration. Peer of the sibling
4393        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
4394        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
4395        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4396        // value pins on the per-`:supervisor` halves.
4397        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
4398    }
4399
4400    #[test]
4401    fn restart_policy_default_routes_through_lifted_default() {
4402        // Composition pin: the [`Default for RestartPolicy`] impl's return
4403        // arm must route through the substrate-canonical
4404        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
4405        // than a raw `Self::Permanent` arm. Prior to the lift the impl
4406        // carried an inline `Self::Permanent` with no compile-time link
4407        // back to the OTP-shape supervisor-tree default set whose three
4408        // per-`:supervisor` halves already rode through lifted constants
4409        // — so a future coherent rebrand of the set would have had to
4410        // migrate three halves through typed constants and this fourth
4411        // through a raw enum arm in lockstep or the supervisor-level and
4412        // child-level defaults would silently drift apart. Byte-parity
4413        // against the lifted constant closes the split. Peer of the
4414        // sibling
4415        // [`restart_strategy_default_routes_through_lifted_default`]
4416        // composition pin on the per-`:supervisor` `:estrategia` axis.
4417        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
4418    }
4419
4420    #[test]
4421    fn child_spec_serde_default_restart_routes_through_lifted_default() {
4422        // Composition pin: the serde-side `#[serde(default)]` on
4423        // [`ChildSpec::restart`] — the wire-format author-omitted
4424        // `:children :restart` arm — must resolve onto the substrate-
4425        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
4426        // (via the [`Default for RestartPolicy`] impl the sibling
4427        // `restart_policy_default_routes_through_lifted_default` pin
4428        // already routes onto the constant). Structurally: a `ChildSpec`
4429        // deserialized from a payload that omits the `restart` key must
4430        // yield a `restart` field byte-equal to the lifted constant, so
4431        // the wire-format author-omitted arm and the
4432        // [`RestartPolicy::default`] impl arm cannot silently split on any
4433        // future default rebrand. Peer of the sibling
4434        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
4435        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4436        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4437        // byte-parity pins on the per-`:supervisor` halves of the same
4438        // author-omitted-slot resolution surface.
4439        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
4440            .expect("ChildSpec must deserialize with the restart key omitted");
4441        assert_eq!(
4442            omitted.restart(),
4443            SUPERVISOR_CHILD_RESTART_DEFAULT,
4444            "an author-omitted :children :restart slot must degrade onto \
4445             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
4446             {:?}, expected {:?})",
4447            omitted.restart(),
4448            SUPERVISOR_CHILD_RESTART_DEFAULT,
4449        );
4450    }
4451
4452    #[test]
4453    fn supervisor_max_restarts_cap_pins_canonical_value() {
4454        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
4455        // 1000 — the same ceiling the peer
4456        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
4457        // `:politicas :circuit-breaker :max-failures` axis (both are
4458        // "trip the next-higher protection layer after N events in a
4459        // rolling window" counters with identical
4460        // degenerate-at-the-high-end shape; uniform top edge so the
4461        // M4 CR materializers and the wasm-operator reconciler reach
4462        // for either field knowing the value is in `1..=1000`). Two
4463        // orders of magnitude above every documented Erlang/OTP /
4464        // Elixir / Riak Core / RabbitMQ production-playbook
4465        // recommendation band and below the clearly-pathological
4466        // "effectively no escalation" floor (10_000, 100_000,
4467        // u32::MAX). Pinning the literal value here surfaces a future
4468        // drift (a relaxation to 10_000, a tightening to 100) as a
4469        // deliberate test edit, not a silent contract narrowing.
4470        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
4471    }
4472
4473    #[test]
4474    fn validate_rejects_empty_child_name() {
4475        let s = SupervisorSpec {
4476            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4477            ..SupervisorSpec::default()
4478        };
4479        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
4480    }
4481
4482    #[test]
4483    fn validate_rejects_empty_child_version() {
4484        let s = SupervisorSpec {
4485            children: vec![child("w", "", RestartPolicy::Permanent)],
4486            ..SupervisorSpec::default()
4487        };
4488        assert!(matches!(
4489            s.validate().unwrap_err(),
4490            SupervisorError::EmptyChildVersion { .. }
4491        ));
4492    }
4493
4494    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
4495
4496    #[test]
4497    fn validate_rejects_invalid_child_versao_requirement() {
4498        // The fail-before-pass-after pin: a non-empty but malformed
4499        // semver requirement (`"^bad-version"`) silently passed
4500        // `validate()` on every pre-gate codebase because the prior
4501        // shape only refused the empty string. The parse failure
4502        // surfaced far downstream at lacre-resolve time with a
4503        // `semver::Error` that didn't name which `:children` entry
4504        // carried the typo. The new gate moves the check to caixa-build
4505        // time at the source caixa.lisp — the third `:versao` typed
4506        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
4507        // structural parity.
4508        let s = SupervisorSpec {
4509            children: vec![
4510                child("worker", "^0.1", RestartPolicy::Permanent),
4511                child("cache", "^bad-version", RestartPolicy::Transient),
4512            ],
4513            ..SupervisorSpec::default()
4514        };
4515        let err = s.validate().unwrap_err();
4516        assert!(
4517            matches!(
4518                err,
4519                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4520                    if caixa == "cache" && versao == "^bad-version"
4521            ),
4522            "got {err:?}"
4523        );
4524    }
4525
4526    #[test]
4527    fn validate_rejects_child_versao_with_double_caret_typo() {
4528        // `"^^0.1"` is the canonical doubled-caret typo — looks
4529        // Cargo-shaped on first glance but fails the parser because
4530        // semver doesn't accept stacked operators. Pin this
4531        // adjacent-shape footgun explicitly so a future relaxation that
4532        // accepts "looks-canonical-but-isn't" forms surfaces here.
4533        let s = SupervisorSpec {
4534            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
4535            ..SupervisorSpec::default()
4536        };
4537        let err = s.validate().unwrap_err();
4538        assert!(
4539            matches!(
4540                err,
4541                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4542                    if caixa == "worker" && versao == "^^0.1"
4543            ),
4544            "got {err:?}"
4545        );
4546    }
4547
4548    #[test]
4549    fn validate_rejects_child_versao_with_v_prefixed_tag() {
4550        // `"v0.1"` is the canonical "git-tag-shape leaking into the
4551        // semver requirement slot" typo — an author copies the
4552        // publish-side git-tag string verbatim into `:versao`, but
4553        // Cargo's semver parser rejects the leading `v`. Same
4554        // adjacent-shape footgun pinned for `:membros :versao`
4555        // (9888b13).
4556        let s = SupervisorSpec {
4557            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
4558            ..SupervisorSpec::default()
4559        };
4560        let err = s.validate().unwrap_err();
4561        assert!(
4562            matches!(
4563                err,
4564                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4565                    if caixa == "worker" && versao == "v0.1"
4566            ),
4567            "got {err:?}"
4568        );
4569    }
4570
4571    #[test]
4572    fn validate_accepts_canonical_child_versao_forms() {
4573        // The Cargo-shaped requirement forms `:deps :versao` and
4574        // `:membros :versao` already accept via
4575        // `crate::parse_requirement` must pass the children gate
4576        // without re-validating at the resolver layer. Pin every leg so
4577        // a future tightening of the canonical set surfaces here as a
4578        // test failure.
4579        for form in [
4580            "^0.1",      // caret — minor-range pin (the most common shape)
4581            "~0.1.2",    // tilde — patch-range pin
4582            "0.1.0",     // exact — single-version pin
4583            "*",         // wildcard — any version (semver::VersionReq::STAR)
4584            ">=0.1, <2", // multi-range — comma-separated comparators
4585        ] {
4586            let s = SupervisorSpec {
4587                children: vec![child("worker", form, RestartPolicy::Permanent)],
4588                ..SupervisorSpec::default()
4589            };
4590            s.validate()
4591                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4592        }
4593    }
4594
4595    #[test]
4596    fn child_versao_empty_takes_precedence_over_invalid() {
4597        // Order pin: the existing `EmptyChildVersion` diagnostic (which
4598        // doesn't try to parse) fires before the new
4599        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
4600        // `:versao` keeps its narrower error message —
4601        // `parse_requirement` would also reject `""`, but the
4602        // empty-string arm is the more self-locating diagnostic for the
4603        // author. Same ordering discipline as
4604        // `membro_versao_empty_takes_precedence_over_invalid` in
4605        // aplicacao.rs.
4606        let s = SupervisorSpec {
4607            children: vec![child("worker", "", RestartPolicy::Permanent)],
4608            ..SupervisorSpec::default()
4609        };
4610        let err = s.validate().unwrap_err();
4611        assert!(
4612            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
4613            "got {err:?}"
4614        );
4615    }
4616
4617    #[test]
4618    fn child_versao_invalid_fires_before_duplicate_check() {
4619        // Order pin: a malformed requirement on a non-duplicate entry
4620        // surfaces *its own* diagnostic (which names the offending
4621        // `:versao` string), even when a later entry would otherwise
4622        // collapse onto an earlier name. The per-entry shape gate runs
4623        // inline before the duplicate-key insert — parallel to
4624        // `membro_versao_invalid_fires_before_duplicate_check` in
4625        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
4626        let s = SupervisorSpec {
4627            children: vec![
4628                child("worker", "^bad", RestartPolicy::Permanent),
4629                child("cache", "^0.1", RestartPolicy::Transient),
4630                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4631            ],
4632            ..SupervisorSpec::default()
4633        };
4634        let err = s.validate().unwrap_err();
4635        assert!(
4636            matches!(
4637                err,
4638                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
4639            ),
4640            "got {err:?}"
4641        );
4642    }
4643
4644    #[test]
4645    fn child_versao_invalid_diagnostic_carries_offending_versao() {
4646        // The diagnostic-shape pin: the error names the offending
4647        // `:versao` value verbatim so the author can grep their
4648        // caixa.lisp without re-running the build, and carries a
4649        // non-empty `reason` from `semver::VersionReq::parse` so the
4650        // parser's own wording flows through to the diagnostic.
4651        let s = SupervisorSpec {
4652            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
4653            ..SupervisorSpec::default()
4654        };
4655        let err = s.validate().unwrap_err();
4656        let SupervisorError::ChildVersaoInvalid {
4657            caixa,
4658            versao,
4659            reason,
4660        } = err
4661        else {
4662            panic!("expected ChildVersaoInvalid, got other variant");
4663        };
4664        assert_eq!(caixa, "worker");
4665        assert_eq!(versao, "not-a-req");
4666        assert!(
4667            !reason.is_empty(),
4668            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
4669        );
4670    }
4671
4672    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
4673
4674    #[test]
4675    fn validate_rejects_child_caixa_with_uppercase() {
4676        // The canonical "I copied the Servico's display name verbatim"
4677        // typo — child caixa names are lowercase per K8s DNS-1123 label
4678        // rule. The diagnostic names the offending name and suggests the
4679        // lower-cased fix in one edit, mirroring the
4680        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
4681        let s = SupervisorSpec {
4682            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
4683            ..SupervisorSpec::default()
4684        };
4685        let err = s.validate().unwrap_err();
4686        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4687            panic!("expected ChildCaixaInvalid, got other variant");
4688        };
4689        assert_eq!(caixa, "Worker");
4690        assert!(
4691            reason.contains("uppercase"),
4692            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
4693        );
4694        assert!(
4695            reason.contains("\"worker\""),
4696            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
4697        );
4698    }
4699
4700    #[test]
4701    fn validate_rejects_child_caixa_with_underscore() {
4702        // The canonical "I'm thinking of a Python module / Postgres
4703        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
4704        // label schema. K8s rejects `metadata.name: my_worker` at
4705        // admission time with an opaque `field is invalid` (no source-
4706        // citing diagnostic). The gate moves it to caixa-build time.
4707        let s = SupervisorSpec {
4708            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
4709            ..SupervisorSpec::default()
4710        };
4711        let err = s.validate().unwrap_err();
4712        assert!(
4713            matches!(
4714                err,
4715                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4716                    if caixa == "my_worker" && reason.contains('_')
4717            ),
4718            "got {err:?}"
4719        );
4720    }
4721
4722    #[test]
4723    fn validate_rejects_child_caixa_with_dot() {
4724        // A `:children :caixa` entry is a single DNS-1123 label, not a
4725        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
4726        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
4727        // (3f9d7a0) on the peer name axis.
4728        let s = SupervisorSpec {
4729            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
4730            ..SupervisorSpec::default()
4731        };
4732        let err = s.validate().unwrap_err();
4733        assert!(
4734            matches!(
4735                err,
4736                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4737                    if caixa == "team.worker" && reason.contains('.')
4738            ),
4739            "got {err:?}"
4740        );
4741    }
4742
4743    #[test]
4744    fn validate_rejects_child_caixa_with_leading_hyphen() {
4745        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
4746        // with an alphanumeric. The K8s apiserver rejects `-worker`
4747        // outright; the renderer would emit a `metadata.name: "-worker"`
4748        // that fails admission far from the source caixa.lisp.
4749        let s = SupervisorSpec {
4750            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
4751            ..SupervisorSpec::default()
4752        };
4753        let err = s.validate().unwrap_err();
4754        assert!(
4755            matches!(
4756                err,
4757                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4758                    if caixa == "-worker" && reason.contains("start and end")
4759            ),
4760            "got {err:?}"
4761        );
4762    }
4763
4764    #[test]
4765    fn validate_rejects_child_caixa_with_trailing_hyphen() {
4766        // The symmetric arm of the boundary rule. Pin separately so
4767        // both ends of the label are covered against a future relaxation
4768        // that only checks one boundary.
4769        let s = SupervisorSpec {
4770            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
4771            ..SupervisorSpec::default()
4772        };
4773        let err = s.validate().unwrap_err();
4774        assert!(
4775            matches!(
4776                err,
4777                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4778                    if caixa == "worker-"
4779            ),
4780            "got {err:?}"
4781        );
4782    }
4783
4784    #[test]
4785    fn validate_rejects_child_caixa_with_unicode() {
4786        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
4787        // (`xn--…`) by the author before it reaches K8s. The byte-by-
4788        // byte ASCII validity check rejects multi-byte UTF-8 sequences
4789        // by the first byte that fails the `[a-z0-9-]` predicate.
4790        let s = SupervisorSpec {
4791            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
4792            ..SupervisorSpec::default()
4793        };
4794        let err = s.validate().unwrap_err();
4795        assert!(
4796            matches!(
4797                err,
4798                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4799                    if caixa == "café"
4800            ),
4801            "got {err:?}"
4802        );
4803    }
4804
4805    #[test]
4806    fn validate_rejects_child_caixa_with_whitespace() {
4807        // Whitespace is the canonical "I pasted from a sketch / doc"
4808        // footgun. The apiserver rejects every `metadata.name` value
4809        // carrying whitespace; pin the gate fires at the right boundary.
4810        let s = SupervisorSpec {
4811            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
4812            ..SupervisorSpec::default()
4813        };
4814        let err = s.validate().unwrap_err();
4815        assert!(
4816            matches!(
4817                err,
4818                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4819                    if caixa == "my worker"
4820            ),
4821            "got {err:?}"
4822        );
4823    }
4824
4825    #[test]
4826    fn validate_rejects_child_caixa_too_long() {
4827        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
4828        // 63 bytes; the K8s apiserver rejects every `metadata.name`
4829        // axis over the limit at admission time. The diagnostic names
4830        // both the cap and the actual length so the author can shorten
4831        // in one edit, mirroring `rejects_membro_caixa_too_long`
4832        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
4833        let too_long = "a".repeat(64);
4834        let s = SupervisorSpec {
4835            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
4836            ..SupervisorSpec::default()
4837        };
4838        let err = s.validate().unwrap_err();
4839        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4840            panic!("expected ChildCaixaInvalid, got other variant");
4841        };
4842        assert_eq!(caixa, too_long);
4843        assert!(
4844            reason.contains("63"),
4845            "diagnostic must name the 63-byte cap (got: {reason:?})"
4846        );
4847        assert!(
4848            reason.contains("64"),
4849            "diagnostic must name the actual length (got: {reason:?})"
4850        );
4851    }
4852
4853    #[test]
4854    fn child_caixa_max_length_validates() {
4855        // The 63-byte boundary control pin — exactly-at-the-cap is
4856        // accepted, mirroring `membro_caixa_max_length_validates`
4857        // (3f9d7a0) and `placement_cluster_max_length_validates`
4858        // (6cbb900). Pinned separately so a future off-by-one tightening
4859        // surfaces here.
4860        let max_label = "a".repeat(63);
4861        let s = SupervisorSpec {
4862            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
4863            ..SupervisorSpec::default()
4864        };
4865        s.validate().unwrap();
4866    }
4867
4868    #[test]
4869    fn validate_accepts_canonical_child_caixa_forms() {
4870        // The realistic shapes a supervised child's `:caixa` carries —
4871        // single-word `worker`, version-suffixed `cache-v2`, single-char
4872        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
4873        // `payment-retry`, all-digit `0`. Pin every leg so a future
4874        // tightening (e.g. requiring a leading lowercase letter) surfaces
4875        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
4876        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
4877        // (6cbb900).
4878        for form in [
4879            "worker",
4880            "cache-v2",
4881            "a",
4882            "db",
4883            "2-pool",
4884            "payment-retry",
4885            "0",
4886        ] {
4887            let s = SupervisorSpec {
4888                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
4889                ..SupervisorSpec::default()
4890            };
4891            s.validate()
4892                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4893        }
4894    }
4895
4896    #[test]
4897    fn child_caixa_empty_takes_precedence_over_invalid() {
4898        // Order pin: the existing `EmptyChildName` diagnostic (which
4899        // doesn't try to parse the DNS-1123 shape) fires before the new
4900        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
4901        // its narrower error message — `is_dns_1123_label` would reject
4902        // the empty string too (boundary check on the first byte), but
4903        // the empty-string arm is the more self-locating diagnostic for
4904        // the author. Same ordering discipline as
4905        // `membro_caixa_empty_takes_precedence_over_invalid` in
4906        // aplicacao.rs.
4907        let s = SupervisorSpec {
4908            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4909            ..SupervisorSpec::default()
4910        };
4911        let err = s.validate().unwrap_err();
4912        assert_eq!(err, SupervisorError::EmptyChildName);
4913    }
4914
4915    #[test]
4916    fn child_caixa_invalid_fires_before_versao_check() {
4917        // Order pin: the per-axis shape gate runs inline before the
4918        // per-entry versao check, so a malformed `:caixa` on an entry
4919        // whose `:versao` would also fail surfaces the more self-
4920        // locating name-axis diagnostic first. Parallel to
4921        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
4922        // and `placement_cluster_invalid_fires_before_duplicate_check`
4923        // (6cbb900).
4924        let s = SupervisorSpec {
4925            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
4926            ..SupervisorSpec::default()
4927        };
4928        let err = s.validate().unwrap_err();
4929        assert!(
4930            matches!(
4931                err,
4932                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
4933            ),
4934            "got {err:?}"
4935        );
4936    }
4937
4938    #[test]
4939    fn child_caixa_invalid_fires_before_duplicate_check() {
4940        // Order pin: a malformed name on a non-duplicate entry surfaces
4941        // its own diagnostic, even when a later entry would otherwise
4942        // collapse onto an earlier name. The per-entry shape gate runs
4943        // inline before the duplicate-key HashSet insert, mirroring
4944        // `placement_cluster_invalid_fires_before_duplicate_check`
4945        // (6cbb900).
4946        let s = SupervisorSpec {
4947            children: vec![
4948                child("Worker", "^0.1", RestartPolicy::Permanent),
4949                child("cache", "^0.1", RestartPolicy::Transient),
4950                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4951            ],
4952            ..SupervisorSpec::default()
4953        };
4954        let err = s.validate().unwrap_err();
4955        assert!(
4956            matches!(
4957                err,
4958                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
4959            ),
4960            "got {err:?}"
4961        );
4962    }
4963
4964    #[test]
4965    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
4966        // The diagnostic-shape pin: the error names the offending
4967        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
4968        // the author can grep their caixa.lisp without re-running the
4969        // build. Mirrors the diagnostic-shape sweep on every prior
4970        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
4971        let s = SupervisorSpec {
4972            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
4973            ..SupervisorSpec::default()
4974        };
4975        let err = s.validate().unwrap_err();
4976        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4977            panic!("expected ChildCaixaInvalid, got other variant");
4978        };
4979        assert_eq!(caixa, "My_Worker");
4980        assert!(
4981            !reason.is_empty(),
4982            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
4983        );
4984    }
4985
4986    // ── value-shape: zero restart_window + duplicate child names ──────────
4987
4988    #[test]
4989    fn validate_accepts_none_restart_window() {
4990        // Omitted `:restart-window` is the "never reset" sentinel —
4991        // valid by design. Mirrors :limits axes where None = unbounded.
4992        let s = SupervisorSpec {
4993            restart_window: None,
4994            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4995            ..SupervisorSpec::default()
4996        };
4997        s.validate().unwrap();
4998    }
4999
5000    #[test]
5001    fn validate_rejects_zero_restart_window() {
5002        // Same "0 means the opposite of what you think" footgun closed
5003        // for :politicas :timeout (Envoy treats 0s as infinite) and
5004        // :limits :wall-clock (wasmtime traps before the call starts).
5005        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
5006        let s = SupervisorSpec {
5007            restart_window: Some(Duration::ZERO),
5008            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5009            ..SupervisorSpec::default()
5010        };
5011        assert_eq!(
5012            s.validate().unwrap_err(),
5013            SupervisorError::RestartWindowZero
5014        );
5015    }
5016
5017    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
5018    //
5019    // The fourth (and last) typed-`Duration` axis in caixa-core to get
5020    // the integer-millisecond canonical-form gate — peer with
5021    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
5022    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
5023    // path is already gated at the shared codec layer (see
5024    // `restart_window_serde_rejects_fractional_seconds`); this arm
5025    // closes the programmatic-struct-literal path the codec gate can't
5026    // see.
5027
5028    #[test]
5029    fn validate_rejects_sub_millisecond_restart_window() {
5030        // The fail-before-pass-after pin: a programmatic
5031        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
5032        // `validate` on every pre-gate codebase, then truncated to
5033        // `as_millis() == 1` on first serialize — the shared codec
5034        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
5035        // 1_000_000 ns, the typed `restart_window` no longer matches
5036        // its rendered form.
5037        let s = SupervisorSpec {
5038            restart_window: Some(Duration::from_micros(1500)),
5039            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5040            ..SupervisorSpec::default()
5041        };
5042        match s.validate().unwrap_err() {
5043            SupervisorError::RestartWindowNotCanonical { window } => {
5044                assert_eq!(window, Duration::from_micros(1500));
5045            }
5046            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5047        }
5048    }
5049
5050    #[test]
5051    fn validate_rejects_one_nanosecond_restart_window() {
5052        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
5053        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
5054        // so the shared codec emits the literal `"0s"` — the next
5055        // serde round-trip would parse back to `Duration::ZERO`, which
5056        // the `RestartWindowZero` arm then rejects on re-validate. The
5057        // canonical-form gate at this layer surfaces a self-locating
5058        // diagnostic naming the offending Duration verbatim rather
5059        // than a downstream `RestartWindowZero` whose remediation
5060        // points at omitting the slot.
5061        let s = SupervisorSpec {
5062            restart_window: Some(Duration::from_nanos(1)),
5063            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5064            ..SupervisorSpec::default()
5065        };
5066        match s.validate().unwrap_err() {
5067            SupervisorError::RestartWindowNotCanonical { window } => {
5068                assert_eq!(window, Duration::from_nanos(1));
5069            }
5070            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5071        }
5072    }
5073
5074    #[test]
5075    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
5076        // The 1-ns-past-1ms boundary case: a `Duration` carrying
5077        // 1_000_001 ns is structurally past the integer-ms granularity
5078        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
5079        // trip would truncate to `1ms` and the consumer would observe
5080        // a 1-ns drift on every emit. Same boundary the peer
5081        // `validate_rejects_nanosecond_past_canonical_boundary` test
5082        // in limits.rs pins for the `:limits :wall-clock` axis.
5083        let w = Duration::from_nanos(1_000_001);
5084        let s = SupervisorSpec {
5085            restart_window: Some(w),
5086            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5087            ..SupervisorSpec::default()
5088        };
5089        assert_eq!(
5090            s.validate().unwrap_err(),
5091            SupervisorError::RestartWindowNotCanonical { window: w }
5092        );
5093    }
5094
5095    #[test]
5096    fn validate_accepts_integer_millisecond_restart_window_values() {
5097        // The positive-control sweep: every `Duration` the shared
5098        // codec can round-trip losslessly — the canonical
5099        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
5100        // pair emits and accepts — passes `validate` without
5101        // surfacing the new canonical-form arm. Mirrors
5102        // `validate_accepts_integer_millisecond_wall_clock_values` on
5103        // the sibling `:limits :wall-clock` axis.
5104        for w in [
5105            Duration::from_millis(1),
5106            Duration::from_millis(500),
5107            Duration::from_millis(1500),
5108            Duration::from_secs(1),
5109            Duration::from_secs(30),
5110            Duration::from_secs(60),
5111            Duration::from_secs(120),
5112            Duration::from_secs(3600),
5113        ] {
5114            let s = SupervisorSpec {
5115                restart_window: Some(w),
5116                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5117                ..SupervisorSpec::default()
5118            };
5119            s.validate()
5120                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
5121        }
5122    }
5123
5124    #[test]
5125    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
5126        // Cross-arm ordering pin: `Duration::ZERO` has
5127        // `subsec_nanos() == 0` and would otherwise pass the
5128        // canonical-form arm — the zero-floor arm must fire first so
5129        // the more self-locating `RestartWindowZero` diagnostic (with
5130        // its omit-axis remediation directly named) leads. Same
5131        // posture every peer zero-then-shape gate uses
5132        // (`WallClockZero` → `WallClockNotCanonical`,
5133        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
5134        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
5135        let s = SupervisorSpec {
5136            restart_window: Some(Duration::ZERO),
5137            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5138            ..SupervisorSpec::default()
5139        };
5140        assert_eq!(
5141            s.validate().unwrap_err(),
5142            SupervisorError::RestartWindowZero
5143        );
5144    }
5145
5146    #[test]
5147    fn restart_window_canonical_diagnostic_carries_offending_duration() {
5148        // Diagnostic-shape pin: the canonical-form arm names the
5149        // offending `Duration` verbatim so the author's grep lands on
5150        // the field's value, not a generic "duration not canonical"
5151        // message. Same shape every other typed-canonical-form arm
5152        // on this surface carries (`WallClockNotCanonical` carries
5153        // the offending `Duration` verbatim,
5154        // `PolicyTimeoutNotCanonical` carries the offending
5155        // `Duration` verbatim).
5156        let w = Duration::from_micros(500);
5157        let s = SupervisorSpec {
5158            restart_window: Some(w),
5159            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5160            ..SupervisorSpec::default()
5161        };
5162        let err = s.validate().unwrap_err();
5163        let msg = err.to_string();
5164        assert!(
5165            msg.contains("500"),
5166            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
5167        );
5168        assert!(
5169            msg.contains("sub-millisecond"),
5170            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
5171        );
5172    }
5173
5174    #[test]
5175    fn restart_window_validated_value_round_trips_through_codec() {
5176        // The structural property the canonical-ms gate enforces:
5177        // every `SupervisorSpec::restart_window` past
5178        // `SupervisorSpec::validate` round-trips losslessly through
5179        // the shared duration codec (serialize → string →
5180        // deserialize → equal value). Pin this end-to-end so a future
5181        // change to either side (the validate gate's accepted
5182        // granularity, the codec's parse/render unit set) that breaks
5183        // the alignment surfaces here. Peer of
5184        // `wall_clock_validated_value_round_trips_through_codec` on
5185        // the sibling `:limits :wall-clock` axis.
5186        for w in [
5187            Duration::from_millis(1),
5188            Duration::from_millis(1500),
5189            Duration::from_secs(30),
5190            Duration::from_secs(3600),
5191        ] {
5192            let s = SupervisorSpec {
5193                restart_window: Some(w),
5194                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5195                ..SupervisorSpec::default()
5196            };
5197            s.validate().unwrap();
5198            let json = serde_json::to_string(&s).unwrap();
5199            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5200            assert_eq!(back.restart_window, Some(w));
5201        }
5202    }
5203
5204    // ── value-shape: upper cap on :restart-window ─────────────────────────
5205    //
5206    // The fourth (and last) typed-`Duration` axis in caixa-core to get
5207    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
5208    // `:politicas :timeout` (2e8ee7e), and `:politicas
5209    // :circuit-breaker :window` (379a814). Brackets the typed
5210    // `:restart-window` axis structurally: every validated value lies
5211    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
5212    // granularity, closing the
5213    // rolling-window-degenerates-to-lifetime-counter footgun the prior
5214    // zero-floor-and-canonical-form-only checks left open.
5215
5216    #[test]
5217    fn validate_rejects_restart_window_above_cap() {
5218        // The fail-before-pass-after pin: 3601s = 1h + 1s is
5219        // structurally one canonical-tick past the
5220        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
5221        // integer-millisecond magnitude the canonical-form arm above
5222        // accepts cleanly, that the shared duration codec round-trips
5223        // losslessly as `"3601s"`, and that silently passed validate on
5224        // every pre-gate codebase because the typed slot's only checks
5225        // were the zero-floor and canonical-form arms. The runtime
5226        // substrate consuming the value (Erlang/OTP's MaxIntensity/
5227        // Period reconciler, the future wasm-operator's per-supervisor
5228        // restart-intensity counter) reaches for a `Duration` so long
5229        // no realistic restart-recovery pattern resets the counter,
5230        // far from the source caixa.lisp.
5231        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5232        let s = SupervisorSpec {
5233            restart_window: Some(w),
5234            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5235            ..SupervisorSpec::default()
5236        };
5237        assert_eq!(
5238            s.validate().unwrap_err(),
5239            SupervisorError::RestartWindowExceedsCap { window: w }
5240        );
5241    }
5242
5243    #[test]
5244    fn validate_rejects_restart_window_one_millisecond_above_cap() {
5245        // Boundary case: exactly 1ms past the cap (the granularity the
5246        // canonical-form gate enforces). Catches a future "strictly
5247        // less than" half-measure and pins the diagnostic to name the
5248        // offending `Duration` verbatim. Peer of
5249        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
5250        // `rejects_policy_timeout_one_millisecond_above_cap` /
5251        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
5252        // on the sibling typed-`Duration` axes' top edges.
5253        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
5254        let s = SupervisorSpec {
5255            restart_window: Some(w),
5256            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5257            ..SupervisorSpec::default()
5258        };
5259        assert_eq!(
5260            s.validate().unwrap_err(),
5261            SupervisorError::RestartWindowExceedsCap { window: w }
5262        );
5263    }
5264
5265    #[test]
5266    fn validate_rejects_restart_window_far_above_cap() {
5267        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
5268        // `(:restart-window "7d")`, or any "I want a lifetime counter
5269        // but wrote a `<integer>h` magnitude anyway" typo — values the
5270        // canonical-form arm accepts as integer-millisecond magnitudes,
5271        // the codec round-trips losslessly through serde, but the
5272        // operator's `MaxIntensity / Period` reconciler cannot honor
5273        // as a meaningful rolling window. Until this gate landed
5274        // validate accepted them. Pin the common above-cap values (24h,
5275        // 7d, ~11.5d) so a future relaxation that drops the upper bound
5276        // surfaces here.
5277        for w in [
5278            Duration::from_secs(86_400),    // 24h
5279            Duration::from_secs(604_800),   // 7d
5280            Duration::from_secs(1_000_000), // ~11.5 days
5281        ] {
5282            let s = SupervisorSpec {
5283                restart_window: Some(w),
5284                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5285                ..SupervisorSpec::default()
5286            };
5287            assert_eq!(
5288                s.validate().unwrap_err(),
5289                SupervisorError::RestartWindowExceedsCap { window: w }
5290            );
5291        }
5292    }
5293
5294    #[test]
5295    fn validate_accepts_restart_window_at_cap() {
5296        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
5297        // (1h) — must validate. The cap is inclusive on the top edge,
5298        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
5299        // [`crate::POLICY_TIMEOUT_MAX`] /
5300        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
5301        // capped axes. Pin the boundary explicitly so a future
5302        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
5303        // instead of `>`) surfaces here as a test failure rather than a
5304        // silent contract narrowing.
5305        let s = SupervisorSpec {
5306            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5307            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5308            ..SupervisorSpec::default()
5309        };
5310        s.validate()
5311            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
5312    }
5313
5314    #[test]
5315    fn validate_accepts_restart_window_typical_values() {
5316        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
5317        // per-supervisor production-playbook band positive-control
5318        // sweep — every value Learn You Some Erlang's `{intensity, 5,
5319        // 60}` worker-supervisor `Period = 60s` default, Elixir's
5320        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
5321        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
5322        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
5323        // default recommend (5s..=300s) must pass, plus a sweep
5324        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
5325        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
5326        // on the sibling `:limits :wall-clock` axis.
5327        for w in [
5328            Duration::from_millis(1),
5329            Duration::from_millis(500),
5330            Duration::from_secs(1),
5331            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
5332            Duration::from_secs(10), // Riak Core lower
5333            Duration::from_secs(30),
5334            Duration::from_secs(60),  // Learn You Some Erlang default
5335            Duration::from_secs(120), // OTP supervisor MaxT typical
5336            Duration::from_secs(300), // Riak Core upper
5337            Duration::from_secs(900), // 15m
5338            Duration::from_secs(1800),
5339            Duration::from_secs(3600), // exactly 1h, the cap
5340        ] {
5341            let s = SupervisorSpec {
5342                restart_window: Some(w),
5343                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5344                ..SupervisorSpec::default()
5345            };
5346            s.validate()
5347                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
5348        }
5349    }
5350
5351    #[test]
5352    fn restart_window_zero_takes_precedence_over_cap() {
5353        // The cross-arm ordering pin: `Duration::ZERO` is structurally
5354        // outside both `>= 1ms` (zero-floor) and `<=
5355        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
5356        // diagnostic is the more self-locating one (it directly names
5357        // the omit-axis remediation), so the validate gate must fire
5358        // on zero first. Same shape every other zero-then-cap ordering
5359        // on this surface uses (`WallClockZero` then
5360        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
5361        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
5362        // `PolicyBreakerWindowExceedsCap`).
5363        let s = SupervisorSpec {
5364            restart_window: Some(Duration::ZERO),
5365            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5366            ..SupervisorSpec::default()
5367        };
5368        assert_eq!(
5369            s.validate().unwrap_err(),
5370            SupervisorError::RestartWindowZero,
5371            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
5372        );
5373    }
5374
5375    #[test]
5376    fn restart_window_canonical_takes_precedence_over_cap() {
5377        // The cross-arm ordering pin: a `Duration` that is *both*
5378        // sub-millisecond (non-canonical-form) and structurally above
5379        // the cap surfaces the canonical-form diagnostic first,
5380        // because the round-trip-shape break is the more fundamental
5381        // issue (the value can't even round-trip through the codec,
5382        // so the cap diagnostic naming `1ms..=1h` would be misleading
5383        // — there's no integer-ms form of the offending value). Pin
5384        // the order so a future refactor that reorders the arms
5385        // surfaces here as a test failure rather than a silent
5386        // diagnostic regression. Peer of
5387        // `wall_clock_canonical_takes_precedence_over_cap` /
5388        // `policy_timeout_canonical_takes_precedence_over_cap`.
5389        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
5390        let s = SupervisorSpec {
5391            restart_window: Some(w),
5392            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5393            ..SupervisorSpec::default()
5394        };
5395        assert_eq!(
5396            s.validate().unwrap_err(),
5397            SupervisorError::RestartWindowNotCanonical { window: w },
5398            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
5399        );
5400    }
5401
5402    #[test]
5403    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
5404        // The cross-arm ordering pin between the `:max-restarts` cap
5405        // and the sibling `:restart-window` cap. A supervisor carrying
5406        // both an over-cap `max_restarts` AND an over-cap window must
5407        // surface the `MaxRestartsExceedsCap` diagnostic first — the
5408        // cap arm is wired immediately after the zero-restart arm and
5409        // strictly before every window-axis arm (zero / canonical /
5410        // cap), so the offending value the diagnostic names matches
5411        // the order the author would discover the gates by reading
5412        // top-to-bottom through `SupervisorSpec::validate`. Pin the
5413        // order so a future refactor that reorders the arms surfaces
5414        // here as a test failure rather than a silent diagnostic
5415        // regression. Peer of
5416        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
5417        // on the sibling zero / canonical window arms.
5418        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5419        let s = SupervisorSpec {
5420            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5421            restart_window: Some(w),
5422            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5423            ..SupervisorSpec::default()
5424        };
5425        assert_eq!(
5426            s.validate().unwrap_err(),
5427            SupervisorError::MaxRestartsExceedsCap {
5428                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5429            },
5430            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5431        );
5432    }
5433
5434    #[test]
5435    fn restart_window_cap_diagnostic_carries_offending_value() {
5436        // The diagnostic-shape pin: the offending `Duration` is
5437        // carried verbatim into the
5438        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
5439        // surfaced error message names the value the author wrote,
5440        // not just the cap. Same self-locating diagnostic shape every
5441        // other typed-cap arm on this surface carries
5442        // (`WallClockExceedsCap` carries the offending `Duration`
5443        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
5444        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
5445        // the offending `Duration` verbatim).
5446        let w = Duration::from_secs(7200); // 2h
5447        let s = SupervisorSpec {
5448            restart_window: Some(w),
5449            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5450            ..SupervisorSpec::default()
5451        };
5452        let err = s.validate().unwrap_err();
5453        assert!(
5454            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
5455            "got {err:?}"
5456        );
5457        let msg = err.to_string();
5458        assert!(
5459            msg.contains("7200"),
5460            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
5461        );
5462    }
5463
5464    #[test]
5465    fn supervisor_restart_window_cap_pins_canonical_value() {
5466        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
5467        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
5468        // shared duration codec emits as a clean canonical string
5469        // (`"<n>h"`). Pinning the literal value here surfaces a future
5470        // drift (a relaxation to 24h, a tightening to 5m) as a
5471        // deliberate test edit, not a silent contract narrowing.
5472        //
5473        // The four typed-`Duration` caps on the validation surface
5474        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
5475        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
5476        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
5477        // single uniform top edge at the codec's largest emitted unit
5478        // — a structural-property invariant the equality assertions
5479        // here enshrine, so a future drift on any of the four
5480        // surfaces as a deliberate test edit. Same shape every other
5481        // typed-cap value pin uses
5482        // (`wall_clock_cap_pins_canonical_value`,
5483        // `policy_timeout_cap_pins_canonical_value`,
5484        // `circuit_breaker_window_cap_pins_canonical_value`).
5485        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
5486        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
5487        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
5488        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
5489        assert_eq!(
5490            SUPERVISOR_RESTART_WINDOW_MAX,
5491            crate::POLICY_BREAKER_WINDOW_MAX
5492        );
5493    }
5494
5495    #[test]
5496    fn restart_window_cap_value_round_trips_through_codec() {
5497        // The codec round-trip property the cap arm preserves: the
5498        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
5499        // through the shared duration codec — every value at the cap
5500        // serializes to the canonical `"1h"` form and parses back
5501        // identically. Pin the round-trip so a future change to the
5502        // codec's unit set or to the cap's magnitude that breaks the
5503        // round-trip property surfaces here. Peer of
5504        // `wall_clock_cap_value_round_trips_through_codec` on the
5505        // sibling `:limits :wall-clock` axis.
5506        let s = SupervisorSpec {
5507            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5508            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5509            ..SupervisorSpec::default()
5510        };
5511        s.validate().unwrap();
5512        let json = serde_json::to_string(&s).unwrap();
5513        assert!(
5514            json.contains("\"1h\""),
5515            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
5516        );
5517        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5518        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
5519    }
5520
5521    #[test]
5522    fn validate_rejects_duplicate_child_caixa() {
5523        // Two children with the same :caixa render to two ComputeUnits
5524        // with the same name in the cluster's HelmRelease values —
5525        // one silently overwrites the other. Erlang/OTP's child_spec.id
5526        // is required-unique per supervisor; same set-not-multiset
5527        // discipline applied here as for :membros / :placement
5528        // :clusters / :entrada :paths.
5529        let s = SupervisorSpec {
5530            children: vec![
5531                child("worker", "^0.1", RestartPolicy::Permanent),
5532                child("cache", "^0.1", RestartPolicy::Transient),
5533                child("worker", "^0.2", RestartPolicy::Permanent),
5534            ],
5535            ..SupervisorSpec::default()
5536        };
5537        let err = s.validate().unwrap_err();
5538        assert!(
5539            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
5540            "got {err:?}"
5541        );
5542    }
5543
5544    #[test]
5545    fn validate_duplicate_child_diagnostic_names_first_collision() {
5546        // Iteration walks the :children list in declaration order —
5547        // the diagnostic names the first repeat, deterministically,
5548        // even when multiple names duplicate.
5549        let s = SupervisorSpec {
5550            children: vec![
5551                child("a", "^0.1", RestartPolicy::Permanent),
5552                child("b", "^0.1", RestartPolicy::Permanent),
5553                child("a", "^0.1", RestartPolicy::Permanent),
5554                child("b", "^0.1", RestartPolicy::Permanent),
5555            ],
5556            ..SupervisorSpec::default()
5557        };
5558        let err = s.validate().unwrap_err();
5559        assert!(
5560            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
5561            "got {err:?}"
5562        );
5563    }
5564
5565    // ── self-supervision cross-slot gate ──────────────────────────
5566
5567    #[test]
5568    fn validate_no_self_supervision_rejects_self_referential_child() {
5569        // A supervisor whose `:children` lists its own `:nome` is a
5570        // one-node reconciliation cycle — rejected, naming the parent.
5571        let children = vec![
5572            child("worker", "^0.1", RestartPolicy::Permanent),
5573            child("orquestra", "^0.1", RestartPolicy::Permanent),
5574        ];
5575        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
5576        assert!(
5577            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
5578            "got {err:?}"
5579        );
5580    }
5581
5582    #[test]
5583    fn validate_no_self_supervision_accepts_distinct_children() {
5584        // Positive control: distinct child names (including a child that
5585        // is itself a supervisor — nested trees are valid OTP) pass.
5586        let children = vec![
5587            child("worker", "^0.1", RestartPolicy::Permanent),
5588            child("sub-tree", "^0.1", RestartPolicy::Permanent),
5589        ];
5590        validate_no_self_supervision(&children, "orquestra").unwrap();
5591    }
5592
5593    #[test]
5594    fn validate_no_self_supervision_empty_children_is_ok() {
5595        // SimpleOneForOne / no-static-children supervisors have nothing
5596        // to self-reference — the gate is vacuously satisfied.
5597        validate_no_self_supervision(&[], "orquestra").unwrap();
5598    }
5599
5600    #[test]
5601    fn validate_simple_one_for_one_skips_uniqueness_check() {
5602        // SimpleOneForOne supervisors carry no static children — the
5603        // duplicate-child loop never runs. A zero-window declaration
5604        // on a SimpleOneForOne supervisor still trips the window check
5605        // (window applies to dynamic children too).
5606        let s = SupervisorSpec {
5607            estrategia: RestartStrategy::SimpleOneForOne,
5608            restart_window: None,
5609            children: vec![],
5610            ..SupervisorSpec::default()
5611        };
5612        s.validate().unwrap();
5613        let s_zero = SupervisorSpec {
5614            estrategia: RestartStrategy::SimpleOneForOne,
5615            restart_window: Some(Duration::ZERO),
5616            children: vec![],
5617            ..SupervisorSpec::default()
5618        };
5619        assert_eq!(
5620            s_zero.validate().unwrap_err(),
5621            SupervisorError::RestartWindowZero
5622        );
5623    }
5624
5625    #[test]
5626    fn validate_zero_window_runs_after_max_restarts_check() {
5627        // Pin the order: max_restarts == 0 fires before
5628        // restart_window == 0s, so an author with both wrong sees the
5629        // counter-axis diagnostic first (matches the order in the
5630        // struct and in the doc comment).
5631        let s = SupervisorSpec {
5632            max_restarts: 0,
5633            restart_window: Some(Duration::ZERO),
5634            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5635            ..SupervisorSpec::default()
5636        };
5637        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5638    }
5639
5640    #[test]
5641    fn round_trip_all_strategies() {
5642        for &strat in RestartStrategy::ALL {
5643            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
5644            // shape partition through the [`gen_platform::IsVariant`]
5645            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
5646            // predicate rather than the raw
5647            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
5648            // open-coded pattern-match — same closed-set-typed-enum
5649            // arm-discriminator dispatch discipline the sibling
5650            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
5651            // (915a934) extended onto its two paired positive / negated
5652            // `matches!` filter sites, and the sibling
5653            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
5654            // predicate convergence (766ec63) extended onto the M3 mesh-
5655            // slot per-`:placement` distribution-strategy `matches!`
5656            // discriminator axis. See the sibling
5657            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
5658            // fixture and the peer `manifest::tests::
5659            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
5660            // fixture — all three sites (the last unlifted
5661            // `matches!`-based arm-discriminator axis on the OTP-shape
5662            // supervisor sibling-restart-strategy closed-set typed enum,
5663            // acknowledged in 915a934's Prior-commits footnote as the
5664            // outstanding follow-up) now consult one typed dispatch on
5665            // the substrate primitive.
5666            let s = SupervisorSpec {
5667                estrategia: strat,
5668                children: if strat.is_simple_one_for_one() {
5669                    vec![]
5670                } else {
5671                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
5672                },
5673                ..SupervisorSpec::default()
5674            };
5675            let json = serde_json::to_string(&s).unwrap();
5676            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5677            assert_eq!(s, back);
5678        }
5679    }
5680
5681    #[test]
5682    fn round_trip_all_restart_policies() {
5683        for policy in [
5684            RestartPolicy::Permanent,
5685            RestartPolicy::Temporary,
5686            RestartPolicy::Transient,
5687        ] {
5688            let c = child("w", "^0.1", policy);
5689            let json = serde_json::to_string(&c).unwrap();
5690            let back: ChildSpec = serde_json::from_str(&json).unwrap();
5691            assert_eq!(c, back);
5692        }
5693    }
5694
5695    #[test]
5696    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
5697        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
5698        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
5699        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
5700        // is the only variant that satisfies `.is_simple_one_for_one()`;
5701        // every static-children-bearing arm (`OneForOne` / `OneForAll`
5702        // / `RestForOne`) returns `false`. This pin makes the partition
5703        // invariant load-bearing at caixa-core test time so a future
5704        // derive regression (a hole that returns `false` for
5705        // `SimpleOneForOne` too, or a byte-collision that flips a second
5706        // variant to `true`) trips here rather than laundering the arm
5707        // at the three test-fixture builder sites (a hole flips the
5708        // `SimpleOneForOne` fixture to carry a non-empty children list
5709        // and the subsequent `SupervisorSpec::validate` would refuse the
5710        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
5711        // a collision flips a peer strategy's fixture to carry an empty
5712        // children list and the subsequent `validate` would refuse with
5713        // [`SupervisorError::NoChildren`] — either way, the pin fires
5714        // here, at the derive site, rather than at the fixture-refusal
5715        // site far away). Peer of the sibling
5716        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
5717        // (915a934) pin on the M2 OTP-appup axis and the sibling
5718        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
5719        // pin on the M0 `:kind` axis.
5720        let cases: &[(RestartStrategy, bool)] = &[
5721            (RestartStrategy::OneForOne, false),
5722            (RestartStrategy::OneForAll, false),
5723            (RestartStrategy::RestForOne, false),
5724            (RestartStrategy::SimpleOneForOne, true),
5725        ];
5726        for (variant, expected) in cases {
5727            assert_eq!(
5728                variant.is_simple_one_for_one(),
5729                *expected,
5730                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
5731                 return {expected} (partition invariant on the \
5732                 IsVariant-derived arm-discriminator predicate — every \
5733                 test-fixture site that partitions the `:children` slot \
5734                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
5735                 off this typed dispatch, so a derive regression must \
5736                 surface here rather than at the fixture-refusal site)"
5737            );
5738        }
5739    }
5740
5741    #[test]
5742    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
5743        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
5744        // fixture-shape partition against the pre-lift
5745        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
5746        // pattern-match every test-fixture builder site previously
5747        // coupled to inline. Asserts the two projections agree byte-for-
5748        // byte on every arm of the enum, so a future derive regression
5749        // that flipped either predicate's arm-set would surface here at
5750        // caixa-core test time rather than at the three fixture-builder
5751        // sites (`supervisor::tests::round_trip_all_strategies`,
5752        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
5753        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
5754        // far from the derive site. Same peer-shape byte-identity pin
5755        // every sibling `IsVariant`-derive-routed convergence carries on
5756        // the substrate's closed-set typed-enum surface (peer of
5757        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
5758        // on the M2 OTP-appup axis).
5759        for &strat in RestartStrategy::ALL {
5760            let via_predicate = strat.is_simple_one_for_one();
5761            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
5762            assert_eq!(
5763                via_predicate, via_matches,
5764                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
5765                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
5766                 the pre-lift open-coded pattern and the \
5767                 IsVariant-derived predicate are the same axis, \
5768                 one typed dispatch"
5769            );
5770        }
5771    }
5772
5773    #[test]
5774    fn duration_codec_round_trip_canonical_units() {
5775        // Note the canonical-form rule: durations serialize to the
5776        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
5777        // "60s" — but the round-trip preserves the underlying Duration.
5778        let cases = [
5779            ("30s", Duration::from_secs(30)),
5780            ("5m", Duration::from_secs(300)),
5781            ("1h", Duration::from_secs(3600)),
5782            ("500ms", Duration::from_millis(500)),
5783        ];
5784        for (lit, dur) in cases {
5785            let s = SupervisorSpec {
5786                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5787                restart_window: Some(dur),
5788                ..SupervisorSpec::default()
5789            };
5790            let json = serde_json::to_string(&s).unwrap();
5791            assert!(
5792                json.contains(&format!("\"{lit}\"")),
5793                "expected \"{lit}\" in {json}"
5794            );
5795            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5796            assert_eq!(back.restart_window, Some(dur));
5797        }
5798    }
5799
5800    #[test]
5801    fn duration_canonicalizes_to_largest_unit() {
5802        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
5803        // typed Duration still equals 60s on the way back.
5804        let s = SupervisorSpec {
5805            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5806            restart_window: Some(Duration::from_secs(60)),
5807            ..SupervisorSpec::default()
5808        };
5809        let json = serde_json::to_string(&s).unwrap();
5810        assert!(json.contains("\"1m\""), "{json}");
5811        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5812        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
5813    }
5814
5815    #[test]
5816    fn three_child_one_for_one_validates() {
5817        let s = SupervisorSpec {
5818            estrategia: RestartStrategy::OneForOne,
5819            max_restarts: 5,
5820            restart_window: Some(Duration::from_secs(60)),
5821            children: vec![
5822                child("worker", "^0.1", RestartPolicy::Permanent),
5823                child("cache", "^0.1", RestartPolicy::Transient),
5824                child("scratch", "^0.1", RestartPolicy::Temporary),
5825            ],
5826        };
5827        s.validate().unwrap();
5828    }
5829
5830    #[test]
5831    fn json_uses_pascal_case_for_strategy_and_policy() {
5832        // Variant names are PascalCase by default in serde, matching
5833        // tatara-lisp's enum convention (`:estrategia OneForOne`).
5834        let c = child("w", "^0.1", RestartPolicy::Permanent);
5835        let json = serde_json::to_string(&c).unwrap();
5836        assert!(json.contains("\"Permanent\""));
5837        assert!(!json.contains("\"permanent\""));
5838
5839        let s = SupervisorSpec {
5840            estrategia: RestartStrategy::OneForOne,
5841            children: vec![c],
5842            ..SupervisorSpec::default()
5843        };
5844        let json = serde_json::to_string(&s).unwrap();
5845        assert!(json.contains("\"estrategia\":\"OneForOne\""));
5846    }
5847
5848    // ── shared duration codec: integer-magnitude canonical-form gate ──
5849    //
5850    // The gate lifts the discipline `crate::limits::parse_duration`
5851    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
5852    // the shared codec backing the remaining three typed-duration
5853    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
5854    // `:politicas :circuit-breaker :window`. Every magnitude `render`
5855    // emits is a non-negative integer with no decimal point and no
5856    // leading sign, so the codec's accepted set must match for
5857    // serialize/deserialize to round-trip without canonical-form
5858    // drift.
5859
5860    #[test]
5861    fn parse_accepts_integer_canonical_units() {
5862        // Pin the happy-path: every canonical author shape `render`
5863        // ever emits parses to the same `Duration` value, so the
5864        // codec's accepted set is at least a superset of its emitted
5865        // set on the canonical-unit axis.
5866        for (lit, dur) in [
5867            ("30s", Duration::from_secs(30)),
5868            ("500ms", Duration::from_millis(500)),
5869            ("2m", Duration::from_secs(120)),
5870            ("1h", Duration::from_secs(3600)),
5871            ("0s", Duration::ZERO),
5872        ] {
5873            assert_eq!(
5874                duration_codec::parse(lit).unwrap(),
5875                dur,
5876                "parse({lit:?}) should be {dur:?}"
5877            );
5878        }
5879    }
5880
5881    #[test]
5882    fn parse_accepts_bare_integer_as_seconds() {
5883        // The `"s" | ""` arm: a bare integer with no unit is read as
5884        // seconds. Pin this so the unit-empty form keeps parsing (it
5885        // renders to `"<n>s"` on serialize — that's a unit-choice
5886        // drift the integer-magnitude gate does NOT close, matching
5887        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
5888        // the peer `:limits :memory` codec).
5889        assert_eq!(
5890            duration_codec::parse("30").unwrap(),
5891            Duration::from_secs(30)
5892        );
5893    }
5894
5895    #[test]
5896    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
5897        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
5898        // on first serialize — DRIFT. The integer-magnitude gate names
5899        // the offending `"1.5"` verbatim and points at the canonical
5900        // remediation `"1500ms"`.
5901        let err = duration_codec::parse("1.5s").unwrap_err();
5902        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
5903        assert!(
5904            err.contains("not a non-negative integer"),
5905            "missing canonical-form reason in {err:?}"
5906        );
5907        assert!(
5908            err.contains("\"1500ms\""),
5909            "missing canonical-form remediation in {err:?}"
5910        );
5911    }
5912
5913    #[test]
5914    fn parse_rejects_decimal_shaped_integer_seconds() {
5915        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
5916        // `1s` exactly, so the round-trip looks correct — but the
5917        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
5918        // decimal-shape-with-integer-value form so author intent is
5919        // never silently rewritten.
5920        let err = duration_codec::parse("1.0s").unwrap_err();
5921        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
5922        assert!(
5923            err.contains("not a non-negative integer"),
5924            "missing canonical-form reason in {err:?}"
5925        );
5926    }
5927
5928    #[test]
5929    fn parse_rejects_half_unit_minute() {
5930        // `"0.5m"` is the unit-fraction footgun — author writes a
5931        // human-readable half-minute, serde silently rewrites to
5932        // `"30s"` on next emit. The gate names the offending
5933        // magnitude `"0.5"` and points at the integer-in-smaller-unit
5934        // form.
5935        let err = duration_codec::parse("0.5m").unwrap_err();
5936        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
5937        assert!(
5938            err.contains("\"30s\""),
5939            "missing canonical-form remediation in {err:?}"
5940        );
5941    }
5942
5943    #[test]
5944    fn parse_rejects_leading_plus_sign() {
5945        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
5946        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
5947        // cleanly to 30s and round-tripped to `"30s"` on next emit
5948        // (DRIFT). The digit-only gate closes the leading-sign class
5949        // first; the diagnostic names `"+30"` verbatim.
5950        let err = duration_codec::parse("+30s").unwrap_err();
5951        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
5952        assert!(
5953            err.contains("not a non-negative integer"),
5954            "missing canonical-form reason in {err:?}"
5955        );
5956    }
5957
5958    #[test]
5959    fn parse_rejects_leading_minus_sign() {
5960        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
5961        // rejected with `"negative duration in \"-30s\""`. Under the
5962        // integer-magnitude gate the diagnostic is unified — `-30` is
5963        // non-digit-only, f64-numeric, and surfaces with the canonical-
5964        // form reason (no leading `+` / `-` sign) naming the offending
5965        // `"-30"` verbatim. Same diagnostic shape as every other
5966        // rejected non-integer magnitude.
5967        let err = duration_codec::parse("-30s").unwrap_err();
5968        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
5969        assert!(
5970            err.contains("not a non-negative integer"),
5971            "missing canonical-form reason in {err:?}"
5972        );
5973    }
5974
5975    #[test]
5976    fn parse_garbage_still_falls_through_to_bad_magnitude() {
5977        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
5978        // through to the narrower "bad duration magnitude" arm — the
5979        // canonical-form diagnostic is reserved for the parser-shape
5980        // footgun case, not the "not a number at all" case. Same
5981        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
5982        // the peer `:limits :memory` codec.
5983        let err = duration_codec::parse("--1s").unwrap_err();
5984        assert!(
5985            err.contains("bad duration magnitude"),
5986            "expected bad-magnitude wording in {err:?}"
5987        );
5988    }
5989
5990    #[test]
5991    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
5992        // The accepted set is now closed under `u64`-exact integer
5993        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
5994        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
5995        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
5996        // possible. Pin the integer-exact arms across the four unit
5997        // suffixes so a future refactor that reaches back for f64
5998        // (`from_secs_f64`, `mul_f64`) surfaces here.
5999        assert_eq!(
6000            duration_codec::parse("3600s").unwrap(),
6001            Duration::from_secs(3600)
6002        );
6003        assert_eq!(
6004            duration_codec::parse("60m").unwrap(),
6005            Duration::from_secs(3600)
6006        );
6007        assert_eq!(
6008            duration_codec::parse("1h").unwrap(),
6009            Duration::from_secs(3600)
6010        );
6011        assert_eq!(
6012            duration_codec::parse("999ms").unwrap(),
6013            Duration::from_millis(999)
6014        );
6015    }
6016
6017    #[test]
6018    fn restart_window_serde_rejects_fractional_seconds() {
6019        // The shared codec backs `SupervisorSpec::restart_window`
6020        // (`with = "duration_codec"`) — so the gate applies on serde
6021        // deserialize for the typed Supervisor slot. A
6022        // `{"restartWindow":"1.5s"}` payload that previously round-
6023        // tripped to a different canonical string on next serialize
6024        // is now refused at deserialize with the integer-magnitude
6025        // diagnostic.
6026        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6027            "restartWindow":"1.5s",
6028            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6029        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6030        let msg = err.to_string();
6031        assert!(
6032            msg.contains("not a non-negative integer"),
6033            "expected integer-magnitude diagnostic in {msg:?}"
6034        );
6035        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
6036    }
6037
6038    #[test]
6039    fn restart_window_serde_rejects_leading_plus() {
6040        // The `u64::from_str` leading-`+` permissiveness gap that
6041        // motivated the digit-only gate (the `f64`-side accepted
6042        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
6043        // is now closed on the shared codec — surfaces as a structured
6044        // diagnostic at the serde layer for every typed-duration slot.
6045        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6046            "restartWindow":"+30s",
6047            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6048        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6049        let msg = err.to_string();
6050        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
6051        assert!(
6052            msg.contains("not a non-negative integer"),
6053            "missing canonical-form reason in {msg:?}"
6054        );
6055    }
6056
6057    #[test]
6058    fn parse_rejects_leading_zero_magnitude() {
6059        // `"030s"` is digit-only, so the existing non-digit-only / sign
6060        // / fractional arm doesn't catch it — `u64::from_str("030")`
6061        // returns `Ok(30)`, so before this gate `"030s"` parsed to
6062        // `Duration::from_secs(30)` and round-tripped through `render`
6063        // to `"30s"` — a *different* canonical string on the next emit,
6064        // breaking the THEORY.md Part V render-determinism contract
6065        // exactly the way `"+30s"` did before the leading-`+` arm
6066        // landed. Peer with the `rate_limit_codec` leading-zero arm
6067        // (4f46830) on the same canonical-form-drift axis.
6068        let err = duration_codec::parse("030s").unwrap_err();
6069        assert!(
6070            err.contains("non-canonical leading zero"),
6071            "expected leading-zero diagnostic in {err:?}"
6072        );
6073        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6074        assert!(
6075            err.contains("\"30s\""),
6076            "missing canonical-form remediation in {err:?}"
6077        );
6078        assert!(
6079            err.contains("THEORY.md"),
6080            "missing render-determinism citation in {err:?}"
6081        );
6082    }
6083
6084    #[test]
6085    fn parse_rejects_multi_digit_zero_magnitude() {
6086        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
6087        // digit-only, parse losslessly to `Duration::ZERO`, but render
6088        // back to `"0s"` (the single-byte canonical form) on the next
6089        // emit. The leading-zero arm refuses the drift class at the
6090        // codec layer; the semantic-zero gate downstream
6091        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
6092        // the single-byte canonical form `"0s"` separately on the
6093        // typed-validate layer.
6094        let err = duration_codec::parse("00s").unwrap_err();
6095        assert!(
6096            err.contains("non-canonical leading zero"),
6097            "expected leading-zero diagnostic in {err:?}"
6098        );
6099        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
6100    }
6101
6102    #[test]
6103    fn parse_rejects_leading_zero_per_hour_window() {
6104        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
6105        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
6106        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
6107        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
6108        // `h` / bare-integer-as-seconds) inherits the same gate.
6109        let err = duration_codec::parse("01h").unwrap_err();
6110        assert!(
6111            err.contains("non-canonical leading zero"),
6112            "expected leading-zero diagnostic in {err:?}"
6113        );
6114        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
6115    }
6116
6117    #[test]
6118    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
6119        // The `parse_accepts_bare_integer_as_seconds` happy-path
6120        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
6121        // multi-byte starts-with-`0`, parses losslessly to
6122        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
6123        // bare-integer surface accepts permissive unit-empty
6124        // shorthand but still must reject leading-zero padding.
6125        let err = duration_codec::parse("030").unwrap_err();
6126        assert!(
6127            err.contains("non-canonical leading zero"),
6128            "expected leading-zero diagnostic in {err:?}"
6129        );
6130        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6131    }
6132
6133    #[test]
6134    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
6135        // The codec-layer / typed-validate-layer boundary: `"0s"` /
6136        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
6137        // each round-trips losslessly through `render`
6138        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
6139        // accepts them. The downstream semantic-zero gates
6140        // (`SupervisorError::ZeroRestartWindow`,
6141        // `AplicacaoError::PolicyTimeoutZero`,
6142        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
6143        // zero-magnitude authoring at the typed-validate layer above,
6144        // peer with the `rate_limit_codec` codec-layer / typed-
6145        // validate-layer partition for `"0/s"`.
6146        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
6147        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
6148        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
6149    }
6150
6151    #[test]
6152    fn parse_accepts_canonical_magnitude_with_leading_one() {
6153        // The complementary boundary: a future tightening cannot
6154        // drift into rejecting valid canonical magnitudes that
6155        // happen to start with `1` (or any digit `[1-9]`). Pin
6156        // every canonical-unit suffix so the leading-zero arm
6157        // remains strictly narrower than the digit-only arm.
6158        assert_eq!(
6159            duration_codec::parse("100ms").unwrap(),
6160            Duration::from_millis(100)
6161        );
6162        assert_eq!(
6163            duration_codec::parse("100s").unwrap(),
6164            Duration::from_secs(100)
6165        );
6166        assert_eq!(
6167            duration_codec::parse("10m").unwrap(),
6168            Duration::from_secs(600)
6169        );
6170        assert_eq!(
6171            duration_codec::parse("10h").unwrap(),
6172            Duration::from_secs(36_000)
6173        );
6174    }
6175
6176    #[test]
6177    fn restart_window_serde_rejects_leading_zero() {
6178        // The shared codec backs `SupervisorSpec::restart_window`
6179        // (`with = "duration_codec"`) — so the leading-zero arm
6180        // applies on serde deserialize for the typed Supervisor slot.
6181        // A `{"restartWindow":"030s"}` payload that previously round-
6182        // tripped to a different canonical string on next serialize
6183        // is now refused at deserialize with the leading-zero
6184        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
6185        // / `restart_window_serde_rejects_fractional_seconds` on the
6186        // same canonical-form-drift axis.
6187        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6188            "restartWindow":"030s",
6189            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6190        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6191        let msg = err.to_string();
6192        assert!(
6193            msg.contains("non-canonical leading zero"),
6194            "expected leading-zero diagnostic in {msg:?}"
6195        );
6196        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
6197    }
6198
6199    #[test]
6200    fn parse_rejects_leading_whitespace() {
6201        // `" 30s"` — the canonical paste-from-aligned-doc /
6202        // paste-from-YAML-quoted-plain-scalar footgun. Before this
6203        // gate the top-level `s.trim()` at parse entry silently ate
6204        // the leading space and parsed the value to
6205        // `Duration::from_secs(30)`, which then round-tripped through
6206        // `render` to `"30s"` (a *different* canonical string on the
6207        // next emit) — the exact canonical-form-drift class the
6208        // leading-`+` / leading-zero arms already close, extended
6209        // to the whitespace-byte class. Peer with the sibling
6210        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
6211        // the M3 `:politicas` axis.
6212        let err = duration_codec::parse(" 30s").unwrap_err();
6213        assert!(
6214            err.contains("contains whitespace byte"),
6215            "expected whitespace diagnostic in {err:?}"
6216        );
6217        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6218        assert!(
6219            err.contains("THEORY.md"),
6220            "missing render-determinism contract citation in {err:?}"
6221        );
6222    }
6223
6224    #[test]
6225    fn parse_rejects_trailing_whitespace() {
6226        // `"30s "` — the canonical shell-history / trailing-space
6227        // paste footgun. Before this gate the top-level `s.trim()`
6228        // silently ate the trailing space and parsed to
6229        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
6230        // next emit — same canonical-form drift as the leading-space
6231        // sibling, closed on the same whitespace-byte arm.
6232        let err = duration_codec::parse("30s ").unwrap_err();
6233        assert!(
6234            err.contains("contains whitespace byte"),
6235            "expected whitespace diagnostic in {err:?}"
6236        );
6237        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6238    }
6239
6240    #[test]
6241    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
6242        // `"30 s"` — the canonical typographically-spaced author
6243        // shape (the same idiom every prose reference to a duration
6244        // renders as, mistakenly retained when the value is pasted
6245        // into a codec-shaped slot). Before this gate the per-part
6246        // `num_part.trim()` / `unit.trim()` calls silently ate the
6247        // whitespace between the magnitude and the unit and parsed
6248        // the value to `Duration::from_secs(30)`, round-tripping to
6249        // `"30s"` — the codec's *internal* whitespace-tolerance
6250        // vector, orthogonal to the leading / trailing surface but
6251        // the same canonical-form-drift class. Pins the arm as
6252        // strictly stronger than the pre-existing top-level
6253        // `s.trim()` behavior: it fires on whitespace anywhere in
6254        // the value, not just at the string boundary.
6255        let err = duration_codec::parse("30 s").unwrap_err();
6256        assert!(
6257            err.contains("contains whitespace byte"),
6258            "expected whitespace diagnostic in {err:?}"
6259        );
6260        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6261    }
6262
6263    #[test]
6264    fn parse_rejects_tab_byte() {
6265        // `"\t30s"` — the canonical paste-from-indented-doc /
6266        // paste-from-YAML-block-scalar footgun where a tab byte leads
6267        // the magnitude. Pins that the gate covers tab (`0x09`) as
6268        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
6269        // members and both would be silently swallowed by `s.trim()`
6270        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
6271        // space alone to the full ASCII-whitespace set (space `0x20`,
6272        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
6273        // the tab arm as a representative of the non-space members.
6274        let err = duration_codec::parse("\t30s").unwrap_err();
6275        assert!(
6276            err.contains("contains whitespace byte"),
6277            "expected whitespace diagnostic in {err:?}"
6278        );
6279        assert!(
6280            err.contains("0x09"),
6281            "missing offending tab byte in {err:?}"
6282        );
6283    }
6284
6285    #[test]
6286    fn restart_window_serde_rejects_whitespace() {
6287        // The shared codec backs `SupervisorSpec::restart_window`
6288        // (`with = "duration_codec"`) — so the whitespace arm
6289        // applies on serde deserialize for the typed Supervisor slot.
6290        // A `{"restartWindow":" 30s"}` payload that previously round-
6291        // tripped to a different canonical string on next serialize
6292        // is now refused at deserialize with the whitespace-byte
6293        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
6294        // / `restart_window_serde_rejects_leading_plus` /
6295        // `restart_window_serde_rejects_fractional_seconds` on the
6296        // same canonical-form-drift axis.
6297        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6298            "restartWindow":" 30s",
6299            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6300        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6301        let msg = err.to_string();
6302        assert!(
6303            msg.contains("contains whitespace byte"),
6304            "expected whitespace diagnostic in {msg:?}"
6305        );
6306        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
6307    }
6308
6309    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
6310    //
6311    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
6312    // duration codec — closes the strictly-complementary class the
6313    // byte-scan cannot see, through the lifted
6314    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
6315    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
6316    // and `:politicas :circuit-breaker :window` simultaneously via
6317    // this shared codec.
6318
6319    #[test]
6320    fn duration_codec_parse_rejects_leading_nbsp() {
6321        // NBSP prefix — the strictly-complementary drift class the
6322        // ASCII byte-scan cannot see. `str::trim` strips it silently
6323        // and the value drifts to `"30s"` on next serialize.
6324        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
6325        assert!(
6326            err.contains("non-ASCII Unicode whitespace character"),
6327            "expected non-ASCII whitespace diagnostic in {err:?}"
6328        );
6329        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
6330    }
6331
6332    #[test]
6333    fn duration_codec_parse_rejects_trailing_line_separator() {
6334        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
6335        // footgun.
6336        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
6337        assert!(
6338            err.contains("non-ASCII Unicode whitespace character"),
6339            "expected non-ASCII whitespace diagnostic in {err:?}"
6340        );
6341        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
6342    }
6343
6344    #[test]
6345    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
6346        // Positive-control pin: every ASCII-only canonical form the
6347        // renderer emits stays accepted through the new arm.
6348        assert_eq!(
6349            duration_codec::parse("30s").unwrap(),
6350            Duration::from_secs(30)
6351        );
6352        assert_eq!(
6353            duration_codec::parse("500ms").unwrap(),
6354            Duration::from_millis(500)
6355        );
6356        assert_eq!(
6357            duration_codec::parse("1h").unwrap(),
6358            Duration::from_secs(3600)
6359        );
6360    }
6361
6362    #[test]
6363    fn restart_window_serde_rejects_non_ascii_whitespace() {
6364        // The shared codec backs `SupervisorSpec::restart_window` — so
6365        // the new non-ASCII Unicode whitespace arm applies on serde
6366        // deserialize for the typed Supervisor slot. A
6367        // `{"restartWindow":" 30s"}` payload that previously
6368        // survived the ASCII byte-scan (only ASCII whitespace was
6369        // refused) is now refused at deserialize with the
6370        // non-ASCII-whitespace-and-codepoint diagnostic.
6371        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
6372            \"restartWindow\":\"\u{00A0}30s\",\
6373            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
6374        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6375        let msg = err.to_string();
6376        assert!(
6377            msg.contains("non-ASCII Unicode whitespace character"),
6378            "expected non-ASCII whitespace diagnostic in {msg:?}"
6379        );
6380        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
6381    }
6382
6383    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
6384
6385    #[test]
6386    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
6387        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
6388        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
6389        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
6390        // name the exact camelCase JSON keys the
6391        // `#[serde(rename_all = "camelCase")]` attribute on
6392        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
6393        // field carries `Some(_)` / non-empty) and pin that each canonical
6394        // byte-sequence appears verbatim in the JSON — a future accidental
6395        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
6396        // name flip at the derive attribute (any of which would silently
6397        // break every downstream JSON consumer that reaches for one of the
6398        // four consts via `Value::get(...)`) surfaces here as a build-time
6399        // test failure at `supervisor.rs`, not as an apply-time
6400        // `.get(<stale-canonical-const>)` returning `None` far from the
6401        // derive-attr drift's commit. Peer with the sibling
6402        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
6403        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
6404        // M2 typed-slot family established, extended here to close the
6405        // top-level Supervisor axis.
6406        let spec = SupervisorSpec {
6407            estrategia: RestartStrategy::OneForOne,
6408            max_restarts: 5,
6409            restart_window: Some(Duration::from_secs(60)),
6410            children: vec![ChildSpec {
6411                caixa: "w".into(),
6412                versao: "^0.1".into(),
6413                restart: RestartPolicy::Permanent,
6414            }],
6415        };
6416        let json = serde_json::to_string(&spec).unwrap();
6417        for key in [
6418            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6419            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6420            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6421            crate::render::SUPERVISOR_KEY_CHILDREN,
6422        ] {
6423            let quoted = format!("\"{key}\"");
6424            assert!(
6425                json.contains(&quoted),
6426                "serialized SupervisorSpec must carry the lifted \
6427                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
6428                 the JSON emission (got: {json})",
6429            );
6430        }
6431    }
6432
6433    #[test]
6434    fn supervisor_key_consts_are_pairwise_distinct() {
6435        // Cross-axis drift-detection pin: a future collapse of two
6436        // canonical top-level byte-strings onto the same value (e.g. an
6437        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
6438        // also read `"estrategia"`) would silently reroute every
6439        // downstream probe on one axis onto the sibling axis's overlay
6440        // entry and pass every propagation-probe test that expected only
6441        // the stale axis's value. Peer of the sibling four-way distinct
6442        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
6443        let all = [
6444            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6445            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6446            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6447            crate::render::SUPERVISOR_KEY_CHILDREN,
6448        ];
6449        for (i, a) in all.iter().enumerate() {
6450            for b in all.iter().skip(i + 1) {
6451                assert_ne!(
6452                    a, b,
6453                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
6454                     canonical byte-sequences — got `{a}` == `{b}`",
6455                );
6456            }
6457        }
6458    }
6459
6460    #[test]
6461    fn supervisor_key_consts_are_lower_camel_case_shape() {
6462        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
6463        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6464        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6465        // capital, no whitespace / dots) — the canonical shape the
6466        // `#[serde(rename_all = "camelCase")]` derive produces on
6467        // `SupervisorSpec`. A future flip to a non-camelCase attribute
6468        // at the derive surfaces both here (this test fails on the
6469        // stale-constant shape) and at
6470        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6471        // (that test fails on the mismatch between const and derive).
6472        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
6473        // (d8b8b4f) on the sibling M2 `:limits` axis.
6474        for key in [
6475            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6476            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6477            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6478            crate::render::SUPERVISOR_KEY_CHILDREN,
6479        ] {
6480            assert!(
6481                !key.is_empty(),
6482                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
6483            );
6484            let first = key.chars().next().unwrap();
6485            assert!(
6486                first.is_ascii_lowercase(),
6487                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
6488                 (got {key:?}, leads with {first:?})",
6489            );
6490            assert!(
6491                key.chars().all(|c| c.is_ascii_alphanumeric()),
6492                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
6493                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6494            );
6495        }
6496    }
6497
6498    #[test]
6499    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
6500        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
6501        // (camelCase JSON keys, no leading colon) must never collide
6502        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
6503        // consts (kebab-case author-facing labels with leading colon)
6504        // that sit next to them at `caixa_core::render`. Both families
6505        // cover the same four typed Supervisor slots on two distinct
6506        // axes (author-side kebab vs renderer-side camelCase);
6507        // collapsing either family onto the other's byte-shape would
6508        // silently reroute the render-side probe onto the author-facing
6509        // surface, or vice versa. Peer of the byte-distinctness
6510        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
6511        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
6512        let pairs = [
6513            (
6514                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6515                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
6516            ),
6517            (
6518                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6519                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
6520            ),
6521            (
6522                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6523                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
6524            ),
6525            (
6526                crate::render::SUPERVISOR_KEY_CHILDREN,
6527                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
6528            ),
6529        ];
6530        for (json_key, author_key) in pairs {
6531            assert_ne!(
6532                json_key, author_key,
6533                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
6534                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
6535                 got JSON `{json_key}` == author `{author_key}`",
6536            );
6537        }
6538    }
6539
6540    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
6541
6542    #[test]
6543    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
6544        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
6545        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
6546        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
6547        // keys the `#[serde(rename_all = "camelCase")]` attribute on
6548        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
6549        // pin that each canonical byte-sequence appears verbatim in the
6550        // JSON — a future accidental `rename_all = "snake_case"` /
6551        // `"kebab-case"` / verbatim-field-name flip at the derive
6552        // attribute (any of which would silently break every downstream
6553        // JSON consumer that reaches for one of the three consts via
6554        // `Value::get(...)`) surfaces here as a build-time test failure at
6555        // `supervisor.rs`, not as an apply-time
6556        // `.get(<stale-canonical-const>)` returning `None` far from the
6557        // derive-attr drift's commit. Peer with the enclosing
6558        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6559        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
6560        // discipline the SupervisorSpec top-level lift established,
6561        // extended here to the sibling per-`:children` entry `ChildSpec`
6562        // derive so the last M2 typed-struct sub-block
6563        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
6564        // surface without a lifted serde-key peer joins the substrate's
6565        // "one canonical byte-string per typed serialized-key axis"
6566        // discipline.
6567        let c = ChildSpec {
6568            caixa: "worker".into(),
6569            versao: "^0.1".into(),
6570            restart: RestartPolicy::Permanent,
6571        };
6572        let json = serde_json::to_string(&c).unwrap();
6573        for key in [
6574            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6575            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6576            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6577        ] {
6578            let quoted = format!("\"{key}\"");
6579            assert!(
6580                json.contains(&quoted),
6581                "serialized ChildSpec must carry the lifted \
6582                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
6583                 in the JSON emission (got: {json})",
6584            );
6585        }
6586    }
6587
6588    #[test]
6589    fn supervisor_child_key_consts_are_pairwise_distinct() {
6590        // Cross-axis drift-detection pin: a future collapse of two
6591        // canonical `ChildSpec` per-entry byte-strings onto the same
6592        // value (e.g. an accidental copy-paste flip of
6593        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
6594        // silently reroute every downstream probe on one axis onto the
6595        // sibling axis's overlay entry and pass every propagation-probe
6596        // test that expected only the stale axis's value. Peer of the
6597        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
6598        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
6599        // pair (ce80ca0).
6600        let all = [
6601            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6602            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6603            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6604        ];
6605        for (i, a) in all.iter().enumerate() {
6606            for b in all.iter().skip(i + 1) {
6607                assert_ne!(
6608                    a, b,
6609                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
6610                     distinct canonical byte-sequences — got `{a}` == `{b}`",
6611                );
6612            }
6613        }
6614    }
6615
6616    #[test]
6617    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
6618        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
6619        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6620        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6621        // capital, no whitespace / dots) — the canonical shape the
6622        // `#[serde(rename_all = "camelCase")]` derive produces on
6623        // `ChildSpec`. A future flip to a non-camelCase attribute at the
6624        // derive surfaces both here (this test fails on the
6625        // stale-constant shape) and at
6626        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
6627        // (that test fails on the mismatch between const and derive).
6628        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
6629        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
6630        for key in [
6631            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6632            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6633            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6634        ] {
6635            assert!(
6636                !key.is_empty(),
6637                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
6638            );
6639            let first = key.chars().next().unwrap();
6640            assert!(
6641                first.is_ascii_lowercase(),
6642                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
6643                 byte (got {key:?}, leads with {first:?})",
6644            );
6645            assert!(
6646                key.chars().all(|c| c.is_ascii_alphanumeric()),
6647                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
6648                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6649            );
6650        }
6651    }
6652
6653    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
6654
6655    #[test]
6656    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
6657        // The fail-before-pass-after pin: pre-lift there was no
6658        // single-source binding between the [`RestartStrategy`] variant
6659        // name the un-`rename`d `Serialize` derive emits under
6660        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
6661        // every downstream cluster-side dispatcher (the future
6662        // wasm-operator's per-supervisor sibling-restart branch, the
6663        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
6664        // admission-time enum-arm bind, the `caixa-operator`'s
6665        // hierarchical reconciliation scheduler's per-strategy fan-out)
6666        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
6667        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
6668        // override, or a variant rename in the source — would silently
6669        // rebrand the emitted scalar under one spelling while every
6670        // downstream dispatcher still probed the other, with the failure
6671        // surfacing at the operator's reconcile posture (subtrees coming
6672        // up under the `default()` `OneForOne` arm rather than the typed
6673        // slot's declared strategy — a bad child would then only take
6674        // itself down instead of the sibling set the author intended, so
6675        // shared-state children fall out of sync) far from the source
6676        // rebrand commit and with no field naming the drift. Pinning the
6677        // two paths (the `Serialize` derive's serialized string AND the
6678        // [`RestartStrategy::as_str`] helper) to the same four lifted
6679        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
6680        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
6681        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
6682        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
6683        // byte-strings makes any future drift on either endpoint fail
6684        // here at caixa-core build time. Peer of the M3
6685        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
6686        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
6687        // three-path-convergence discipline, extended to close the
6688        // OTP-shaped per-supervisor sibling-restart axis.
6689        for (variant, expected) in [
6690            (
6691                RestartStrategy::OneForOne,
6692                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6693            ),
6694            (
6695                RestartStrategy::OneForAll,
6696                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6697            ),
6698            (
6699                RestartStrategy::RestForOne,
6700                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6701            ),
6702            (
6703                RestartStrategy::SimpleOneForOne,
6704                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6705            ),
6706        ] {
6707            let json = serde_json::to_string(&variant).unwrap();
6708            assert_eq!(
6709                json,
6710                format!("\"{expected}\""),
6711                "RestartStrategy::{variant:?} must serialize to {expected:?}"
6712            );
6713            assert_eq!(
6714                variant.as_str(),
6715                expected,
6716                "RestartStrategy::{variant:?}.as_str() must return the lifted \
6717                 SUPERVISOR_ESTRATEGIA_* constant"
6718            );
6719        }
6720    }
6721
6722    #[test]
6723    fn supervisor_estrategia_consts_are_pairwise_distinct() {
6724        // Cross-arm drift-detection pin: a future collapse of two
6725        // canonical variant byte-strings onto the same value (e.g. an
6726        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
6727        // to also read `"OneForOne"`) would silently reroute every
6728        // downstream operator's per-strategy dispatch onto the sibling
6729        // arm's reconcile branch and pass every propagation-probe test
6730        // that expected only the stale arm's value — the mis-strategied
6731        // subtree would come up with the wrong sibling-restart posture
6732        // on every subsequent failure. Peer of the sibling four-way
6733        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
6734        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
6735        let all = [
6736            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6737            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6738            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6739            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6740        ];
6741        for (i, a) in all.iter().enumerate() {
6742            for (j, b) in all.iter().enumerate() {
6743                if i != j {
6744                    assert_ne!(
6745                        a, b,
6746                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
6747                         — got duplicate {a:?} at indices {i} and {j}",
6748                    );
6749                }
6750            }
6751        }
6752    }
6753
6754    #[test]
6755    fn restart_strategy_display_routes_through_as_str_helper() {
6756        // The fail-before-pass-after pin on the first half of the
6757        // three-path convergence: pre-convergence the sibling
6758        // OTP-shape typed enum [`RestartStrategy`] carried a
6759        // [`std::fmt::Display`] surface via its
6760        // `#[discriminant(also_display)]` gen-platform derive route,
6761        // which arrived kebab-case as `"one-for-one"` /
6762        // `"one-for-all"` / `"rest-for-one"` /
6763        // `"simple-one-for-one"` while the wire format ran as
6764        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
6765        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
6766        // Every consumer reaching for a strategy byte-string past the
6767        // wire format had to pick between three paths
6768        // ([`RestartStrategy::as_str`], the `Serialize` derive's
6769        // serialized string, or `format!("{v}")` on the
6770        // discriminant-Display route), any two of which a future
6771        // variant rename or `#[serde(rename_all = "kebab-case")]`
6772        // attribute would silently desynchronize. Wiring
6773        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
6774        // closes the third path: every `format!("{v}")` call reaches
6775        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6776        // const the wire format and the [`RestartStrategy::as_str`]
6777        // helper already route through, so a future variant rename
6778        // lands at exactly one place. Pin the routing here so a future
6779        // `impl std::fmt::Display for RestartStrategy`
6780        // reimplementation that hand-rolls the arms instead of
6781        // delegating to [`RestartStrategy::as_str`] fails at
6782        // caixa-core build time. Peer of the M3
6783        // `placement_strategy_display_routes_through_as_str_helper`
6784        // (cc8f749) which the M3 axis converged first.
6785        for &variant in RestartStrategy::ALL {
6786            assert_eq!(
6787                variant.to_string(),
6788                variant.as_str(),
6789                "RestartStrategy::{variant:?} Display must route through \
6790                 RestartStrategy::as_str (single source of truth: the lifted \
6791                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
6792            );
6793        }
6794    }
6795
6796    #[test]
6797    fn restart_strategy_display_matches_serialized_wire_byte_string() {
6798        // The fail-before-pass-after pin on the second half of the
6799        // three-path convergence: `Display` (user-facing text) agrees
6800        // byte-for-byte with the `Serialize` derive's wire format
6801        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
6802        // scalar) on every variant. Pre-convergence the two paths
6803        // were structurally independent — a future
6804        // `#[serde(rename_all = "kebab-case")]` attribute on the
6805        // enum would silently rebrand the emitted wire scalar
6806        // (`one-for-one`, `one-for-all`, `rest-for-one`,
6807        // `simple-one-for-one`) while every consumer that
6808        // pretty-prints the strategy (the future wasm-operator's
6809        // per-supervisor sibling-restart-strategy diagnostic line,
6810        // the future `feira app graph` per-supervisor strategy line,
6811        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
6812        // materializer's admission-webhook rejection body) would
6813        // still emit the PascalCase form the `as_str` / `Display`
6814        // route returns, with the mismatch surfacing at consumer
6815        // parse time / operator dispatch time far from the source
6816        // rebrand commit. Pin the two paths byte-for-byte here so any
6817        // future serde-attribute or variant-rename drift is a
6818        // caixa-core-build-time test failure at this call, not a
6819        // silent per-consumer dispatch miss. Peer of the M3
6820        // `placement_strategy_display_matches_serialized_wire_byte_string`
6821        // (cc8f749) which the M3 axis converged first.
6822        for &variant in RestartStrategy::ALL {
6823            let wire = serde_json::to_string(&variant).unwrap();
6824            let unquoted = wire
6825                .strip_prefix('"')
6826                .and_then(|s| s.strip_suffix('"'))
6827                .expect("serialized RestartStrategy is a JSON string");
6828            assert_eq!(
6829                variant.to_string(),
6830                unquoted,
6831                "RestartStrategy::{variant:?} Display byte-string must match the \
6832                 Serialize derive's wire byte-string (three-path convergence: \
6833                 Display + as_str + Serialize all resolve to the same \
6834                 SUPERVISOR_ESTRATEGIA_* const)"
6835            );
6836        }
6837    }
6838
6839    #[test]
6840    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
6841        // Fail-before-pass-after byte-parity pin on the lifted
6842        // `impl AsRef<str> for RestartStrategy` — asserts the
6843        // standard-library trait impl and the substrate-primitive
6844        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
6845        // to the same `&str` per instance across the four-arm
6846        // closed set, so any future silent detour that routes the
6847        // impl through a divergent projection (a per-arm inline
6848        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
6849        // re-inlining that opens a compile-time link to the un-lifted
6850        // arm-literal, a swap onto the kebab-case
6851        // [`gen_platform::Discriminant`] catalog identity that would
6852        // collide the wire axis with the dispatcher-catalog axis) trips
6853        // at caixa-core test time under `PartialEq` rather than at a
6854        // downstream `impl AsRef<str>`-bound consumer's silent split.
6855        // Sweeps every one of the four arms
6856        // [`RestartStrategy::ALL`] carries so no arm's projection is
6857        // covered only by the sibling wire-format `Serialize` derive
6858        // path. Peer of the sibling
6859        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
6860        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
6861        // top-level `:versao` typed newtype — the two pins together
6862        // cover the substrate primitive's `AsRef<str>` projection axis
6863        // on the paired newtype + closed-set-typed-enum surface.
6864        for &variant in RestartStrategy::ALL {
6865            assert_eq!(
6866                <RestartStrategy as AsRef<str>>::as_ref(&variant),
6867                variant.as_str(),
6868                "AsRef<str> impl on RestartStrategy::{variant:?} must \
6869                 byte-equal RestartStrategy::as_str on the same instance \
6870                 — divergence signals a silent detour off the substrate-\
6871                 primitive accessor"
6872            );
6873        }
6874    }
6875
6876    #[test]
6877    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
6878        // Fail-before-pass-after byte-parity pin on the three-path
6879        // convergence discipline the M2 sibling-restart primitive now
6880        // carries on the `&str`-projection axis:
6881        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
6882        // lifted impl), `format!("{s}")` (the pre-existing
6883        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
6884        // primitive `pub const fn` accessor both trait impls delegate
6885        // through) must resolve to the same byte-string on every
6886        // instance across the four-arm closed set. Refuses any future
6887        // divergence between the two trait impls (a stray
6888        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
6889        // rather than delegating through the shared accessor; a
6890        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
6891        // literal cascade) that would silently split the two
6892        // projection paths of the same closed-set typed enum. Mirrors
6893        // the sibling three-path-convergence discipline the peer
6894        // [`crate::CaixaVersion`] typed newtype carries on its
6895        // `AsRef<str>` / `Display` / `as_str` triple
6896        // (version.rs pin
6897        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
6898        // 16d5c7e).
6899        for &variant in RestartStrategy::ALL {
6900            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
6901            let via_display: String = format!("{variant}");
6902            let via_accessor: &str = variant.as_str();
6903            assert_eq!(via_as_ref, via_accessor);
6904            assert_eq!(via_display, via_accessor);
6905            assert_eq!(via_as_ref, via_display.as_str());
6906        }
6907    }
6908
6909    #[test]
6910    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
6911        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
6912        // exhaustive-iteration surface: every variant appears exactly
6913        // once, and the slice length matches the arm count of the
6914        // closed set. Every consumer that walks the accepted-strategy
6915        // set (a future `feira supervisor --estrategia …` CLI-side
6916        // arg-parse's "did you mean" hint, a future M4 admission-
6917        // webhook's rejection body naming the accepted-`:estrategia`
6918        // list, the [`RestartStrategy::from_wire`] reverse-projection
6919        // consumers that iterate the accept-set for diagnostic
6920        // rendering) reads through this slice, so a future arm addition
6921        // that grows the enum but forgets to grow [`Self::ALL`]
6922        // silently truncates every downstream consumer's accept-set at
6923        // the same pre-addition boundary — this pin fails at caixa-core
6924        // build time on the pairwise-distinct + arm-count invariants.
6925        //
6926        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
6927        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
6928        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
6929        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6930        // pins on the peer closed-set typed-enum axes.
6931        let all: &[RestartStrategy] = RestartStrategy::ALL;
6932        assert_eq!(
6933            all.len(),
6934            4,
6935            "RestartStrategy::ALL must enumerate every variant of the \
6936             four-arm closed set (OneForOne, OneForAll, RestForOne, \
6937             SimpleOneForOne); got {all:?}"
6938        );
6939        for (i, a) in all.iter().enumerate() {
6940            for (j, b) in all.iter().enumerate() {
6941                if i != j {
6942                    assert_ne!(
6943                        a, b,
6944                        "RestartStrategy::ALL must carry every variant exactly \
6945                         once — got duplicate {a:?} at indices {i} and {j}"
6946                    );
6947                }
6948            }
6949        }
6950        for variant in [
6951            RestartStrategy::OneForOne,
6952            RestartStrategy::OneForAll,
6953            RestartStrategy::RestForOne,
6954            RestartStrategy::SimpleOneForOne,
6955        ] {
6956            assert!(
6957                all.contains(&variant),
6958                "RestartStrategy::ALL must contain {variant:?} — a future arm \
6959                 addition that grows the enum but forgets to grow the ALL slice \
6960                 silently truncates every downstream consumer's accept-set at \
6961                 the pre-addition boundary"
6962            );
6963        }
6964    }
6965
6966    #[test]
6967    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
6968        // Fail-before-pass-after pin on the forward accept-set of the
6969        // [`RestartStrategy::from_wire`] reverse projection: every
6970        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6971        // constant the [`RestartStrategy::as_str`] emitter walks parses
6972        // back to its paired variant. Any future arm addition that
6973        // grows the emitter's `as_str` match but forgets to grow the
6974        // parser's `from_wire` match silently splits the two halves of
6975        // the round-trip — the wire byte-string one non-serde consumer
6976        // parses from the one the emitter wrote — with the failure
6977        // surfacing at parse time far from the rebrand commit. Pinning
6978        // the four-arm accept-set here catches the drift at caixa-core
6979        // build time.
6980        //
6981        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
6982        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
6983        // accept-set pins on the peer closed-set typed-enum `str → Self`
6984        // axes.
6985        for (wire, expected) in [
6986            (
6987                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6988                RestartStrategy::OneForOne,
6989            ),
6990            (
6991                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6992                RestartStrategy::OneForAll,
6993            ),
6994            (
6995                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6996                RestartStrategy::RestForOne,
6997            ),
6998            (
6999                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7000                RestartStrategy::SimpleOneForOne,
7001            ),
7002        ] {
7003            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7004                panic!(
7005                    "RestartStrategy::from_wire({wire:?}) must accept every \
7006                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
7007                     lifted canonical byte-string that RestartStrategy::{expected:?} \
7008                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
7009                )
7010            });
7011            assert_eq!(
7012                parsed, expected,
7013                "RestartStrategy::from_wire({wire:?}) must return \
7014                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
7015            );
7016        }
7017    }
7018
7019    #[test]
7020    fn restart_strategy_from_wire_round_trips_through_as_str() {
7021        // Fail-before-pass-after pin on the closed round-trip between
7022        // the forward [`RestartStrategy::as_str`] emitter and the
7023        // reverse [`RestartStrategy::from_wire`] parser: for every
7024        // variant in [`RestartStrategy::ALL`], parsing the emitter's
7025        // output must return exactly the same variant. Any per-arm
7026        // divergence — a future arm added to `as_str` but not
7027        // `from_wire`, an accidental copy-paste flip in one but not
7028        // the other — silently splits the emit and parse halves and
7029        // the failure surfaces at consumer parse time far from the
7030        // drift site. The `ALL`-iterating shape means a future arm
7031        // addition picks up the coverage by construction.
7032        //
7033        // Peer of the sibling
7034        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
7035        // (18c7342) round-trip pin on
7036        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
7037        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
7038        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
7039        for &variant in RestartStrategy::ALL {
7040            let wire = variant.as_str();
7041            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7042                panic!(
7043                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7044                     must be Some({variant:?}) — the two halves of the round-trip \
7045                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
7046                     got None on wire byte-string {wire:?}"
7047                )
7048            });
7049            assert_eq!(
7050                parsed, variant,
7051                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7052                 must round-trip to the same variant; got {parsed:?}"
7053            );
7054        }
7055    }
7056
7057    #[test]
7058    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
7059        // Fail-before-pass-after pin on the closed-set refusal
7060        // discipline of [`RestartStrategy::from_wire`]: every
7061        // byte-string outside the four-arm accept-set returns `None`
7062        // rather than silently collapsing onto the [`Default`]
7063        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
7064        // exercised here sweeps the load-bearing drift shapes: the
7065        // empty string (a stripped serde-attribute drift), all-
7066        // whitespace strings (the canonical text-editor accidental
7067        // padding shape), the kebab-case dispatcher-catalog identities
7068        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
7069        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
7070        // derived [`std::str::FromStr`] accept-set, which parses the
7071        // *other* axis of this enum's two-axis split and must not leak
7072        // into the `from_wire` PascalCase-wire accept-set), the
7073        // lowercased single-word forms (`"oneforone"`), the padded
7074        // canonical scalar (`" OneForOne "`), the trailing-newline
7075        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
7076        // (`"AllForOne"` — the canonical typo direction).
7077        //
7078        // Peer of the sibling
7079        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
7080        // (2aa6d23) +
7081        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
7082        // (18c7342) refusal pins on the peer closed-set typed-enum
7083        // axes.
7084        for bad in [
7085            "",
7086            " ",
7087            "\n",
7088            "\t",
7089            "one-for-one",
7090            "one-for-all",
7091            "rest-for-one",
7092            "simple-one-for-one",
7093            "oneforone",
7094            "OneForOnes",
7095            "one_for_one",
7096            "one for one",
7097            "ONEFORONE",
7098            "OneForOne ",
7099            " OneForOne",
7100            " SimpleOneForOne ",
7101            "OneForOne\n",
7102            "restforone",
7103            "REST_FOR_ONE",
7104            "AllForOne",
7105            "Simple",
7106            "?",
7107        ] {
7108            assert!(
7109                RestartStrategy::from_wire(bad).is_none(),
7110                "RestartStrategy::from_wire({bad:?}) must return None — the \
7111                 parser's accept-set is exactly the four RestartStrategy::as_str \
7112                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
7113                 and this byte-string is outside that closed set"
7114            );
7115        }
7116    }
7117
7118    #[test]
7119    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
7120        // Fail-before-pass-after pin on the fourth path of the four-path
7121        // convergence: `from_wire` (the reverse projection) inverts the
7122        // `Serialize` derive's wire byte-string on every variant.
7123        // Together with the pre-existing three-path convergence
7124        // (`Display` + `as_str` + `Serialize` all resolve to the same
7125        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
7126        // pinned by
7127        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
7128        // this closes the round-trip: the wire byte-string the
7129        // `Serialize` derive emits parses back to the same variant
7130        // through `from_wire`, so any future serde-attribute or variant-
7131        // rename drift on the emit half now surfaces as a matched drift
7132        // on the parse half at caixa-core build time — the two halves
7133        // migrate as a unit through the lifted consts on any future
7134        // rename, and the round-trip cannot silently split.
7135        //
7136        // Peer of the sibling
7137        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7138        // (18c7342) wire-format pin on
7139        // [`crate::aplicacao::PlacementStrategy::from_wire`].
7140        for &variant in RestartStrategy::ALL {
7141            let wire = serde_json::to_string(&variant).unwrap();
7142            let unquoted = wire
7143                .strip_prefix('"')
7144                .and_then(|s| s.strip_suffix('"'))
7145                .expect("serialized RestartStrategy is a JSON string");
7146            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
7147                panic!(
7148                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
7149                     Serialize derive's wire byte-string for \
7150                     RestartStrategy::{variant:?} — the four-path convergence \
7151                     (Display + as_str + Serialize + from_wire) resolves through \
7152                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
7153                )
7154            });
7155            assert_eq!(
7156                parsed, variant,
7157                "RestartStrategy::from_wire of the Serialize derive's wire \
7158                 byte-string for RestartStrategy::{variant:?} must round-trip \
7159                 to the same variant; got {parsed:?}"
7160            );
7161        }
7162    }
7163
7164    #[test]
7165    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
7166        // Fail-before-pass-after byte-parity pin on the newly lifted
7167        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
7168        // library trait impl and the substrate-primitive
7169        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
7170        // the same four-arm accept-set across every arm the exhaustive
7171        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7172        // detour that routes the trait impl through a divergent projection
7173        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
7174        // … }` re-inlining that opens a compile-time link to the un-
7175        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
7176        // attribute drift that silently splits the wire byte-string from
7177        // every consumer that reaches for this typed dispatch, an
7178        // accidental swap onto the kebab-case dispatcher-catalog axis the
7179        // pre-existing [`std::str::FromStr`] impl parses through and which
7180        // would collide the two-axis wire/catalog split the sibling
7181        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
7182        // trips at caixa-core test time under `assert_eq!` rather than at
7183        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
7184        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
7185        // carries so no arm's projection is covered only by the sibling
7186        // method-named `from_wire` path. Peer of the sibling
7187        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
7188        // (3c83606),
7189        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
7190        // (bf33136), and the M3
7191        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
7192        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
7193        // onto the first M2-OTP-shape closed-set typed enum on the caixa
7194        // surface.
7195        for &variant in RestartStrategy::ALL {
7196            let wire = variant.as_str();
7197            assert_eq!(
7198                <RestartStrategy as TryFrom<&str>>::try_from(wire),
7199                Ok(variant),
7200                "TryFrom<&str> impl on RestartStrategy must round-trip \
7201                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
7202                 Ok(RestartStrategy::{variant:?}) — divergence from \
7203                 RestartStrategy::from_wire signals a silent detour off \
7204                 the substrate-primitive accessor"
7205            );
7206            assert_eq!(
7207                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
7208                RestartStrategy::from_wire(wire),
7209                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
7210                 RestartStrategy::from_wire on the same input"
7211            );
7212        }
7213    }
7214
7215    #[test]
7216    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
7217        // Rejection witness on the `impl TryFrom<&str> for
7218        // RestartStrategy` — sweeps a candidate set of byte-strings
7219        // outside the four-arm PascalCase wire accept-set the sibling
7220        // [`RestartStrategy::as_str`] emits and asserts every one lands on
7221        // `Err(())`, so a future accidental widening of the trait impl's
7222        // accept-set (a stray additional
7223        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
7224        // path, a silent inclusion of the kebab-case dispatcher-catalog
7225        // byte-string the pre-existing [`std::str::FromStr`] impl the
7226        // [`gen_platform::FromStrKind`] derive installs parses onto the
7227        // wire axis — which would collide the two-axis
7228        // wire/dispatcher-catalog split the sibling
7229        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
7230        // an English-rebrand or plural-arm silent alias that would
7231        // widen the wire accept-set past the OTP-canonical four) trips at
7232        // caixa-core test time. The candidate set includes the empty
7233        // string, whitespace-only padding, the kebab-case dispatcher-
7234        // catalog byte-strings on the sibling axis (a caller who confuses
7235        // the two axes trips here rather than at a downstream consumer's
7236        // silent reject), a lowercase / uppercase / mixed-case fold of
7237        // each PascalCase arm (a caller who assumes case-fold acceptance
7238        // trips here), leading/trailing whitespace padding, the trailing-
7239        // newline shape, quote-wrapped candidates, and a residual set of
7240        // plausible-but-wrong English rebrand candidates. Peer of the
7241        // sibling
7242        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
7243        // (3c83606) and
7244        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
7245        // (6fd00cd) rejection witnesses.
7246        let rejected: &[&str] = &[
7247            "",
7248            " ",
7249            "\n",
7250            "\t",
7251            "one-for-one",
7252            "one-for-all",
7253            "rest-for-one",
7254            "simple-one-for-one",
7255            "oneforone",
7256            "one_for_one",
7257            "OneForOnes",
7258            "ONEFORONE",
7259            "oneforall",
7260            "restforone",
7261            "simpleoneforone",
7262            "OneForOne ",
7263            " OneForOne",
7264            " OneForAll ",
7265            "OneForOne\n",
7266            "RestForOne\t",
7267            "OneForEach",
7268            "AllForOne",
7269            "one for one",
7270            "\"OneForOne\"",
7271            "?",
7272        ];
7273        for &input in rejected {
7274            assert_eq!(
7275                <RestartStrategy as TryFrom<&str>>::try_from(input),
7276                Err(()),
7277                "TryFrom<&str> impl on RestartStrategy must reject the \
7278                 non-wire byte-string {input:?} — silent acceptance signals \
7279                 an accept-set widening off the paired \
7280                 RestartStrategy::from_wire resolver"
7281            );
7282        }
7283    }
7284
7285    #[test]
7286    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
7287        // Cross-axis partition pin: the paired `TryFrom<&str>` and
7288        // `from_wire` reverse projections must resolve identically on
7289        // *every* input, not just the ones [`RestartStrategy::ALL`]
7290        // enumerates. Sweeps a mixed candidate set spanning accepted
7291        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
7292        // dispatcher-catalog byte-strings, empty, whitespace-padded,
7293        // quoted, English-rebrand candidates) inputs and asserts the
7294        // trait's `Result::ok()` projection byte-equals the method-named
7295        // resolver's `Option<Self>` return-shape on each, locking the two
7296        // paths together by construction so any future detour (a stray
7297        // `try_from` special-case that widens or narrows the accept-set
7298        // outside the paired `from_wire` resolver, an accidental swap
7299        // onto the kebab-case [`std::str::FromStr`] impl the
7300        // [`gen_platform::FromStrKind`] derive installs on the sibling
7301        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
7302        // the sibling
7303        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
7304        // pin — extends the round-trip discipline onto the M2-OTP-shape
7305        // sibling-restart axis.
7306        let candidates: &[&str] = &[
7307            "OneForOne",
7308            "OneForAll",
7309            "RestForOne",
7310            "SimpleOneForOne",
7311            "",
7312            "one-for-one",
7313            "one-for-all",
7314            "rest-for-one",
7315            "simple-one-for-one",
7316            "oneforone",
7317            "unknown",
7318            "OneForOne ",
7319            " OneForOne",
7320            "\"OneForOne\"",
7321            "OneForEach",
7322            "?",
7323        ];
7324        for &input in candidates {
7325            let via_trait: Option<RestartStrategy> =
7326                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
7327            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
7328            assert_eq!(
7329                via_trait, via_method,
7330                "TryFrom<&str> and from_wire must resolve identically on \
7331                 input {input:?} — divergence signals the two reverse-\
7332                 projection paths have drifted onto different accept-sets"
7333            );
7334        }
7335    }
7336
7337    #[test]
7338    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
7339        // Fail-before-pass-after byte-parity pin on the newly lifted
7340        // `impl From<RestartStrategy> for &'static str` — asserts the
7341        // standard-library trait impl and the substrate-primitive
7342        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
7343        // the same four-arm emit-set across every arm the exhaustive
7344        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7345        // detour that routes the trait impl through a divergent
7346        // projection (a per-arm inline `match strategy { OneForOne =>
7347        // "OneForOne", … }` re-inlining that opens a compile-time link to
7348        // the un-lifted arm-literal, an accidental swap onto the sibling
7349        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
7350        // would collide the two-axis wire/catalog split the sibling
7351        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
7352        // at caixa-core test time under `assert_eq!` rather than at a
7353        // downstream `impl Into<&'static str>`-bound consumer's silent
7354        // split. Sweeps every one of the four arms
7355        // [`RestartStrategy::ALL`] carries so no arm's projection is
7356        // covered only by the sibling method-named `as_str` /
7357        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
7358        // `<&'static str as From<RestartStrategy>>::from` output in a
7359        // `const`-shape binding to make the `'static` lifetime promise a
7360        // build-time invariant — a future accidental downgrade of any of
7361        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7362        // constants to a non-`&'static str` (a `String::leak()`-produced
7363        // return, a `Box::leak`-cast) trips at caixa-core build time
7364        // rather than at a downstream `'static`-bound consumer.
7365        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7366        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7367        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7368        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7369        for &variant in RestartStrategy::ALL {
7370            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7371            let via_method: &'static str = variant.as_str();
7372            assert_eq!(
7373                via_trait, via_method,
7374                "From<RestartStrategy> for &'static str impl must round-trip \
7375                 RestartStrategy::{variant:?} to the same lifted \
7376                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
7377                 divergence signals a silent detour off the substrate-primitive \
7378                 accessor"
7379            );
7380            let via_into: &'static str = variant.into();
7381            assert_eq!(
7382                via_into, via_method,
7383                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
7384                 byte-equal RestartStrategy::as_str on the same input — the \
7385                 blanket-derived Into shape must resolve to the same as_str \
7386                 dispatch as the explicit From impl"
7387            );
7388        }
7389        assert_eq!(
7390            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7391            [
7392                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7393                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7394                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7395                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7396            ],
7397            "const-context RestartStrategy::as_str must resolve to the four \
7398             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
7399             downgrade of any arm to a non-const or non-static byte-string \
7400             breaks the `&'static str`-lifetime promise the paired \
7401             From<RestartStrategy> for &'static str impl carries by \
7402             construction"
7403        );
7404    }
7405
7406    #[test]
7407    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
7408        // Cross-axis partition pin: the paired trait-idiomatic
7409        // `From<RestartStrategy> for &'static str` forward projection and
7410        // the method-named [`RestartStrategy::as_str`] forward projection
7411        // must resolve identically on *every* arm, not just the ones
7412        // named in the primary byte-parity pin above. Sweeps every
7413        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
7414        // output byte-equals the method-named accessor's return-value on
7415        // each, locking the two forward-projection paths together by
7416        // construction so any future detour (a stray `From` special-case
7417        // that lands on a divergent per-arm literal outside the paired
7418        // `as_str` dispatch, a hypothetical rebrand touching one axis
7419        // without the other) trips at caixa-core test time. Peer of the
7420        // sibling reverse-projection partition pin
7421        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7422        // — extends the round-trip discipline onto the trait-idiomatic
7423        // *forward* axis, closing the two-way `Self ↔ &'static str`
7424        // round-trip on the trait-idiomatic pair
7425        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
7426        // well as the pre-existing method-named pair
7427        // (`as_str` + `from_wire`).
7428        for &variant in RestartStrategy::ALL {
7429            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7430            let via_method: &'static str = variant.as_str();
7431            assert_eq!(
7432                via_trait, via_method,
7433                "From<RestartStrategy> for &'static str and \
7434                 RestartStrategy::as_str must resolve identically on \
7435                 RestartStrategy::{variant:?} — divergence signals the \
7436                 two forward-projection paths have drifted onto different \
7437                 emit-sets"
7438            );
7439        }
7440        // Round-trip witness: every arm's forward `From` output re-parses
7441        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
7442        // to the original variant. Closes the two-way `RestartStrategy ↔
7443        // &'static str` round-trip on the trait-idiomatic axis pair,
7444        // mirroring the pre-existing method-named `as_str` + `from_wire`
7445        // round-trip on the substrate-primitive axis pair.
7446        for &variant in RestartStrategy::ALL {
7447            let emitted: &'static str = variant.into();
7448            let re_parsed: Result<RestartStrategy, ()> =
7449                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7450            assert_eq!(
7451                re_parsed,
7452                Ok(variant),
7453                "trait-idiomatic axis pair must round-trip \
7454                 RestartStrategy::{variant:?} through `.into::<&'static \
7455                 str>()` and back through `TryFrom<&str>` — a break signals \
7456                 the forward-emit and reverse-parse axes have drifted onto \
7457                 different vocabularies"
7458            );
7459        }
7460    }
7461
7462    #[test]
7463    fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
7464        // Fail-before-pass-after byte-parity pin on the newly lifted
7465        // `impl From<&RestartStrategy> for &'static str` — asserts the
7466        // borrowed-input standard-library trait impl and the substrate-
7467        // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
7468        // resolve to the same four-arm emit-set across every arm the
7469        // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
7470        // `From` trait does not auto-derive the borrowed-input sibling
7471        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
7472        // where T: Copy, U: From<T>` blanket in `core`), so the
7473        // borrowed-input axis is a distinct trait-idiomatic surface
7474        // that a `.iter().map(Into::into)` shape over
7475        // [`RestartStrategy::ALL`] (whose iterator yields
7476        // `&RestartStrategy`, not `RestartStrategy`) reaches through
7477        // this impl and no other — the paired owned-input
7478        // [`From<RestartStrategy>`] impl requires an explicit
7479        // `.copied()` / dereference before the trait fires.
7480        // Materializes the `<&'static str as
7481        // From<&RestartStrategy>>::from` output in a `const`-shape
7482        // binding to make the `'static` lifetime promise a build-time
7483        // invariant.
7484        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7485        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7486        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7487        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7488        for variant in RestartStrategy::ALL {
7489            let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
7490            let via_method: &'static str = variant.as_str();
7491            assert_eq!(
7492                via_trait, via_method,
7493                "From<&RestartStrategy> for &'static str impl must \
7494                 round-trip &RestartStrategy::{variant:?} to the same \
7495                 lifted SUPERVISOR_ESTRATEGIA_* const \
7496                 RestartStrategy::as_str returns — divergence signals a \
7497                 silent detour off the substrate-primitive accessor"
7498            );
7499            let via_into: &'static str = variant.into();
7500            assert_eq!(
7501                via_into, via_method,
7502                "Into<&'static str>::into on &RestartStrategy::{variant:?} \
7503                 must byte-equal RestartStrategy::as_str on the same input — \
7504                 the blanket-derived Into shape must resolve to the same \
7505                 as_str dispatch as the explicit From impl"
7506            );
7507        }
7508        assert_eq!(
7509            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7510            [
7511                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7512                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7513                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7514                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7515            ],
7516            "const-context RestartStrategy::as_str must resolve to the \
7517             four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
7518             input From<&RestartStrategy> for &'static str impl inherits \
7519             its `'static` lifetime promise from the same accessor the \
7520             owned-input sibling routes through"
7521        );
7522    }
7523
7524    #[test]
7525    fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
7526        // Cross-axis partition pin: the paired trait-idiomatic
7527        // owned-input `From<RestartStrategy> for &'static str` (523157d
7528        // campaign-shape) and borrowed-input `From<&RestartStrategy> for
7529        // &'static str` (this lift) forward projections must resolve
7530        // identically on every arm, locking the two input-shape paths
7531        // together so any future detour trips at caixa-core test time.
7532        // Then a witness that a `.iter().map(Into::into)` pipe over
7533        // [`RestartStrategy::ALL`] (whose iterator yields
7534        // `&RestartStrategy`) materializes the four-arm accept-set
7535        // through the borrowed-input axis alone — the exact shape a
7536        // future wasm-operator per-supervisor sibling-restart-strategy
7537        // diagnostic line, a future substrate-wide per-arm diagnostic
7538        // column, or a
7539        // `HashMap::<&'static str, RestartStrategy>::from_iter(
7540        //     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
7541        // per-strategy lookup reaches through — closing the two-way
7542        // owned/borrowed input-shape symmetry on the forward-projection
7543        // trait-idiomatic axis. Peer of the sibling
7544        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7545        // (64aa742) /
7546        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7547        // (5ab993a) /
7548        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7549        // (807b0b5) partition pins on the sibling closed-set typed-enum
7550        // discriminator axes — extends the borrowed-input axis
7551        // discipline onto the first M2 OTP-shape sibling-restart
7552        // closed-set typed enum on the caixa surface. Also closes the
7553        // direct two-way `&Self → &'static str → Self` round-trip via
7554        // the paired [`TryFrom<&str>`] axis — unlike the peer
7555        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
7556        // lowercase Portuguese diagnostic bytes while the reverse
7557        // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
7558        // trip through an intermediate wire-vocab hop), the
7559        // [`RestartStrategy::as_str`] emit and
7560        // [`RestartStrategy::from_wire`] parse share the same
7561        // `PascalCase` vocabulary by construction, so the borrowed-
7562        // input forward axis and the reverse axis compose directly.
7563        for &variant in RestartStrategy::ALL {
7564            let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7565            let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
7566            assert_eq!(
7567                owned, borrowed,
7568                "From<RestartStrategy> and From<&RestartStrategy> for \
7569                 &'static str must resolve identically on \
7570                 RestartStrategy::{variant:?} — divergence signals the \
7571                 owned-input and borrowed-input forward-projection paths \
7572                 have drifted onto different emit-sets"
7573            );
7574        }
7575        let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
7576        let via_method: Vec<&'static str> =
7577            RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
7578        assert_eq!(
7579            via_iter, via_method,
7580            "`.iter().map(Into::into)` over RestartStrategy::ALL must \
7581             byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
7582             borrowed-input `From<&RestartStrategy> for &'static str` \
7583             axis is what makes the `.iter().map(Into::into)` shape route \
7584             through the substrate-primitive `RestartStrategy::as_str` \
7585             accessor rather than through a per-call-site `.copied()` / \
7586             dereference detour"
7587        );
7588        for variant in RestartStrategy::ALL {
7589            let emitted: &'static str = variant.into();
7590            let re_parsed: Result<RestartStrategy, ()> =
7591                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7592            assert_eq!(
7593                re_parsed,
7594                Ok(*variant),
7595                "trait-idiomatic borrowed-input forward-projection + \
7596                 reverse-projection axis pair must round-trip \
7597                 &RestartStrategy::{variant:?} through `.into::<&'static \
7598                 str>()` (via the borrowed-input axis) and back through \
7599                 `TryFrom<&str>` — a break signals the borrowed-input \
7600                 forward-emit and reverse-parse axes have drifted onto \
7601                 different vocabularies"
7602            );
7603        }
7604    }
7605
7606    #[test]
7607    fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
7608        // Fail-before-pass-after byte-parity pin on the newly lifted
7609        // `impl From<RestartStrategy> for String` — asserts the
7610        // owned-`String`-returning standard-library trait impl and the
7611        // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
7612        // accessor resolve to the same four-arm emit-set across every
7613        // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
7614        // Rust's standard library does not carry a blanket
7615        // `impl<T: AsRef<str>> From<T> for String` (nor an
7616        // `impl<T: fmt::Display> From<T> for String`), so the
7617        // owned-`String` forward-projection axis is a distinct
7618        // trait-idiomatic surface that a
7619        // `let key: String = strategy.into();`-shaped call site
7620        // reaches through this impl and no other — the paired sibling
7621        // `From<RestartStrategy> for &'static str` impl forces every
7622        // owned-`String` call site through an explicit
7623        // `.to_owned()` / `String::from` restatement.
7624        for &variant in RestartStrategy::ALL {
7625            let via_trait: String = <String as From<RestartStrategy>>::from(variant);
7626            let via_method: &'static str = variant.as_str();
7627            assert_eq!(
7628                via_trait.as_str(),
7629                via_method,
7630                "From<RestartStrategy> for String impl must round-trip \
7631                 RestartStrategy::{variant:?} to the same lifted \
7632                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
7633                 returns — divergence signals a silent detour off the \
7634                 substrate-primitive accessor"
7635            );
7636            let via_into: String = variant.into();
7637            assert_eq!(
7638                via_into.as_str(),
7639                via_method,
7640                "Into<String>::into on RestartStrategy::{variant:?} must \
7641                 byte-equal RestartStrategy::as_str on the same input — the \
7642                 blanket-derived Into shape must resolve to the same as_str \
7643                 dispatch as the explicit From impl"
7644            );
7645        }
7646    }
7647
7648    #[test]
7649    fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
7650        // Cross-axis partition pin: the paired trait-idiomatic
7651        // owned-`String` `From<RestartStrategy> for String` (this lift)
7652        // and owned-`&'static str` `From<RestartStrategy> for &'static
7653        // str` (523157d) forward projections must resolve identically
7654        // on every arm, locking the two return-type-shape paths
7655        // together so any future detour trips at caixa-core test time.
7656        // Also byte-parity witness against the sibling
7657        // [`ToString::to_string`] surface routed through
7658        // [`std::fmt::Display`] — the three owned-heap-string paths
7659        // (`.into::<String>()`, `String::from`, `.to_string()`) must
7660        // resolve identically on every arm so a future consumer that
7661        // picks any of the three lands on the same lifted
7662        // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
7663        // witness through the paired trait-idiomatic reverse
7664        // [`TryFrom<&str>`] axis on the owned-`String`'s
7665        // [`String::as_str`] borrow that closes the two-way
7666        // `Self → String → Self` round-trip on the trait-idiomatic
7667        // owned-`String` forward + reverse axis pair.
7668        for &variant in RestartStrategy::ALL {
7669            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
7670            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7671            assert_eq!(
7672                owned_string.as_str(),
7673                owned_static,
7674                "From<RestartStrategy> for String and From<RestartStrategy> \
7675                 for &'static str must resolve identically on \
7676                 RestartStrategy::{variant:?} — divergence signals the \
7677                 owned-`String` and owned-`&'static str` forward-projection \
7678                 return-type-shape paths have drifted onto different \
7679                 emit-sets"
7680            );
7681            let via_to_string: String = variant.to_string();
7682            assert_eq!(
7683                owned_string, via_to_string,
7684                "From<RestartStrategy> for String must byte-equal \
7685                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
7686                 divergence signals the trait-idiomatic owned-`String` \
7687                 forward-projection axis and the ToString-through-Display \
7688                 axis have drifted onto different emit-sets"
7689            );
7690        }
7691        let via_iter: Vec<String> = RestartStrategy::ALL
7692            .iter()
7693            .copied()
7694            .map(String::from)
7695            .collect();
7696        let via_method: Vec<String> = RestartStrategy::ALL
7697            .iter()
7698            .map(|s| s.as_str().to_owned())
7699            .collect();
7700        assert_eq!(
7701            via_iter, via_method,
7702            "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
7703             must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
7704             every arm — the owned-`String` `From<RestartStrategy> for \
7705             String` axis is what makes the `String::from` composition \
7706             route through the substrate-primitive `RestartStrategy::as_str` \
7707             accessor rather than through a per-call-site `.to_owned()` / \
7708             `String::from(strategy.as_str())` detour"
7709        );
7710        for &variant in RestartStrategy::ALL {
7711            let emitted: String = variant.into();
7712            let re_parsed: Result<RestartStrategy, ()> =
7713                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
7714            assert_eq!(
7715                re_parsed,
7716                Ok(variant),
7717                "trait-idiomatic owned-`String` forward-projection + \
7718                 reverse-projection axis pair must round-trip \
7719                 RestartStrategy::{variant:?} through `.into::<String>()` \
7720                 and back through `TryFrom<&str>` on the owned-`String`'s \
7721                 String::as_str borrow — a break signals the owned-`String` \
7722                 forward-emit and reverse-parse axes have drifted onto \
7723                 different vocabularies"
7724            );
7725        }
7726    }
7727
7728    #[test]
7729    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
7730        // Fail-before-pass-after byte-parity pin on the newly lifted
7731        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
7732        // library trait impl and the substrate-primitive
7733        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
7734        // the same three-arm accept-set across every arm the exhaustive
7735        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
7736        // detour that routes the trait impl through a divergent
7737        // projection (a per-arm inline `match s { "Permanent" =>
7738        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
7739        // link to the un-lifted arm-literal, a hypothetical
7740        // `#[serde(rename_all = "…")]` attribute drift that silently
7741        // splits the wire byte-string from every consumer that reaches
7742        // for this typed dispatch, an accidental swap onto the kebab-case
7743        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
7744        // impl parses through and which would collide the two-axis
7745        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
7746        // doc block makes load-bearing) trips at caixa-core test time
7747        // under `assert_eq!` rather than at a downstream
7748        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
7749        // every one of the three arms [`RestartPolicy::ALL`] carries so
7750        // no arm's projection is covered only by the sibling method-
7751        // named `from_wire` path. Peer of the sibling
7752        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
7753        // (5b828ed) — extends the trait-idiomatic reverse-projection
7754        // axis onto the third and final M2-OTP-shape closed-set typed
7755        // enum on the caixa surface (the paired per-child restart-
7756        // decision-policy sibling on the same M2 `:supervisor` slot).
7757        for &variant in RestartPolicy::ALL {
7758            let wire = variant.as_str();
7759            assert_eq!(
7760                <RestartPolicy as TryFrom<&str>>::try_from(wire),
7761                Ok(variant),
7762                "TryFrom<&str> impl on RestartPolicy must round-trip \
7763                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
7764                 Ok(RestartPolicy::{variant:?}) — divergence from \
7765                 RestartPolicy::from_wire signals a silent detour off \
7766                 the substrate-primitive accessor"
7767            );
7768            assert_eq!(
7769                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
7770                RestartPolicy::from_wire(wire),
7771                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
7772                 equal RestartPolicy::from_wire on the same input"
7773            );
7774        }
7775    }
7776
7777    #[test]
7778    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
7779        // Rejection witness on the `impl TryFrom<&str> for
7780        // RestartPolicy` — sweeps a candidate set of byte-strings
7781        // outside the three-arm PascalCase wire accept-set the sibling
7782        // [`RestartPolicy::as_str`] emits and asserts every one lands on
7783        // `Err(())`, so a future accidental widening of the trait impl's
7784        // accept-set (a stray additional
7785        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
7786        // path, a silent inclusion of the kebab-case dispatcher-catalog
7787        // byte-string the pre-existing [`std::str::FromStr`] impl the
7788        // [`gen_platform::FromStrKind`] derive installs parses onto the
7789        // wire axis — which would collide the two-axis
7790        // wire/dispatcher-catalog split the sibling
7791        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
7792        // an English-rebrand or plural-arm silent alias that would widen
7793        // the wire accept-set past the OTP-canonical three) trips at
7794        // caixa-core test time. The candidate set includes the empty
7795        // string, whitespace-only padding, the kebab-case dispatcher-
7796        // catalog byte-strings on the sibling axis (a caller who
7797        // confuses the two axes trips here rather than at a downstream
7798        // consumer's silent reject), a lowercase / uppercase / mixed-case
7799        // fold of each PascalCase arm (a caller who assumes case-fold
7800        // acceptance trips here), leading/trailing whitespace padding,
7801        // the trailing-newline shape, quote-wrapped candidates, and a
7802        // residual set of plausible-but-wrong English rebrand
7803        // candidates. Peer of the sibling
7804        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
7805        // (5b828ed) rejection witness.
7806        let rejected: &[&str] = &[
7807            "",
7808            " ",
7809            "\n",
7810            "\t",
7811            "permanent",
7812            "temporary",
7813            "transient",
7814            "PERMANENT",
7815            "TEMPORARY",
7816            "TRANSIENT",
7817            "Permanents",
7818            "Permanent ",
7819            " Permanent",
7820            " Temporary ",
7821            "Permanent\n",
7822            "Transient\t",
7823            "\"Permanent\"",
7824            "Ephemeral",
7825            "Always",
7826            "Never",
7827            "OnAbnormalExit",
7828            "intrinsic",
7829            "?",
7830        ];
7831        for &input in rejected {
7832            assert_eq!(
7833                <RestartPolicy as TryFrom<&str>>::try_from(input),
7834                Err(()),
7835                "TryFrom<&str> impl on RestartPolicy must reject the \
7836                 non-wire byte-string {input:?} — silent acceptance \
7837                 signals an accept-set widening off the paired \
7838                 RestartPolicy::from_wire resolver"
7839            );
7840        }
7841    }
7842
7843    #[test]
7844    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
7845        // Cross-axis partition pin: the paired `TryFrom<&str>` and
7846        // `from_wire` reverse projections must resolve identically on
7847        // *every* input, not just the ones [`RestartPolicy::ALL`]
7848        // enumerates. Sweeps a mixed candidate set spanning accepted
7849        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
7850        // case dispatcher-catalog byte-strings, empty, whitespace-
7851        // padded, quoted, English-rebrand candidates) inputs and asserts
7852        // the trait's `Result::ok()` projection byte-equals the method-
7853        // named resolver's `Option<Self>` return-shape on each, locking
7854        // the two paths together by construction so any future detour
7855        // (a stray `try_from` special-case that widens or narrows the
7856        // accept-set outside the paired `from_wire` resolver, an
7857        // accidental swap onto the kebab-case [`std::str::FromStr`]
7858        // impl the [`gen_platform::FromStrKind`] derive installs on the
7859        // sibling dispatcher-catalog axis) trips at caixa-core test
7860        // time. Peer of the sibling
7861        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7862        // pin — extends the round-trip discipline onto the M2-OTP-shape
7863        // per-child restart-policy axis.
7864        let candidates: &[&str] = &[
7865            "Permanent",
7866            "Temporary",
7867            "Transient",
7868            "",
7869            "permanent",
7870            "temporary",
7871            "transient",
7872            "PERMANENT",
7873            "unknown",
7874            "Permanent ",
7875            " Permanent",
7876            "\"Permanent\"",
7877            "Ephemeral",
7878            "OnAbnormalExit",
7879            "?",
7880        ];
7881        for &input in candidates {
7882            let via_trait: Option<RestartPolicy> =
7883                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
7884            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
7885            assert_eq!(
7886                via_trait, via_method,
7887                "TryFrom<&str> and from_wire must resolve identically on \
7888                 input {input:?} — divergence signals the two reverse-\
7889                 projection paths have drifted onto different accept-sets"
7890            );
7891        }
7892    }
7893
7894    #[test]
7895    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
7896        // Fail-before-pass-after byte-parity pin on the newly lifted
7897        // `impl From<RestartPolicy> for &'static str` — asserts the
7898        // standard-library trait impl and the substrate-primitive
7899        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
7900        // the same three-arm emit-set across every arm the exhaustive
7901        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
7902        // detour that routes the trait impl through a divergent
7903        // projection (a per-arm inline `match policy { Permanent =>
7904        // "Permanent", … }` re-inlining that opens a compile-time link
7905        // to the un-lifted arm-literal, an accidental swap onto the
7906        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
7907        // axis that would collide the two-axis wire/catalog split the
7908        // sibling [`RestartPolicy::from_wire`] doc block makes
7909        // load-bearing) trips at caixa-core test time under
7910        // `assert_eq!` rather than at a downstream
7911        // `impl Into<&'static str>`-bound consumer's silent split.
7912        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
7913        // carries so no arm's projection is covered only by the sibling
7914        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
7915        // paths. Materializes the `<&'static str as
7916        // From<RestartPolicy>>::from` output in a `const`-shape binding
7917        // to make the `'static` lifetime promise a build-time invariant
7918        // — a future accidental downgrade of any of the three arms'
7919        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
7920        // non-`&'static str` (a `String::leak()`-produced return, a
7921        // `Box::leak`-cast) trips at caixa-core build time rather than
7922        // at a downstream `'static`-bound consumer. Peer of the sibling
7923        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
7924        // (523157d) — extends the trait-idiomatic forward-projection
7925        // axis onto the second (and second-of-two-in-M2) closed-set
7926        // typed enum on the caixa surface (the paired per-child
7927        // restart-decision-policy sibling on the same M2 `:supervisor`
7928        // slot).
7929        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
7930        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
7931        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
7932        for &variant in RestartPolicy::ALL {
7933            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
7934            let via_method: &'static str = variant.as_str();
7935            assert_eq!(
7936                via_trait, via_method,
7937                "From<RestartPolicy> for &'static str impl must round-trip \
7938                 RestartPolicy::{variant:?} to the same lifted \
7939                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
7940                 divergence signals a silent detour off the substrate-primitive \
7941                 accessor"
7942            );
7943            let via_into: &'static str = variant.into();
7944            assert_eq!(
7945                via_into, via_method,
7946                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
7947                 byte-equal RestartPolicy::as_str on the same input — the \
7948                 blanket-derived Into shape must resolve to the same as_str \
7949                 dispatch as the explicit From impl"
7950            );
7951        }
7952        assert_eq!(
7953            [PERMANENT, TEMPORARY, TRANSIENT],
7954            [
7955                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7956                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7957                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7958            ],
7959            "const-context RestartPolicy::as_str must resolve to the three \
7960             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
7961             downgrade of any arm to a non-const or non-static byte-string \
7962             breaks the `&'static str`-lifetime promise the paired \
7963             From<RestartPolicy> for &'static str impl carries by \
7964             construction"
7965        );
7966    }
7967
7968    #[test]
7969    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
7970        // Cross-axis partition pin: the paired trait-idiomatic
7971        // `From<RestartPolicy> for &'static str` forward projection and
7972        // the method-named [`RestartPolicy::as_str`] forward projection
7973        // must resolve identically on *every* arm, not just the ones
7974        // named in the primary byte-parity pin above. Sweeps every
7975        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
7976        // output byte-equals the method-named accessor's return-value on
7977        // each, locking the two forward-projection paths together by
7978        // construction so any future detour (a stray `From` special-case
7979        // that lands on a divergent per-arm literal outside the paired
7980        // `as_str` dispatch, a hypothetical rebrand touching one axis
7981        // without the other) trips at caixa-core test time. Peer of the
7982        // sibling forward-projection partition pin
7983        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
7984        // (523157d) — extends the round-trip discipline onto the
7985        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
7986        // surface, closing the two-way `Self ↔ &'static str` round-trip
7987        // on the trait-idiomatic pair (`From<Self> for &'static str` +
7988        // `TryFrom<&str> for Self`) as well as the pre-existing method-
7989        // named pair (`as_str` + `from_wire`).
7990        for &variant in RestartPolicy::ALL {
7991            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
7992            let via_method: &'static str = variant.as_str();
7993            assert_eq!(
7994                via_trait, via_method,
7995                "From<RestartPolicy> for &'static str and \
7996                 RestartPolicy::as_str must resolve identically on \
7997                 RestartPolicy::{variant:?} — divergence signals the \
7998                 two forward-projection paths have drifted onto different \
7999                 emit-sets"
8000            );
8001        }
8002        // Round-trip witness: every arm's forward `From` output re-parses
8003        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8004        // to the original variant. Closes the two-way `RestartPolicy ↔
8005        // &'static str` round-trip on the trait-idiomatic axis pair,
8006        // mirroring the pre-existing method-named `as_str` + `from_wire`
8007        // round-trip on the substrate-primitive axis pair.
8008        for &variant in RestartPolicy::ALL {
8009            let emitted: &'static str = variant.into();
8010            let re_parsed: Result<RestartPolicy, ()> =
8011                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
8012            assert_eq!(
8013                re_parsed,
8014                Ok(variant),
8015                "trait-idiomatic axis pair must round-trip \
8016                 RestartPolicy::{variant:?} through `.into::<&'static \
8017                 str>()` and back through `TryFrom<&str>` — a break signals \
8018                 the forward-emit and reverse-parse axes have drifted onto \
8019                 different vocabularies"
8020            );
8021        }
8022    }
8023
8024    #[test]
8025    fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
8026        // Fail-before-pass-after byte-parity pin on the newly lifted
8027        // `impl From<&RestartPolicy> for &'static str` — asserts the
8028        // borrowed-input standard-library trait impl and the substrate-
8029        // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
8030        // resolve to the same three-arm emit-set across every arm the
8031        // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
8032        // `From` trait does not auto-derive the borrowed-input sibling
8033        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8034        // where T: Copy, U: From<T>` blanket in `core`), so the
8035        // borrowed-input axis is a distinct trait-idiomatic surface
8036        // that a `.iter().map(Into::into)` shape over
8037        // [`RestartPolicy::ALL`] (whose iterator yields
8038        // `&RestartPolicy`, not `RestartPolicy`) reaches through this
8039        // impl and no other — the paired owned-input
8040        // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
8041        // / dereference before the trait fires. Materializes the
8042        // `<&'static str as From<&RestartPolicy>>::from` output in a
8043        // `const`-shape binding to make the `'static` lifetime promise
8044        // a build-time invariant.
8045        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
8046        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
8047        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
8048        for variant in RestartPolicy::ALL {
8049            let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
8050            let via_method: &'static str = variant.as_str();
8051            assert_eq!(
8052                via_trait, via_method,
8053                "From<&RestartPolicy> for &'static str impl must round-trip \
8054                 &RestartPolicy::{variant:?} to the same lifted \
8055                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
8056                 returns — divergence signals a silent detour off the \
8057                 substrate-primitive accessor"
8058            );
8059            let via_into: &'static str = variant.into();
8060            assert_eq!(
8061                via_into, via_method,
8062                "Into<&'static str>::into on &RestartPolicy::{variant:?} \
8063                 must byte-equal RestartPolicy::as_str on the same input — \
8064                 the blanket-derived Into shape must resolve to the same \
8065                 as_str dispatch as the explicit From impl"
8066            );
8067        }
8068        assert_eq!(
8069            [PERMANENT, TEMPORARY, TRANSIENT],
8070            [
8071                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8072                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8073                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8074            ],
8075            "const-context RestartPolicy::as_str must resolve to the three \
8076             lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
8077             From<&RestartPolicy> for &'static str impl inherits its \
8078             `'static` lifetime promise from the same accessor the \
8079             owned-input sibling routes through"
8080        );
8081    }
8082
8083    #[test]
8084    fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8085        // Cross-axis partition pin: the paired trait-idiomatic
8086        // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
8087        // campaign-shape) and borrowed-input `From<&RestartPolicy> for
8088        // &'static str` (this lift) forward projections must resolve
8089        // identically on every arm, locking the two input-shape paths
8090        // together so any future detour trips at caixa-core test time.
8091        // Then a witness that a `.iter().map(Into::into)` pipe over
8092        // [`RestartPolicy::ALL`] (whose iterator yields
8093        // `&RestartPolicy`) materializes the three-arm accept-set
8094        // through the borrowed-input axis alone — the exact shape a
8095        // future wasm-operator per-child post-exit restart-decision
8096        // diagnostic line, a future substrate-wide per-arm diagnostic
8097        // column, or a
8098        // `HashMap::<&'static str, RestartPolicy>::from_iter(
8099        //     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
8100        // per-policy lookup reaches through — closing the two-way
8101        // owned/borrowed input-shape symmetry on the forward-projection
8102        // trait-idiomatic axis. Peer of the sibling
8103        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8104        // (64aa742) /
8105        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8106        // (5ab993a) /
8107        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8108        // (807b0b5) /
8109        // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8110        // (e941836) partition pins on the sibling closed-set typed-enum
8111        // discriminator axes — extends the borrowed-input axis
8112        // discipline onto the second-of-two M2 OTP-shape closed-set
8113        // typed enum on the caixa surface (per-child restart-decision
8114        // policy). Also closes the direct two-way `&Self → &'static
8115        // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
8116        // — unlike the peer [`crate::CaixaKind`] axis pair (whose
8117        // forward `From` emits lowercase Portuguese diagnostic bytes
8118        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
8119        // forcing the round-trip through an intermediate wire-vocab
8120        // hop), the [`RestartPolicy::as_str`] emit and
8121        // [`RestartPolicy::from_wire`] parse share the same
8122        // `PascalCase` vocabulary by construction, so the borrowed-
8123        // input forward axis and the reverse axis compose directly.
8124        for &variant in RestartPolicy::ALL {
8125            let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8126            let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
8127            assert_eq!(
8128                owned, borrowed,
8129                "From<RestartPolicy> and From<&RestartPolicy> for \
8130                 &'static str must resolve identically on \
8131                 RestartPolicy::{variant:?} — divergence signals the \
8132                 owned-input and borrowed-input forward-projection paths \
8133                 have drifted onto different emit-sets"
8134            );
8135        }
8136        let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
8137        let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
8138        assert_eq!(
8139            via_iter, via_method,
8140            "`.iter().map(Into::into)` over RestartPolicy::ALL must \
8141             byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
8142             borrowed-input `From<&RestartPolicy> for &'static str` axis \
8143             is what makes the `.iter().map(Into::into)` shape route \
8144             through the substrate-primitive `RestartPolicy::as_str` \
8145             accessor rather than through a per-call-site `.copied()` / \
8146             dereference detour"
8147        );
8148        for variant in RestartPolicy::ALL {
8149            let emitted: &'static str = variant.into();
8150            let re_parsed: Result<RestartPolicy, ()> =
8151                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
8152            assert_eq!(
8153                re_parsed,
8154                Ok(*variant),
8155                "trait-idiomatic borrowed-input forward-projection + \
8156                 reverse-projection axis pair must round-trip \
8157                 &RestartPolicy::{variant:?} through `.into::<&'static \
8158                 str>()` (via the borrowed-input axis) and back through \
8159                 `TryFrom<&str>` — a break signals the borrowed-input \
8160                 forward-emit and reverse-parse axes have drifted onto \
8161                 different vocabularies"
8162            );
8163        }
8164    }
8165
8166    #[test]
8167    fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
8168        // Fail-before-pass-after byte-parity pin on the newly lifted
8169        // `impl From<RestartPolicy> for String` — asserts the
8170        // owned-`String`-returning standard-library trait impl and the
8171        // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
8172        // accessor resolve to the same three-arm emit-set across every
8173        // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
8174        // Rust's standard library does not carry a blanket
8175        // `impl<T: AsRef<str>> From<T> for String` (nor an
8176        // `impl<T: fmt::Display> From<T> for String`), so the
8177        // owned-`String` forward-projection axis is a distinct
8178        // trait-idiomatic surface that a `let key: String =
8179        // policy.into();`-shaped call site reaches through this impl
8180        // and no other — the paired sibling `From<RestartPolicy> for
8181        // &'static str` impl forces every owned-`String` call site
8182        // through an explicit `.to_owned()` / `String::from`
8183        // restatement. Peer of the first-mover
8184        // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
8185        // (7baa18a) — extends the trait-idiomatic owned-`String`
8186        // forward-projection axis onto the second-of-two M2 OTP-shape
8187        // closed-set typed enums on the caixa surface (per-child
8188        // restart-decision-policy sibling on the same M2 `:supervisor`
8189        // slot).
8190        for &variant in RestartPolicy::ALL {
8191            let via_trait: String = <String as From<RestartPolicy>>::from(variant);
8192            let via_method: &'static str = variant.as_str();
8193            assert_eq!(
8194                via_trait.as_str(),
8195                via_method,
8196                "From<RestartPolicy> for String impl must round-trip \
8197                 RestartPolicy::{variant:?} to the same lifted \
8198                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
8199                 returns — divergence signals a silent detour off the \
8200                 substrate-primitive accessor"
8201            );
8202            let via_into: String = variant.into();
8203            assert_eq!(
8204                via_into.as_str(),
8205                via_method,
8206                "Into<String>::into on RestartPolicy::{variant:?} must \
8207                 byte-equal RestartPolicy::as_str on the same input — the \
8208                 blanket-derived Into shape must resolve to the same as_str \
8209                 dispatch as the explicit From impl"
8210            );
8211        }
8212    }
8213
8214    #[test]
8215    fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
8216        // Cross-axis partition pin: the paired trait-idiomatic
8217        // owned-`String` `From<RestartPolicy> for String` (this lift)
8218        // and owned-`&'static str` `From<RestartPolicy> for &'static
8219        // str` (9fb37d0) forward projections must resolve identically
8220        // on every arm, locking the two return-type-shape paths
8221        // together so any future detour trips at caixa-core test time.
8222        // Also byte-parity witness against the sibling
8223        // [`ToString::to_string`] surface routed through
8224        // [`std::fmt::Display`] — the three owned-heap-string paths
8225        // (`.into::<String>()`, `String::from`, `.to_string()`) must
8226        // resolve identically on every arm so a future consumer that
8227        // picks any of the three lands on the same lifted
8228        // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
8229        // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
8230        // that materializes the three-arm accept-set through the
8231        // owned-`String` axis alone — the exact shape a future
8232        // wasm-operator per-child post-exit restart-decision
8233        // diagnostic line composer or a
8234        // `HashMap::<String, RestartPolicy>::from_iter(
8235        //     RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
8236        // owned-key per-policy lookup reaches through — closing the
8237        // owned-`String` forward-projection axis's iterator-pipe
8238        // shape. Then a direct round-trip witness through the paired
8239        // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
8240        // owned-`String`'s [`String::as_str`] borrow that closes the
8241        // two-way `Self → String → Self` round-trip on the trait-
8242        // idiomatic owned-`String` forward + reverse axis pair —
8243        // unlike the peer [`crate::CaixaKind`] axis pair (whose
8244        // forward `From` emits lowercase Portuguese diagnostic bytes
8245        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
8246        // forcing the round-trip through an intermediate wire-vocab
8247        // hop), the [`RestartPolicy::as_str`] emit and
8248        // [`RestartPolicy::from_wire`] parse share the same
8249        // `PascalCase` vocabulary by construction, so the owned-
8250        // `String` forward axis and the reverse axis compose directly.
8251        for &variant in RestartPolicy::ALL {
8252            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
8253            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8254            assert_eq!(
8255                owned_string.as_str(),
8256                owned_static,
8257                "From<RestartPolicy> for String and From<RestartPolicy> \
8258                 for &'static str must resolve identically on \
8259                 RestartPolicy::{variant:?} — divergence signals the \
8260                 owned-`String` and owned-`&'static str` forward-projection \
8261                 return-type-shape paths have drifted onto different \
8262                 emit-sets"
8263            );
8264            let via_to_string: String = variant.to_string();
8265            assert_eq!(
8266                owned_string, via_to_string,
8267                "From<RestartPolicy> for String must byte-equal \
8268                 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
8269                 divergence signals the trait-idiomatic owned-`String` \
8270                 forward-projection axis and the ToString-through-Display \
8271                 axis have drifted onto different emit-sets"
8272            );
8273        }
8274        let via_iter: Vec<String> = RestartPolicy::ALL
8275            .iter()
8276            .copied()
8277            .map(String::from)
8278            .collect();
8279        let via_method: Vec<String> = RestartPolicy::ALL
8280            .iter()
8281            .map(|p| p.as_str().to_owned())
8282            .collect();
8283        assert_eq!(
8284            via_iter, via_method,
8285            "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
8286             must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
8287             every arm — the owned-`String` `From<RestartPolicy> for \
8288             String` axis is what makes the `String::from` composition \
8289             route through the substrate-primitive `RestartPolicy::as_str` \
8290             accessor rather than through a per-call-site `.to_owned()` / \
8291             `String::from(policy.as_str())` detour"
8292        );
8293        for &variant in RestartPolicy::ALL {
8294            let emitted: String = variant.into();
8295            let re_parsed: Result<RestartPolicy, ()> =
8296                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
8297            assert_eq!(
8298                re_parsed,
8299                Ok(variant),
8300                "trait-idiomatic owned-`String` forward-projection + \
8301                 reverse-projection axis pair must round-trip \
8302                 RestartPolicy::{variant:?} through `.into::<String>()` \
8303                 and back through `TryFrom<&str>` on the owned-`String`'s \
8304                 String::as_str borrow — a break signals the owned-`String` \
8305                 forward-emit and reverse-parse axes have drifted onto \
8306                 different vocabularies"
8307            );
8308        }
8309    }
8310
8311    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
8312
8313    #[test]
8314    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
8315        // The fail-before-pass-after pin: pre-lift there was no
8316        // single-source binding between the [`RestartPolicy`] variant
8317        // name the un-`rename`d `Serialize` derive emits under
8318        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
8319        // byte-string every downstream cluster-side dispatcher (the
8320        // future wasm-operator's per-child post-exit restart-decision
8321        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8322        // materializer's admission-time enum-arm bind, the
8323        // `caixa-operator`'s hierarchical reconciliation scheduler's
8324        // per-child-policy fan-out) probes verbatim. A future
8325        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
8326        // or a per-variant `#[serde(rename = "…")]` override, or a
8327        // variant rename in the source — would silently rebrand the
8328        // emitted scalar under one spelling while every downstream
8329        // dispatcher still probed the other, with the failure surfacing
8330        // at the operator's reconcile posture (children coming up under
8331        // the `default()` `Permanent` arm rather than the typed slot's
8332        // declared policy — a `:temporary` `oneShot` child would be
8333        // restarted on clean exit, treating the successful-completion
8334        // signal as failure and re-running the completion-terminal
8335        // one-shot indefinitely; a `:transient` child that clean-exited
8336        // would be restarted, masking the clean-completion contract)
8337        // far from the source rebrand commit and with no field naming
8338        // the drift. Pinning the two paths (the `Serialize` derive's
8339        // serialized string AND the [`RestartPolicy::as_str`] helper)
8340        // to the same three lifted
8341        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
8342        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
8343        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
8344        // byte-strings makes any future drift on either endpoint fail
8345        // here at caixa-core build time. Peer of the sibling
8346        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
8347        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
8348        // and the M3
8349        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
8350        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
8351        // same three-path-convergence discipline, extended to close the
8352        // third OTP-shaped closed-enum discriminator axis on the caixa
8353        // typed surface (per-child restart-decision policy).
8354        for (variant, expected) in [
8355            (
8356                RestartPolicy::Permanent,
8357                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8358            ),
8359            (
8360                RestartPolicy::Temporary,
8361                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8362            ),
8363            (
8364                RestartPolicy::Transient,
8365                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8366            ),
8367        ] {
8368            let json = serde_json::to_string(&variant).unwrap();
8369            assert_eq!(
8370                json,
8371                format!("\"{expected}\""),
8372                "RestartPolicy::{variant:?} must serialize to {expected:?}"
8373            );
8374            assert_eq!(
8375                variant.as_str(),
8376                expected,
8377                "RestartPolicy::{variant:?}.as_str() must return the lifted \
8378                 SUPERVISOR_CHILD_RESTART_* constant"
8379            );
8380        }
8381    }
8382
8383    #[test]
8384    fn supervisor_child_restart_consts_are_pairwise_distinct() {
8385        // Cross-arm drift-detection pin: a future collapse of two
8386        // canonical variant byte-strings onto the same value (e.g. an
8387        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
8388        // to also read `"Permanent"`) would silently reroute every
8389        // downstream operator's per-child-policy dispatch onto the
8390        // sibling arm's reconcile branch and pass every propagation-probe
8391        // test that expected only the stale arm's value — a `:transient`
8392        // child would come up under the `:permanent` restart-decision
8393        // posture on every subsequent clean exit, so a completion-terminal
8394        // child would be restarted indefinitely against its declared
8395        // policy. Peer of the sibling
8396        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
8397        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
8398        // and the four-way distinct pin
8399        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
8400        // top-level `SUPERVISOR_KEY_*` axis.
8401        let all = [
8402            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8403            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8404            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8405        ];
8406        for (i, a) in all.iter().enumerate() {
8407            for (j, b) in all.iter().enumerate() {
8408                if i != j {
8409                    assert_ne!(
8410                        a, b,
8411                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
8412                         — got duplicate {a:?} at indices {i} and {j}",
8413                    );
8414                }
8415            }
8416        }
8417    }
8418
8419    #[test]
8420    fn restart_policy_display_routes_through_as_str_helper() {
8421        // The fail-before-pass-after pin on the first half of the
8422        // three-path convergence: pre-convergence [`RestartPolicy`]
8423        // carried a [`std::fmt::Display`] surface via its
8424        // `#[discriminant(also_display)]` gen-platform derive route,
8425        // which arrived kebab-case as `"permanent"` / `"temporary"`
8426        // / `"transient"` on this three-arm enum (whose variant
8427        // names each collapse to their own lowercase form under the
8428        // kebab-case transform) while the wire format ran as
8429        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
8430        // through the un-`rename`d serde derive. Every consumer
8431        // reaching for a policy byte-string past the wire format had
8432        // to pick between three paths ([`RestartPolicy::as_str`],
8433        // the `Serialize` derive's serialized string, or
8434        // `format!("{v}")` on the discriminant-Display route), any
8435        // two of which a future variant rename or
8436        // `#[serde(rename_all = "kebab-case")]` attribute would
8437        // silently desynchronize. Wiring [`std::fmt::Display`]
8438        // through [`RestartPolicy::as_str`] closes the third path:
8439        // every `format!("{v}")` call reaches the same lifted
8440        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
8441        // wire format and the [`RestartPolicy::as_str`] helper
8442        // already route through, so a future variant rename lands at
8443        // exactly one place. Pin the routing here so a future
8444        // `impl std::fmt::Display for RestartPolicy`
8445        // reimplementation that hand-rolls the arms instead of
8446        // delegating to [`RestartPolicy::as_str`] fails at
8447        // caixa-core build time. Peer of the sibling
8448        // [`restart_strategy_display_routes_through_as_str_helper`]
8449        // on the per-supervisor sibling-restart-strategy axis and
8450        // the M3
8451        // `placement_strategy_display_routes_through_as_str_helper`
8452        // (cc8f749) — the third of three OTP-shape closed-enum
8453        // discriminator axes on the caixa typed surface now
8454        // converged onto the same three-path
8455        // (Display → as_str → lifted const) discipline.
8456        for variant in [
8457            RestartPolicy::Permanent,
8458            RestartPolicy::Temporary,
8459            RestartPolicy::Transient,
8460        ] {
8461            assert_eq!(
8462                variant.to_string(),
8463                variant.as_str(),
8464                "RestartPolicy::{variant:?} Display must route through \
8465                 RestartPolicy::as_str (single source of truth: the lifted \
8466                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
8467            );
8468        }
8469    }
8470
8471    #[test]
8472    fn restart_policy_display_matches_serialized_wire_byte_string() {
8473        // The fail-before-pass-after pin on the second half of the
8474        // three-path convergence: `Display` (user-facing text) agrees
8475        // byte-for-byte with the `Serialize` derive's wire format
8476        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
8477        // scalar) on every variant. Pre-convergence the two paths
8478        // were structurally independent — a future
8479        // `#[serde(rename_all = "kebab-case")]` attribute on the
8480        // enum would silently rebrand the emitted wire scalar
8481        // (`permanent`, `temporary`, `transient`) while every
8482        // consumer that pretty-prints the policy (the future
8483        // wasm-operator's per-child post-exit restart-decision
8484        // diagnostic line, the future `feira app graph` per-child
8485        // restart column, the future M4
8486        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
8487        // per-child admission-webhook rejection body) would still
8488        // emit the PascalCase form the `as_str` / `Display` route
8489        // returns, with the mismatch surfacing at consumer parse
8490        // time / operator dispatch time far from the source rebrand
8491        // commit. Pin the two paths byte-for-byte here so any future
8492        // serde-attribute or variant-rename drift is a
8493        // caixa-core-build-time test failure at this call, not a
8494        // silent per-consumer dispatch miss. Peer of the sibling
8495        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
8496        // on the per-supervisor sibling-restart-strategy axis and
8497        // the M3
8498        // `placement_strategy_display_matches_serialized_wire_byte_string`
8499        // (cc8f749).
8500        for variant in [
8501            RestartPolicy::Permanent,
8502            RestartPolicy::Temporary,
8503            RestartPolicy::Transient,
8504        ] {
8505            let wire = serde_json::to_string(&variant).unwrap();
8506            let unquoted = wire
8507                .strip_prefix('"')
8508                .and_then(|s| s.strip_suffix('"'))
8509                .expect("serialized RestartPolicy is a JSON string");
8510            assert_eq!(
8511                variant.to_string(),
8512                unquoted,
8513                "RestartPolicy::{variant:?} Display byte-string must match the \
8514                 Serialize derive's wire byte-string (three-path convergence: \
8515                 Display + as_str + Serialize all resolve to the same \
8516                 SUPERVISOR_CHILD_RESTART_* const)"
8517            );
8518        }
8519    }
8520
8521    #[test]
8522    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
8523        // Fail-before-pass-after byte-parity pin on the lifted
8524        // `impl AsRef<str> for RestartPolicy` — asserts the
8525        // standard-library trait impl and the substrate-primitive
8526        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
8527        // to the same `&str` per instance across the three-arm
8528        // closed set, so any future silent detour that routes the
8529        // impl through a divergent projection (a per-arm inline
8530        // `match self { RestartPolicy::Permanent => "Permanent", … }`
8531        // re-inlining that opens a compile-time link to the un-lifted
8532        // arm-literal, a swap onto the kebab-case
8533        // [`gen_platform::Discriminant`] catalog identity that would
8534        // collide the wire axis with the dispatcher-catalog axis) trips
8535        // at caixa-core test time under `PartialEq` rather than at a
8536        // downstream `impl AsRef<str>`-bound consumer's silent split.
8537        // Sweeps every one of the three arms
8538        // [`RestartPolicy::ALL`] carries so no arm's projection is
8539        // covered only by the sibling wire-format `Serialize` derive
8540        // path. Peer of the sibling
8541        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
8542        // (63eb1a4) on the paired per-supervisor sibling-restart-
8543        // strategy axis and the [`crate::CaixaVersion`]
8544        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
8545        // top-level `:versao` typed newtype — the three pins together
8546        // cover the substrate primitive's `AsRef<str>` projection axis
8547        // on the paired newtype + M2 closed-set-typed-enum surface.
8548        for &variant in RestartPolicy::ALL {
8549            assert_eq!(
8550                <RestartPolicy as AsRef<str>>::as_ref(&variant),
8551                variant.as_str(),
8552                "AsRef<str> impl on RestartPolicy::{variant:?} must \
8553                 byte-equal RestartPolicy::as_str on the same instance \
8554                 — divergence signals a silent detour off the substrate-\
8555                 primitive accessor"
8556            );
8557        }
8558    }
8559
8560    #[test]
8561    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
8562        // Fail-before-pass-after byte-parity pin on the three-path
8563        // convergence discipline the M2 per-child-restart-policy
8564        // primitive now carries on the `&str`-projection axis:
8565        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
8566        // lifted impl), `format!("{v}")` (the pre-existing
8567        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
8568        // primitive `pub const fn` accessor both trait impls delegate
8569        // through) must resolve to the same byte-string on every
8570        // instance across the three-arm closed set. Refuses any future
8571        // divergence between the two trait impls (a stray
8572        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
8573        // rather than delegating through the shared accessor; a
8574        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
8575        // literal cascade) that would silently split the two
8576        // projection paths of the same closed-set typed enum. Mirrors
8577        // the sibling three-path-convergence discipline the peer
8578        // [`RestartStrategy`] typed enum carries on its
8579        // `AsRef<str>` / `Display` / `as_str` triple
8580        // (supervisor.rs pin
8581        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
8582        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
8583        // carries on the same triple (version.rs pin
8584        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
8585        // 16d5c7e).
8586        for &variant in RestartPolicy::ALL {
8587            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
8588            let via_display: String = format!("{variant}");
8589            let via_accessor: &str = variant.as_str();
8590            assert_eq!(via_as_ref, via_accessor);
8591            assert_eq!(via_display, via_accessor);
8592            assert_eq!(via_as_ref, via_display.as_str());
8593        }
8594    }
8595
8596    #[test]
8597    fn restart_policy_all_enumerates_every_variant_exactly_once() {
8598        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
8599        // exhaustive-iteration surface: every variant appears exactly
8600        // once, and the slice length matches the arm count of the
8601        // closed set. Every consumer that walks the accepted-policy
8602        // set (a future `feira supervisor --restart …` CLI-side
8603        // arg-parse's "did you mean" hint, a future M4 admission-
8604        // webhook's per-child rejection body naming the accepted-
8605        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
8606        // projection consumers that iterate the accept-set for
8607        // diagnostic rendering) reads through this slice, so a future
8608        // arm addition that grows the enum but forgets to grow
8609        // [`Self::ALL`] silently truncates every downstream consumer's
8610        // accept-set at the same pre-addition boundary — this pin
8611        // fails at caixa-core build time on the pairwise-distinct +
8612        // arm-count invariants.
8613        //
8614        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
8615        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
8616        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
8617        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
8618        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
8619        // pins on the peer closed-set typed-enum axes.
8620        let all: &[RestartPolicy] = RestartPolicy::ALL;
8621        assert_eq!(
8622            all.len(),
8623            3,
8624            "RestartPolicy::ALL must enumerate every variant of the \
8625             three-arm closed set (Permanent, Temporary, Transient); \
8626             got {all:?}"
8627        );
8628        for (i, a) in all.iter().enumerate() {
8629            for (j, b) in all.iter().enumerate() {
8630                if i != j {
8631                    assert_ne!(
8632                        a, b,
8633                        "RestartPolicy::ALL must carry every variant exactly \
8634                         once — got duplicate {a:?} at indices {i} and {j}"
8635                    );
8636                }
8637            }
8638        }
8639        for variant in [
8640            RestartPolicy::Permanent,
8641            RestartPolicy::Temporary,
8642            RestartPolicy::Transient,
8643        ] {
8644            assert!(
8645                all.contains(&variant),
8646                "RestartPolicy::ALL must contain {variant:?} — a future arm \
8647                 addition that grows the enum but forgets to grow the ALL slice \
8648                 silently truncates every downstream consumer's accept-set at \
8649                 the pre-addition boundary"
8650            );
8651        }
8652    }
8653
8654    #[test]
8655    fn restart_policy_from_wire_accepts_every_lifted_constant() {
8656        // Fail-before-pass-after pin on the forward accept-set of the
8657        // [`RestartPolicy::from_wire`] reverse projection: every
8658        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
8659        // constant the [`RestartPolicy::as_str`] emitter walks parses
8660        // back to its paired variant. Any future arm addition that
8661        // grows the emitter's `as_str` match but forgets to grow the
8662        // parser's `from_wire` match silently splits the two halves of
8663        // the round-trip — the wire byte-string one non-serde consumer
8664        // parses from the one the emitter wrote — with the failure
8665        // surfacing at the operator's reconcile posture (a `:temporary`
8666        // `oneShot` child restarted on clean exit, a `:transient` child
8667        // restarted after clean completion) far from the rebrand
8668        // commit. Pinning the three-arm accept-set here catches the
8669        // drift at caixa-core build time.
8670        //
8671        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
8672        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
8673        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
8674        // accept-set pins on the peer closed-set typed-enum `str → Self`
8675        // axes.
8676        for (wire, expected) in [
8677            (
8678                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8679                RestartPolicy::Permanent,
8680            ),
8681            (
8682                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8683                RestartPolicy::Temporary,
8684            ),
8685            (
8686                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8687                RestartPolicy::Transient,
8688            ),
8689        ] {
8690            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
8691                panic!(
8692                    "RestartPolicy::from_wire({wire:?}) must accept every \
8693                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
8694                     lifted canonical byte-string that RestartPolicy::{expected:?} \
8695                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
8696                )
8697            });
8698            assert_eq!(
8699                parsed, expected,
8700                "RestartPolicy::from_wire({wire:?}) must return \
8701                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
8702            );
8703        }
8704    }
8705
8706    #[test]
8707    fn restart_policy_from_wire_round_trips_through_as_str() {
8708        // Fail-before-pass-after pin on the closed round-trip between
8709        // the forward [`RestartPolicy::as_str`] emitter and the
8710        // reverse [`RestartPolicy::from_wire`] parser: for every
8711        // variant in [`RestartPolicy::ALL`], parsing the emitter's
8712        // output must return exactly the same variant. Any per-arm
8713        // divergence — a future arm added to `as_str` but not
8714        // `from_wire`, an accidental copy-paste flip in one but not
8715        // the other — silently splits the emit and parse halves and
8716        // the failure surfaces at consumer parse time far from the
8717        // drift site. The `ALL`-iterating shape means a future arm
8718        // addition picks up the coverage by construction.
8719        //
8720        // Peer of the sibling
8721        // [`restart_strategy_from_wire_round_trips_through_as_str`]
8722        // (4eec29c) round-trip pin on
8723        // [`RestartStrategy::from_wire`] and the M3
8724        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
8725        // (18c7342) round-trip pin on
8726        // [`crate::aplicacao::PlacementStrategy::from_wire`].
8727        for &variant in RestartPolicy::ALL {
8728            let wire = variant.as_str();
8729            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
8730                panic!(
8731                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
8732                     must be Some({variant:?}) — the two halves of the round-trip \
8733                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
8734                     got None on wire byte-string {wire:?}"
8735                )
8736            });
8737            assert_eq!(
8738                parsed, variant,
8739                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
8740                 must round-trip to the same variant; got {parsed:?}"
8741            );
8742        }
8743    }
8744
8745    #[test]
8746    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
8747        // Fail-before-pass-after pin on the closed-set refusal
8748        // discipline of [`RestartPolicy::from_wire`]: every
8749        // byte-string outside the three-arm accept-set returns `None`
8750        // rather than silently collapsing onto the [`Default`]
8751        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
8752        // exercised here sweeps the load-bearing drift shapes: the
8753        // empty string (a stripped serde-attribute drift), all-
8754        // whitespace strings (the canonical text-editor accidental
8755        // padding shape), the kebab-case dispatcher-catalog identities
8756        // (`"permanent"` / `"temporary"` / `"transient"` — the
8757        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
8758        // accept-set, which parses the *other* axis of this enum's
8759        // two-axis split and must not leak into the `from_wire`
8760        // PascalCase-wire accept-set — a lowercase leak here would
8761        // silently accept the operator's kebab-case
8762        // dispatcher-catalog probe under the wire-axis parser and mis-
8763        // route a `:permanent` intent), the padded canonical scalar
8764        // (`" Permanent "`), the trailing-newline shapes
8765        // (`"Permanent\n"`), the uppercase-single-word forms
8766        // (`"PERMANENT"`), and neighboring-but-unknown arms
8767        // (`"Restart"` — the canonical typo direction toward the
8768        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
8769        //
8770        // Peer of the sibling
8771        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
8772        // (4eec29c) +
8773        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
8774        // (2aa6d23) +
8775        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
8776        // (18c7342) refusal pins on the peer closed-set typed-enum
8777        // axes.
8778        for bad in [
8779            "",
8780            " ",
8781            "\n",
8782            "\t",
8783            "permanent",
8784            "temporary",
8785            "transient",
8786            "PERMANENT",
8787            "TEMPORARY",
8788            "TRANSIENT",
8789            "Permanents",
8790            "Permanent ",
8791            " Permanent",
8792            " Transient ",
8793            "Permanent\n",
8794            "perma",
8795            "Trans",
8796            "OneForOne",
8797            "Restart",
8798            "?",
8799        ] {
8800            assert!(
8801                RestartPolicy::from_wire(bad).is_none(),
8802                "RestartPolicy::from_wire({bad:?}) must return None — the \
8803                 parser's accept-set is exactly the three RestartPolicy::as_str \
8804                 outputs (Permanent, Temporary, Transient), and this \
8805                 byte-string is outside that closed set"
8806            );
8807        }
8808    }
8809
8810    #[test]
8811    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
8812        // Fail-before-pass-after pin on the fourth path of the four-path
8813        // convergence: `from_wire` (the reverse projection) inverts the
8814        // `Serialize` derive's wire byte-string on every variant.
8815        // Together with the pre-existing three-path convergence
8816        // (`Display` + `as_str` + `Serialize` all resolve to the same
8817        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
8818        // pinned by
8819        // [`restart_policy_display_matches_serialized_wire_byte_string`])
8820        // this closes the round-trip: the wire byte-string the
8821        // `Serialize` derive emits parses back to the same variant
8822        // through `from_wire`, so any future serde-attribute or variant-
8823        // rename drift on the emit half now surfaces as a matched drift
8824        // on the parse half at caixa-core build time — the two halves
8825        // migrate as a unit through the lifted consts on any future
8826        // rename, and the round-trip cannot silently split.
8827        //
8828        // Peer of the sibling
8829        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8830        // (4eec29c) wire-format pin on
8831        // [`RestartStrategy::from_wire`] and the M3
8832        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8833        // (18c7342) wire-format pin on
8834        // [`crate::aplicacao::PlacementStrategy::from_wire`].
8835        for &variant in RestartPolicy::ALL {
8836            let wire = serde_json::to_string(&variant).unwrap();
8837            let unquoted = wire
8838                .strip_prefix('"')
8839                .and_then(|s| s.strip_suffix('"'))
8840                .expect("serialized RestartPolicy is a JSON string");
8841            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
8842                panic!(
8843                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
8844                     Serialize derive's wire byte-string for \
8845                     RestartPolicy::{variant:?} — the four-path convergence \
8846                     (Display + as_str + Serialize + from_wire) resolves through \
8847                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
8848                )
8849            });
8850            assert_eq!(
8851                parsed, variant,
8852                "RestartPolicy::from_wire of the Serialize derive's wire \
8853                 byte-string for RestartPolicy::{variant:?} must round-trip \
8854                 to the same variant; got {parsed:?}"
8855            );
8856        }
8857    }
8858
8859    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
8860    //
8861    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
8862    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
8863    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
8864    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
8865    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
8866    // the peer per-`:upgrade-from :from` axis. The three pins jointly
8867    // brace the accessor against every future silent detour that would
8868    // desynchronize it from the raw `.caixa` field access every consumer
8869    // previously open-coded.
8870
8871    #[test]
8872    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
8873        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
8874        // [`ChildSpec::nome`] must return the `:children :caixa` field
8875        // byte-for-byte across every DNS-1123-label value the upstream
8876        // [`crate::render::require_valid_dns_1123_label`] gate at
8877        // `SupervisorSpec::validate` admits. Peer of the sibling
8878        // `membro_nome_returns_caixa_byte_equal_across_permutations`
8879        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
8880        // substrate-primitive accessor must byte-equal the raw field
8881        // access verbatim across every author-declared value" discipline
8882        // extended to the M2 supervisor-tree per-`:children` arm. Pins
8883        // against a future silent detour that re-normalized the child
8884        // identity (an accidental `.to_lowercase()` — every `:children
8885        // :caixa` is validated as a DNS-1123 label upstream, so any
8886        // re-normalization is redundant + a drift surface between the
8887        // validator and the accessor), a namespace-prefix rewrite (an
8888        // accidental `format!("{namespace}/{caixa}")` per-CR
8889        // fully-qualified rewrite that didn't land on the peer axes), or
8890        // a per-cluster alias stamp the future wasm-operator's
8891        // hierarchical reconciliation scheduler authors on one consumer
8892        // without the others. Five values sweep the accept-set the
8893        // DNS-1123 gate upstream admits (short single-word / dashed /
8894        // v-suffixed / mixed-digit child names).
8895        for name in [
8896            "worker",
8897            "cache-server",
8898            "scratch-job",
8899            "orders-v2",
8900            "session-8080",
8901        ] {
8902            let c = ChildSpec {
8903                caixa: name.into(),
8904                versao: "^0.1".into(),
8905                restart: RestartPolicy::Permanent,
8906            };
8907            assert_eq!(
8908                c.nome(),
8909                name,
8910                "ChildSpec::nome must return :children :caixa verbatim \
8911                 (got {:?}, expected {name:?})",
8912                c.nome(),
8913            );
8914            assert_eq!(
8915                c.nome(),
8916                c.caixa.as_str(),
8917                "ChildSpec::nome must byte-equal the .caixa field access",
8918            );
8919        }
8920    }
8921
8922    #[test]
8923    fn child_spec_nome_borrows_from_caixa_storage() {
8924        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
8925        // `&str` slice that borrows from the typed slot's own [`String`]
8926        // storage — same-address invariant with `c.caixa.as_str()`. Pins
8927        // against a future silent detour that allocated a fresh `String`
8928        // (`self.caixa.clone()` in the body would type-check but silently
8929        // drop the borrow, and every downstream consumer that assumed
8930        // the returned slice outlives `&self` would break on a stale-
8931        // reference use-after-free — the [`crate::render::insert_first_seen`]
8932        // dedup key at [`SupervisorSpec::validate`], the
8933        // [`validate_no_self_supervision`] equality check against the
8934        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
8935        // borrow — each would silently misbehave if this accessor
8936        // produced a detached copy). Peer of the sibling
8937        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
8938        // M3 per-`:membros` axis and the
8939        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
8940        // first M2 slot scalar accessor.
8941        let c = ChildSpec {
8942            caixa: "worker".into(),
8943            versao: "^0.1".into(),
8944            restart: RestartPolicy::Permanent,
8945        };
8946        let name = c.nome();
8947        let caixa_slice = c.caixa.as_str();
8948        assert_eq!(
8949            name.as_ptr(),
8950            caixa_slice.as_ptr(),
8951            "ChildSpec::nome must borrow from the .caixa String's backing \
8952             storage — a fresh allocation here means the accessor no \
8953             longer names the substrate-primitive typed dispatch and \
8954             every downstream consumer would silently carry a detached \
8955             copy",
8956        );
8957        assert_eq!(
8958            name.len(),
8959            caixa_slice.len(),
8960            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
8961             as well as in address",
8962        );
8963    }
8964
8965    #[test]
8966    fn validate_gates_child_nome_through_lifted_accessor() {
8967        // Bilateral coherence pin: every `:children :caixa` that
8968        // [`SupervisorSpec::validate`] accepts is one
8969        // [`crate::render::require_valid_dns_1123_label`] accepts on the
8970        // accessor-projected value, and vice versa on the reject side.
8971        // This closes the "the validator reads through the accessor"
8972        // contract structurally — a future silent detour that made the
8973        // accessor return a different byte-string than the validator
8974        // gates against would surface here as a coverage mismatch, not
8975        // as an apply-time DNS-1123 rejection at
8976        // `metadata.name: Invalid value` far from the caixa.lisp source.
8977        // Peer of the M2 sibling
8978        // `validate_parses_prior_versao_through_lifted_accessor`
8979        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
8980        // `validate_membros` peer discipline.
8981        //
8982        // Accept-set sweep: five DNS-1123-label values the upstream gate
8983        // admits.
8984        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
8985            let s = SupervisorSpec {
8986                children: vec![ChildSpec {
8987                    caixa: ok_name.into(),
8988                    versao: "^0.1".into(),
8989                    restart: RestartPolicy::Permanent,
8990                }],
8991                ..SupervisorSpec::default()
8992            };
8993            s.validate().unwrap_or_else(|e| {
8994                panic!(
8995                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
8996                     (upstream DNS-1123 gate accepts it): got {e:?}",
8997                );
8998            });
8999            let c = ChildSpec {
9000                caixa: ok_name.into(),
9001                versao: "^0.1".into(),
9002                restart: RestartPolicy::Permanent,
9003            };
9004            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
9005                .unwrap_or_else(|()| {
9006                    panic!(
9007                        "require_valid_dns_1123_label must accept the accessor-projected \
9008                     :children :caixa {ok_name:?}",
9009                    );
9010                });
9011        }
9012        // Reject-set sweep: five DNS-1123-label-violating shapes the
9013        // upstream gate refuses (empty / uppercase / underscore / dot /
9014        // leading-hyphen). Every rejection at the validator must
9015        // correspond to a rejection when the accessor's projected value
9016        // is fed back through the shared gate.
9017        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
9018            let s = SupervisorSpec {
9019                children: vec![ChildSpec {
9020                    caixa: bad_name.into(),
9021                    versao: "^0.1".into(),
9022                    restart: RestartPolicy::Permanent,
9023                }],
9024                ..SupervisorSpec::default()
9025            };
9026            let err = s.validate().unwrap_err();
9027            assert!(
9028                matches!(
9029                    err,
9030                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
9031                ),
9032                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
9033                 via the DNS-1123 gate: got {err:?}",
9034            );
9035            let c = ChildSpec {
9036                caixa: bad_name.into(),
9037                versao: "^0.1".into(),
9038                restart: RestartPolicy::Permanent,
9039            };
9040            assert!(
9041                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
9042                    .is_err(),
9043                "require_valid_dns_1123_label must reject the accessor-projected \
9044                 :children :caixa {bad_name:?}",
9045            );
9046        }
9047    }
9048
9049    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
9050    //
9051    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
9052    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
9053    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
9054    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
9055    // trio on the peer per-`:children` `String`-carry axis. The three pins
9056    // jointly brace the accessor against every future silent detour that
9057    // would desynchronize it from the raw `.versao` field access the
9058    // requirement gate + error carrier previously open-coded.
9059    //
9060    // Closes the last unlifted per-`:children` `String`-carry axis: the
9061    // pair (`nome`, `versao_requirement`) now jointly projects the
9062    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
9063    // consumer that fans on per-child identity + version pin reads,
9064    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
9065    // pair discipline verbatim.
9066    #[test]
9067    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
9068        // The canonical per-`:children` child-`:versao`-scalar pin:
9069        // [`ChildSpec::versao_requirement`] must return the `:children
9070        // :versao` field byte-for-byte across every Cargo-shaped semver
9071        // requirement value the upstream
9072        // [`crate::render::require_valid_versao_requirement`] gate admits.
9073        // Peer of the sibling
9074        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
9075        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
9076        // substrate-primitive accessor must byte-equal the raw field
9077        // access verbatim across every author-declared value" discipline
9078        // extended to the M2 supervisor-tree per-`:children` arm. Pins
9079        // against a future silent detour that re-canonicalized the
9080        // requirement (an accidental `.to_string()` via
9081        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
9082        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
9083        // silently drifted the error carrier's quoted requirement away
9084        // from the source `caixa.lisp`, an accidental whitespace trim on
9085        // `"^ 0.1"` that no consumer ever produced from the field-access
9086        // side, an accidental per-cluster lacre-projected concrete-version
9087        // rewrite that didn't land on the peer requirement-gate call).
9088        // Five values sweep the accept-set the shared
9089        // [`crate::render::require_valid_versao_requirement`] gate admits
9090        // (caret / tilde / exact / wildcard / bare-major).
9091        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
9092            let c = ChildSpec {
9093                caixa: "worker".into(),
9094                versao: req.into(),
9095                restart: RestartPolicy::Permanent,
9096            };
9097            assert_eq!(
9098                c.versao_requirement(),
9099                req,
9100                "ChildSpec::versao_requirement must return :children :versao \
9101                 verbatim (got {:?}, expected {req:?})",
9102                c.versao_requirement(),
9103            );
9104            assert_eq!(
9105                c.versao_requirement(),
9106                c.versao.as_str(),
9107                "ChildSpec::versao_requirement must byte-equal the .versao \
9108                 field access",
9109            );
9110        }
9111    }
9112
9113    #[test]
9114    fn child_spec_versao_requirement_borrows_from_versao_storage() {
9115        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
9116        // return a `&str` slice that borrows from the typed slot's own
9117        // [`String`] storage — same-address invariant with
9118        // `c.versao.as_str()`. Pins against a future silent detour that
9119        // allocated a fresh `String` (`self.versao.clone()` in the body
9120        // would type-check but silently drop the borrow, and every
9121        // downstream consumer that assumed the returned slice outlives
9122        // `&self` — the [`crate::render::require_valid_versao_requirement`]
9123        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
9124        // `.to_string()` carrier's byte-length assumption — would silently
9125        // misbehave if this accessor produced a detached copy). Peer of
9126        // the sibling `child_spec_nome_borrows_from_caixa_storage`
9127        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
9128        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
9129        // pin on the peer per-`:membros` `:versao` axis.
9130        let c = ChildSpec {
9131            caixa: "worker".into(),
9132            versao: "^0.1".into(),
9133            restart: RestartPolicy::Permanent,
9134        };
9135        let req = c.versao_requirement();
9136        let versao_slice = c.versao.as_str();
9137        assert_eq!(
9138            req.as_ptr(),
9139            versao_slice.as_ptr(),
9140            "ChildSpec::versao_requirement must borrow from the .versao \
9141             String's backing storage — a fresh allocation here means the \
9142             accessor no longer names the substrate-primitive typed \
9143             dispatch and every downstream consumer would silently carry \
9144             a detached copy",
9145        );
9146        assert_eq!(
9147            req.len(),
9148            versao_slice.len(),
9149            "ChildSpec::versao_requirement and .versao.as_str() must \
9150             byte-equal in length as well as in address",
9151        );
9152    }
9153
9154    #[test]
9155    fn validate_gates_child_versao_through_lifted_accessor() {
9156        // Bilateral coherence pin: every `:children :versao` that
9157        // [`SupervisorSpec::validate`] accepts is one
9158        // [`crate::render::require_valid_versao_requirement`] accepts on
9159        // the accessor-projected value, and vice versa on the reject side.
9160        // This closes the "the validator reads through the accessor"
9161        // contract structurally — a future silent detour that made the
9162        // accessor return a different byte-string than the validator gates
9163        // against would surface here as a coverage mismatch, not as a
9164        // resolver-time semver-parse rejection at lacre-closure time far
9165        // from the caixa.lisp source. Peer of the sibling
9166        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
9167        // the per-`:children :caixa` axis and the M2
9168        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
9169        // on the peer per-`:upgrade-from :from` axis.
9170        //
9171        // Accept-set sweep: five Cargo-shaped semver requirement values
9172        // the upstream gate admits (caret / tilde / exact / wildcard /
9173        // bare-major).
9174        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
9175            let s = SupervisorSpec {
9176                children: vec![ChildSpec {
9177                    caixa: "worker".into(),
9178                    versao: ok_req.into(),
9179                    restart: RestartPolicy::Permanent,
9180                }],
9181                ..SupervisorSpec::default()
9182            };
9183            s.validate().unwrap_or_else(|e| {
9184                panic!(
9185                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
9186                     (upstream versao-requirement gate accepts it): got {e:?}",
9187                );
9188            });
9189            let c = ChildSpec {
9190                caixa: "worker".into(),
9191                versao: ok_req.into(),
9192                restart: RestartPolicy::Permanent,
9193            };
9194            crate::render::require_valid_versao_requirement(
9195                c.versao_requirement(),
9196                || (),
9197                |_reason| (),
9198            )
9199            .unwrap_or_else(|()| {
9200                panic!(
9201                    "require_valid_versao_requirement must accept the accessor-projected \
9202                     :children :versao {ok_req:?}",
9203                );
9204            });
9205        }
9206        // Reject-set sweep: five requirement-violating shapes the upstream
9207        // gate refuses. The empty string closes the empty-first arm of the
9208        // shared [`crate::render::require_valid_versao_requirement`]
9209        // cascade; the four non-empty arms exercise distinct semver-parse
9210        // failure modes the M3 peer per-`:membros` reject-set already pins
9211        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
9212        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
9213        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
9214        // shared parser routing means the same reject-set must fail
9215        // identically at the M2 supervisor-tree per-`:children` accessor
9216        // arm here. Every rejection at the validator must correspond to a
9217        // rejection when the accessor's projected value is fed back
9218        // through the shared gate.
9219        //
9220        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
9221        // `"not-a-semver"` are intentionally *not* in the reject-set: the
9222        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
9223        // and the identifier-tail arm's grammar admits some non-canonical
9224        // shapes — matching what the M3 peer test suite already documents
9225        // as the shared parser's accept-set edges.)
9226        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
9227            let s = SupervisorSpec {
9228                children: vec![ChildSpec {
9229                    caixa: "worker".into(),
9230                    versao: bad_req.into(),
9231                    restart: RestartPolicy::Permanent,
9232                }],
9233                ..SupervisorSpec::default()
9234            };
9235            let err = s.validate().unwrap_err();
9236            assert!(
9237                matches!(
9238                    err,
9239                    SupervisorError::EmptyChildVersion { .. }
9240                        | SupervisorError::ChildVersaoInvalid { .. }
9241                ),
9242                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
9243                 via the versao-requirement gate: got {err:?}",
9244            );
9245            let c = ChildSpec {
9246                caixa: "worker".into(),
9247                versao: bad_req.into(),
9248                restart: RestartPolicy::Permanent,
9249            };
9250            assert!(
9251                crate::render::require_valid_versao_requirement(
9252                    c.versao_requirement(),
9253                    || (),
9254                    |_reason| (),
9255                )
9256                .is_err(),
9257                "require_valid_versao_requirement must reject the accessor-projected \
9258                 :children :versao {bad_req:?}",
9259            );
9260        }
9261    }
9262
9263    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
9264    //
9265    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
9266    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
9267    // already project the `String`-carry `(caixa, versao)` fields; the
9268    // `Copy`-composite-enum `restart` field is the third and final axis).
9269    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
9270    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
9271    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
9272    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
9273    // strategy scalar accessor — same "one typed dispatch on the substrate
9274    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
9275    // extended onto the M2 supervisor-slot per-`:children` restart-decision
9276    // axis. The pin below covers the accessor's byte-equal projection
9277    // against the raw field access across every variant in the closed
9278    // accept-set (`Permanent`, `Transient`, `Temporary`).
9279
9280    #[test]
9281    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
9282        // The canonical per-`:children` restart-decision-policy-scalar
9283        // pin: [`ChildSpec::restart`] must return the `:children :restart`
9284        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
9285        // typed slot's own [`RestartPolicy`] storage across every variant
9286        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
9287        // Pins against a future silent detour that re-derived the policy
9288        // from a peer axis (an accidental fallback to
9289        // `if is_supervisor_child { Permanent } else { Temporary }` that
9290        // collapsed the child's kind axis into the restart discriminator),
9291        // a variant remap the operator authors on one consumer without the
9292        // other, or a stale-derive detour that substituted
9293        // [`RestartPolicy::default`] when the field held any explicit
9294        // variant (which would silently collapse the distinction between
9295        // "author explicitly declared `:restart Permanent`" and "author
9296        // omitted the slot and inherited the default" the future
9297        // per-cluster restart-decision override slot depends on).
9298        //
9299        // Peer of the sibling per-`:supervisor`
9300        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
9301        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
9302        // axis and the M3
9303        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
9304        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
9305        // — same "the substrate-primitive accessor must byte-equal the raw
9306        // field access verbatim across every author-declared value"
9307        // discipline extended onto the M2 supervisor-slot per-`:children`
9308        // restart-decision-policy axis, closing the last unlifted axis on
9309        // the per-`:children` [`ChildSpec`] type.
9310        for restart in [
9311            RestartPolicy::Permanent,
9312            RestartPolicy::Transient,
9313            RestartPolicy::Temporary,
9314        ] {
9315            let c = ChildSpec {
9316                caixa: "worker".into(),
9317                versao: "^0.1".into(),
9318                restart,
9319            };
9320            assert_eq!(
9321                c.restart(),
9322                restart,
9323                "ChildSpec::restart must return :children :restart \
9324                 verbatim (got {:?}, expected {restart:?})",
9325                c.restart(),
9326            );
9327            assert_eq!(
9328                c.restart(),
9329                c.restart,
9330                "ChildSpec::restart accessor and .restart field access \
9331                 must byte-equal — the accessor is the substrate-primitive \
9332                 typed dispatch every downstream per-child restart-\
9333                 decision consumer must route through",
9334            );
9335        }
9336    }
9337
9338    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
9339    //
9340    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
9341    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
9342    // distribution-strategy accessor discipline onto the M2 supervisor-slot
9343    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
9344    // scalar axis. The two pins below cover (1) the accessor's byte-equal
9345    // projection against the raw field access across every variant in the
9346    // closed accept-set, and (2) the two-consumer coherence between the
9347    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
9348    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
9349    // carrier's `estrategia:` field — peer of the sibling M3
9350    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
9351    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
9352    // pair on the per-`:placement` distribution-strategy axis.
9353
9354    #[test]
9355    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
9356        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
9357        // pin: [`SupervisorSpec::estrategia`] must return the
9358        // `:supervisor :estrategia` field verbatim as a
9359        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
9360        // [`RestartStrategy`] storage across every variant in the closed
9361        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
9362        // `SimpleOneForOne`). Pins against a future silent detour that
9363        // re-derived the strategy from a peer axis (an accidental
9364        // fallback to `if children.is_empty() { SimpleOneForOne } else {
9365        // OneForOne }` collapse that read the children-count axis into
9366        // the strategy discriminator), a variant remap the operator
9367        // authors on one consumer without the other, or a stale-derive
9368        // detour that substituted [`RestartStrategy::default`] when the
9369        // field held any explicit variant (which would silently collapse
9370        // the distinction between "author explicitly declared
9371        // `:estrategia OneForOne`" and "author omitted the slot and
9372        // inherited the default" the future per-cluster strategy override
9373        // slot depends on). Peer of the sibling M3
9374        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
9375        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
9376        // axis — same "the substrate-primitive accessor must byte-equal
9377        // the raw field access verbatim across every author-declared
9378        // value" discipline extended onto the M2 supervisor-slot
9379        // per-`:supervisor` sibling-restart-strategy axis.
9380        for &estrategia in RestartStrategy::ALL {
9381            // `SimpleOneForOne` requires `children.is_empty()`; the peer
9382            // three strategies require a non-empty static children list.
9383            // Build each shape coherently so the pin's fixture would
9384            // itself pass [`SupervisorSpec::validate`] once fed through
9385            // the sibling coherence pin below — the byte-equal projection
9386            // asserted here is a strictly weaker property (a `Copy` field
9387            // read) that does not depend on `validate` running, but
9388            // keeping the fixture validate-clean means a future extension
9389            // of the pin to exercise `validate` end-to-end does not have
9390            // to re-author the children shape.
9391            //
9392            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
9393            // shape partition through the [`gen_platform::IsVariant`]
9394            // derive-generated
9395            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
9396            // than the raw `matches!(estrategia, RestartStrategy::
9397            // SimpleOneForOne)` open-coded pattern-match — same closed-
9398            // set-typed-enum arm-discriminator dispatch discipline the
9399            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
9400            // convergence (915a934) extended onto its two paired positive
9401            // / negated `matches!` sites and the peer
9402            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
9403            // predicate convergence (766ec63) extended onto the M3 mesh-
9404            // slot per-`:placement` distribution-strategy discriminator
9405            // axis. See the sibling `round_trip_all_strategies` and the
9406            // peer `manifest::tests::
9407            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
9408            // fixture for the two peer sites the same lift closes on.
9409            let children = if estrategia.is_simple_one_for_one() {
9410                Vec::new()
9411            } else {
9412                vec![ChildSpec {
9413                    caixa: "worker".into(),
9414                    versao: "^0.1".into(),
9415                    restart: RestartPolicy::Permanent,
9416                }]
9417            };
9418            let s = SupervisorSpec {
9419                estrategia,
9420                children,
9421                ..SupervisorSpec::default()
9422            };
9423            assert_eq!(
9424                s.estrategia(),
9425                estrategia,
9426                "SupervisorSpec::estrategia must return :supervisor :estrategia \
9427                 verbatim (got {:?}, expected {estrategia:?})",
9428                s.estrategia(),
9429            );
9430            assert_eq!(
9431                s.estrategia(),
9432                s.estrategia,
9433                "SupervisorSpec::estrategia accessor and .estrategia field \
9434                 access must byte-equal — the accessor is the substrate-\
9435                 primitive typed dispatch every downstream sibling-restart-\
9436                 strategy consumer must route through",
9437            );
9438        }
9439    }
9440
9441    #[test]
9442    fn validate_reads_through_lifted_estrategia_accessor() {
9443        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
9444        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
9445        // dispatch (which reads through [`SupervisorSpec::estrategia`]
9446        // to fan across the strategy-arm shape-gate cascades) and the
9447        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
9448        // error carrier's `estrategia:` field (which reads through
9449        // [`SupervisorSpec::estrategia`] to name the strategy the empty
9450        // `:children` list was declared against) must both key off the
9451        // lifted accessor, so any future rebrand on the typed slot's
9452        // reader shape lands at exactly one place. Pins the two-site
9453        // coherence by exercising the `NoChildren` error surface end-to-
9454        // end across every non-`SimpleOneForOne` variant and asserting
9455        // the surfaced `estrategia:` field byte-equals the accessor's
9456        // return. Peer of the sibling M3
9457        // `validate_placement_reads_through_lifted_estrategia_accessor`
9458        // (921fe1b) three-consumer coherence pin on the per-`:placement`
9459        // distribution-strategy axis.
9460        for estrategia in [
9461            RestartStrategy::OneForOne,
9462            RestartStrategy::OneForAll,
9463            RestartStrategy::RestForOne,
9464        ] {
9465            let s = SupervisorSpec {
9466                estrategia,
9467                children: Vec::new(),
9468                ..SupervisorSpec::default()
9469            };
9470            let err = s.validate().unwrap_err();
9471            match err {
9472                SupervisorError::NoChildren { estrategia: e } => {
9473                    assert_eq!(
9474                        e,
9475                        s.estrategia(),
9476                        "NoChildren.estrategia must byte-equal \
9477                         SupervisorSpec::estrategia() — the empty-`:children` \
9478                         refusal reads through the lifted accessor",
9479                    );
9480                    assert_eq!(
9481                        e, estrategia,
9482                        "NoChildren.estrategia must carry the author-declared \
9483                         :supervisor :estrategia variant verbatim (got {e:?}, \
9484                         expected {estrategia:?})",
9485                    );
9486                }
9487                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
9488            }
9489        }
9490    }
9491
9492    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
9493    //
9494    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
9495    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
9496    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
9497    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
9498    // The two pins below cover (1) the accessor's byte-equal projection
9499    // against the raw field access across every representative value in
9500    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
9501    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
9502    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
9503    // zero-floor / cap composition — the validate gate and the accessor
9504    // must route through the same substrate-primitive typed dispatch, so
9505    // any future silent detour that had the accessor perform a
9506    // bounds-collapsing clamp would fail here at caixa-core build time.
9507    // Peer of the sibling M3
9508    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
9509    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
9510
9511    #[test]
9512    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
9513        // The canonical per-`:supervisor` restart-budget-count scalar pin:
9514        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
9515        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
9516        // typed slot's own `u32` storage, byte-equal to the raw field
9517        // access across every representative value in the accept-set —
9518        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
9519        // accept-set the surrounding [`SupervisorSpec::validate`] gate
9520        // carves out on the sibling `ZeroMaxRestarts` refusal),
9521        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
9522        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
9523        // (a past-the-guard sentinel that pins the accessor doesn't
9524        // perform a silent bounds-collapse into `1` on the zero arm —
9525        // validate rejects zero but the accessor must ship the raw slot
9526        // verbatim so a validate-time gate regression surfaces at the
9527        // emit boundary rather than being silently absorbed), `u32::MAX`
9528        // (a past-the-guard sentinel that pins the accessor doesn't
9529        // perform a silent bounds-collapse through
9530        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
9531        //
9532        // Peer of the sibling M3
9533        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
9534        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
9535        // required-scalar axis — same "the substrate-primitive accessor
9536        // must byte-equal the raw field access verbatim across every
9537        // value in the `u32` accept-set" discipline extended onto the M2
9538        // supervisor-slot per-`:supervisor` restart-budget-count axis.
9539        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
9540            let s = SupervisorSpec {
9541                max_restarts,
9542                ..SupervisorSpec::default()
9543            };
9544            assert_eq!(
9545                s.max_restarts(),
9546                max_restarts,
9547                "SupervisorSpec::max_restarts must return :supervisor \
9548                 :max-restarts verbatim (got {}, expected {max_restarts})",
9549                s.max_restarts(),
9550            );
9551            assert_eq!(
9552                s.max_restarts(),
9553                s.max_restarts,
9554                "SupervisorSpec::max_restarts accessor and .max_restarts \
9555                 field access must byte-equal — the accessor is the \
9556                 substrate-primitive typed dispatch every downstream \
9557                 restart-budget-count consumer must route through",
9558            );
9559        }
9560    }
9561
9562    #[test]
9563    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
9564        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
9565        // zero-floor + upper-cap bracket must key off
9566        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
9567        // field access. Structurally: a `SupervisorSpec { max_restarts:
9568        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
9569        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
9570        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
9571        // (with the offending count carried verbatim from the accessor
9572        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
9573        // lower boundary of the accept-set) plus a `SupervisorSpec {
9574        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
9575        // boundary) must pass validate. The four together jointly pin the
9576        // accessor + validate-gate composition: any future silent detour
9577        // that had the accessor return a fresh `1` on the zero arm (a
9578        // `.max_restarts().max(1)` collapse) would silently absorb the
9579        // `ZeroMaxRestarts` refusal at the accessor boundary and the
9580        // validate gate would accept a struct-literal `SupervisorSpec {
9581        // max_restarts: 0, .. }` — the composition pin catches that at
9582        // caixa-core build time.
9583        //
9584        // Peer of the sibling M3
9585        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
9586        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
9587        // composition axis — same "the validate / shape-gate predicate
9588        // must route through the substrate-primitive typed dispatch"
9589        // discipline extended onto the peer M2 supervisor-slot
9590        // required-`u32` composition axis.
9591        let child = ChildSpec {
9592            caixa: "worker".into(),
9593            versao: "^0.1".into(),
9594            restart: RestartPolicy::Permanent,
9595        };
9596        // Zero-floor arm.
9597        let s = SupervisorSpec {
9598            max_restarts: 0,
9599            children: vec![child.clone()],
9600            ..SupervisorSpec::default()
9601        };
9602        assert_eq!(
9603            s.validate().unwrap_err(),
9604            SupervisorError::ZeroMaxRestarts,
9605            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
9606             — the accessor and the validate gate must route through the \
9607             same substrate-primitive typed dispatch on the zero-floor arm",
9608        );
9609        // Cap arm — the surfaced `max_restarts:` field must byte-equal
9610        // the accessor's return so a future rebrand on the accessor
9611        // lands in the diagnostic without a coordinated rewrite.
9612        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
9613        let s = SupervisorSpec {
9614            max_restarts: over_cap,
9615            children: vec![child.clone()],
9616            ..SupervisorSpec::default()
9617        };
9618        match s.validate().unwrap_err() {
9619            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
9620                assert_eq!(
9621                    max_restarts,
9622                    s.max_restarts(),
9623                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
9624                     SupervisorSpec::max_restarts() — the cap-arm refusal \
9625                     reads through the lifted accessor",
9626                );
9627                assert_eq!(
9628                    max_restarts, over_cap,
9629                    "MaxRestartsExceedsCap.max_restarts must carry the \
9630                     author-declared :supervisor :max-restarts value \
9631                     verbatim (got {max_restarts}, expected {over_cap})",
9632                );
9633            }
9634            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
9635        }
9636        // Lower + upper accept-set boundaries.
9637        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
9638            let s = SupervisorSpec {
9639                max_restarts,
9640                children: vec![child.clone()],
9641                ..SupervisorSpec::default()
9642            };
9643            assert!(
9644                s.validate().is_ok(),
9645                "validate must accept max_restarts == {max_restarts} \
9646                 (an accept-set boundary of \
9647                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
9648            );
9649        }
9650    }
9651
9652    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
9653    //
9654    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
9655    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
9656    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
9657    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
9658    // supervisor-slot per-`:supervisor` restart-intensity-denominator
9659    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
9660    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
9661    // per-`:supervisor` scalar-value axis. The three pins below cover
9662    // (1) the accessor's byte-equal projection against the raw field
9663    // access across every representative value in the `Option<Duration>`
9664    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
9665    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
9666    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
9667    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
9668    // `if let Some(w) = self.restart_window() { … }` bracket-arm
9669    // composition — the validate gate and the accessor must route through
9670    // the same substrate-primitive typed dispatch, so any future silent
9671    // detour that had the accessor perform a bounds-collapsing clamp
9672    // would fail here at caixa-core build time, and (3) the accessor's
9673    // by-copy idempotence pin — the returned `Option<Duration>` must
9674    // outlive `&self` and two successive calls must return byte-equal
9675    // values. Peer of the sibling M2
9676    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
9677    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
9678    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
9679    // (7073d0f) pin on the per-`:politicas :timeout` axis.
9680
9681    #[test]
9682    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
9683        // The canonical per-`:supervisor` restart-intensity-denominator
9684        // scalar pin: [`SupervisorSpec::restart_window`] must return the
9685        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
9686        // `Option<Duration>`, `Copy`-projected from the typed slot's own
9687        // `Option<Duration>` storage, byte-equal to the raw field access
9688        // across every representative value in the accept-set — `None`
9689        // (the "never reset — every restart across the supervisor's
9690        // lifetime counts against the sibling `:max-restarts` budget"
9691        // sentinel the field's own docstring names and the peer
9692        // `validate_accepts_none_restart_window` pin locks in on the
9693        // [`SupervisorSpec::validate`] entry-side),
9694        // `Some(Duration::from_millis(1))` (the structural minimum a
9695        // validated `:restart-window` may carry, the integer-millisecond
9696        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
9697        // everything sub-ms; `Duration::ZERO` is separately rejected by
9698        // [`SupervisorError::RestartWindowZero`]),
9699        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
9700        // surrounding [`SupervisorSpec::validate`] gate carves out on the
9701        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
9702        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
9703        // accessor doesn't perform a silent bounds-collapse into `None` on
9704        // the zero-Duration arm — validate rejects zero but the accessor
9705        // must ship the raw slot verbatim so a validate-time gate
9706        // regression surfaces at the emit boundary rather than being
9707        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
9708        // sentinel that pins the accessor doesn't perform a silent
9709        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
9710        // return path).
9711        //
9712        // Peer of the sibling M2
9713        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
9714        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
9715        // sibling M3
9716        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
9717        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
9718        // substrate-primitive accessor must byte-equal the raw field
9719        // access verbatim across every value in the `Option<Duration>`
9720        // accept-set" discipline extended onto the M2 supervisor-slot
9721        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
9722        // silent detour that re-derived the restart-window from a peer
9723        // axis (an accidental `.max_restarts.into()` collapse that read
9724        // the restart-budget-count as a duration — the two axes serve
9725        // different halves of the `MaxIntensity / Period` restart-
9726        // intensity ratio, and confusing them silently inverts the
9727        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
9728        // "zero means never reset" collapse (the canonical
9729        // `Option<Duration>` → `Duration` collapse footgun the
9730        // [`SupervisorError::RestartWindowZero`] validate arm guards on
9731        // the peer zero-floor axis; a zero period either trips on the
9732        // first failure or never trips depending on operator
9733        // interpretation, neither of which is the author's "never reset"
9734        // intent that `None` expresses structurally), or a per-arm
9735        // variant swap that landed on one consumer without the other.
9736        for restart_window in [
9737            None,
9738            Some(Duration::from_millis(1)),
9739            Some(SUPERVISOR_RESTART_WINDOW_MAX),
9740            Some(Duration::ZERO),
9741            Some(Duration::MAX),
9742        ] {
9743            let s = SupervisorSpec {
9744                restart_window,
9745                ..SupervisorSpec::default()
9746            };
9747            assert_eq!(
9748                s.restart_window(),
9749                restart_window,
9750                "SupervisorSpec::restart_window must return :supervisor \
9751                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
9752                s.restart_window(),
9753            );
9754            assert_eq!(
9755                s.restart_window(),
9756                s.restart_window,
9757                "SupervisorSpec::restart_window accessor and \
9758                 .restart_window field access must byte-equal — the \
9759                 accessor is the substrate-primitive typed dispatch every \
9760                 downstream restart-intensity-denominator consumer must \
9761                 route through",
9762            );
9763        }
9764    }
9765
9766    #[test]
9767    fn validate_restart_window_bracket_arm_routes_through_accessor() {
9768        // Composition pin: [`SupervisorSpec::validate`]'s
9769        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
9770        // zero-floor + integer-millisecond canonical-form + upper-cap
9771        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
9772        // the raw `.restart_window` field access. Structurally: a
9773        // `SupervisorSpec { restart_window: None, .. }` must pass the
9774        // arm gate structurally (the `if let Some(_)` shape returns
9775        // early on the `None` arm — the accessor and the validate gate
9776        // must agree on `None → skip the bracket cascade` so an authored
9777        // `:restart-window ()` structurally routes through the "never
9778        // reset" sentinel path), a `SupervisorSpec { restart_window:
9779        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
9780        // refusal exactly, a `SupervisorSpec { restart_window:
9781        // Some(Duration::from_micros(1500)), .. }` must surface the
9782        // `RestartWindowNotCanonical` refusal exactly (with the offending
9783        // duration carried verbatim from the accessor return), a
9784        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
9785        // + Duration::from_millis(1)), .. }` must surface the
9786        // `RestartWindowExceedsCap` refusal exactly (with the offending
9787        // duration carried verbatim from the accessor return), and a
9788        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
9789        // .. }` (the lower boundary of the accept-set) plus a
9790        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
9791        // .. }` (the upper boundary) must pass validate. The six together
9792        // jointly pin the accessor + validate-gate composition: any future
9793        // silent detour that had the accessor return a fresh `None` on any
9794        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
9795        // collapse) would silently absorb the `RestartWindowZero` refusal
9796        // at the accessor boundary and the validate gate would accept a
9797        // struct-literal `SupervisorSpec { restart_window:
9798        // Some(Duration::ZERO), .. }` — the composition pin catches that
9799        // at caixa-core build time.
9800        //
9801        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
9802        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
9803        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
9804        // accessor-composition pin on the per-`:politicas :timeout` axis —
9805        // same "the validate / shape-gate predicate must route through
9806        // the substrate-primitive typed dispatch" discipline extended
9807        // onto the peer M2 supervisor-slot optional-`Duration` axis.
9808        let child = ChildSpec {
9809            caixa: "worker".into(),
9810            versao: "^0.1".into(),
9811            restart: RestartPolicy::Permanent,
9812        };
9813        // None arm — must not surface any :restart-window-shaped refusal;
9814        // the `if let Some(_)` bracket returns early on `None` structurally.
9815        let s = SupervisorSpec {
9816            restart_window: None,
9817            children: vec![child.clone()],
9818            ..SupervisorSpec::default()
9819        };
9820        assert!(
9821            s.validate().is_ok(),
9822            "validate must accept restart_window: None (the never-reset \
9823             sentinel) — the `if let Some(_)` bracket returns early on \
9824             the None arm and the accessor must agree",
9825        );
9826        // Zero-floor arm.
9827        let s = SupervisorSpec {
9828            restart_window: Some(Duration::ZERO),
9829            children: vec![child.clone()],
9830            ..SupervisorSpec::default()
9831        };
9832        assert_eq!(
9833            s.validate().unwrap_err(),
9834            SupervisorError::RestartWindowZero,
9835            "validate must reject restart_window == Some(Duration::ZERO) \
9836             with RestartWindowZero — the accessor and the validate gate \
9837             must route through the same substrate-primitive typed \
9838             dispatch on the zero-floor arm",
9839        );
9840        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
9841        // byte-equal the accessor's return so a future rebrand on the
9842        // accessor lands in the diagnostic without a coordinated rewrite.
9843        let sub_ms = Duration::from_micros(1500);
9844        let s = SupervisorSpec {
9845            restart_window: Some(sub_ms),
9846            children: vec![child.clone()],
9847            ..SupervisorSpec::default()
9848        };
9849        match s.validate().unwrap_err() {
9850            SupervisorError::RestartWindowNotCanonical { window } => {
9851                assert_eq!(
9852                    Some(window),
9853                    s.restart_window(),
9854                    "RestartWindowNotCanonical.window must byte-equal \
9855                     SupervisorSpec::restart_window().unwrap() — the \
9856                     non-canonical-arm refusal reads through the lifted \
9857                     accessor",
9858                );
9859                assert_eq!(
9860                    window, sub_ms,
9861                    "RestartWindowNotCanonical.window must carry the \
9862                     author-declared :supervisor :restart-window value \
9863                     verbatim (got {window:?}, expected {sub_ms:?})",
9864                );
9865            }
9866            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
9867        }
9868        // Cap arm — the surfaced `window:` field must byte-equal the
9869        // accessor's return.
9870        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
9871        let s = SupervisorSpec {
9872            restart_window: Some(over_cap),
9873            children: vec![child.clone()],
9874            ..SupervisorSpec::default()
9875        };
9876        match s.validate().unwrap_err() {
9877            SupervisorError::RestartWindowExceedsCap { window } => {
9878                assert_eq!(
9879                    Some(window),
9880                    s.restart_window(),
9881                    "RestartWindowExceedsCap.window must byte-equal \
9882                     SupervisorSpec::restart_window().unwrap() — the \
9883                     cap-arm refusal reads through the lifted accessor",
9884                );
9885                assert_eq!(
9886                    window, over_cap,
9887                    "RestartWindowExceedsCap.window must carry the \
9888                     author-declared :supervisor :restart-window value \
9889                     verbatim (got {window:?}, expected {over_cap:?})",
9890                );
9891            }
9892            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
9893        }
9894        // Lower + upper accept-set boundaries.
9895        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
9896            let s = SupervisorSpec {
9897                restart_window: Some(restart_window),
9898                children: vec![child.clone()],
9899                ..SupervisorSpec::default()
9900            };
9901            assert!(
9902                s.validate().is_ok(),
9903                "validate must accept restart_window == Some({restart_window:?}) \
9904                 (an accept-set boundary of \
9905                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
9906            );
9907        }
9908    }
9909
9910    #[test]
9911    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
9912        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
9913        // `Option<Duration>` by copy — `Duration` is `Copy` (so
9914        // `Option<Duration>` is `Copy`) and the accessor must return by
9915        // value, not by reference. Peer of the sibling M2
9916        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
9917        // per-`:limits :wall-clock` axis and the sibling M3
9918        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
9919        // per-`:politicas :timeout` axis, extended onto the peer M2
9920        // supervisor-slot `Option<Duration>` copy-invariant shape — the
9921        // accessor's returned `Option<Duration>` must outlive `&self`
9922        // (multiple calls must return equal values from a dropped-`&self`
9923        // copy, since the returned Option carries no borrow), and calling
9924        // the accessor twice on the same SupervisorSpec must yield the
9925        // same `Option<Duration>` verbatim (idempotent, no side effects
9926        // on `&self`).
9927        //
9928        // Pins against a future silent detour that returned
9929        // `Option<&Duration>` (which would type-check but silently break
9930        // every downstream caller — the future wasm-operator's
9931        // per-supervisor restart-intensity counter consumes `Duration` by
9932        // value and `&Duration` would fold to a detached copy at the call
9933        // site), an accidental `Option::as_ref()` projection
9934        // (`self.restart_window.as_ref()` would also type-check but
9935        // return `Option<&Duration>`), or a one-arm-only accessor that
9936        // reads `Some(*w)` in the Some arm but reads a fresh
9937        // `Default::default()` (which would collapse to `Duration::ZERO`,
9938        // not `None`) in the None arm — a footgun the
9939        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
9940        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
9941        // requires `Period > 0` and `None` structurally expresses "never
9942        // reset" instead.
9943        for restart_window in [
9944            None,
9945            Some(Duration::from_millis(1)),
9946            Some(Duration::from_secs(60)),
9947            Some(SUPERVISOR_RESTART_WINDOW_MAX),
9948        ] {
9949            let s = SupervisorSpec {
9950                restart_window,
9951                ..SupervisorSpec::default()
9952            };
9953            let first = s.restart_window();
9954            let second = s.restart_window();
9955            assert_eq!(
9956                first, second,
9957                "SupervisorSpec::restart_window must be idempotent — two \
9958                 successive calls on the same &self must return the \
9959                 same Option<Duration>",
9960            );
9961            assert_eq!(
9962                first, restart_window,
9963                "SupervisorSpec::restart_window must return :supervisor \
9964                 :restart-window verbatim by copy — got {first:?}, \
9965                 expected {restart_window:?}",
9966            );
9967        }
9968    }
9969
9970    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
9971    //
9972    // The [`SupervisorSpec::children`] accessor lift is the seed of the
9973    // slice-return (`&[T]`) accessor discipline on the substrate — the four
9974    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
9975    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
9976    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
9977    // access at the time of this seed, and inherit this pin family's
9978    // discipline as future compounding runs migrate their consumers. The
9979    // three pins below cover (1) the accessor's byte-equal projection
9980    // against the raw field access across the empty / singleton / cohort
9981    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
9982    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
9983    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
9984    // consumer routing through the accessor on both arms, and (3) the
9985    // per-child validate loop's traversal reading the same slice-view the
9986    // accessor projects. Peer of the sibling M2
9987    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
9988    // two-consumer coherence pin on the per-`:supervisor`
9989    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
9990    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
9991
9992    #[test]
9993    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
9994        // The canonical per-`:supervisor` static-child-list scalar-shape
9995        // pin: [`SupervisorSpec::children`] must return the `:supervisor
9996        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
9997        // slice-view over the same backing buffer the raw
9998        // `self.children.as_slice()` field access borrows from, byte-
9999        // equal across every representative fixture in the accept-set —
10000        // the empty slice (the `SimpleOneForOne`-arm sentinel),
10001        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
10002        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
10003        // with the peer three restart-policy variants in play).
10004        //
10005        // Pins against a future silent detour that returned
10006        // `&Vec<ChildSpec>` (which would type-check but leak the
10007        // storage-side `Vec`'s grow/push/reserve surface no consumer of
10008        // the typed view reaches for), a fresh-allocated
10009        // `Vec<ChildSpec>` copy (which would type-check via a coercion
10010        // but silently break every downstream caller that relied on the
10011        // slice sharing the backing buffer's identity), or an
10012        // out-of-order or length-drifted projection (which would silently
10013        // split the per-child validate loop's traversal input from the
10014        // paired partition-dispatch `.is_empty()` probe's input).
10015        //
10016        // Peer of the sibling
10017        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
10018        // (eafb619) `Copy`-composite-enum byte-equal pin on the
10019        // per-`:supervisor` sibling-restart-strategy axis, extended onto
10020        // the per-`:supervisor` static-child-list `Vec`-carry axis.
10021        let fixtures: Vec<Vec<ChildSpec>> = vec![
10022            Vec::new(),
10023            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
10024            vec![
10025                child("worker", "^0.1", RestartPolicy::Permanent),
10026                child("cache-server", "^0.1", RestartPolicy::Transient),
10027            ],
10028            vec![
10029                child("worker", "^0.1", RestartPolicy::Permanent),
10030                child("cache-server", "^0.1", RestartPolicy::Transient),
10031                child("scratch-job", "^0.1", RestartPolicy::Temporary),
10032            ],
10033        ];
10034        for children in fixtures {
10035            let s = SupervisorSpec {
10036                children: children.clone(),
10037                ..SupervisorSpec::default()
10038            };
10039            assert_eq!(
10040                s.children(),
10041                children.as_slice(),
10042                "SupervisorSpec::children must return :supervisor \
10043                 :children verbatim (got {:?}, expected {:?})",
10044                s.children(),
10045                children.as_slice(),
10046            );
10047            assert_eq!(
10048                s.children(),
10049                s.children.as_slice(),
10050                "SupervisorSpec::children accessor and \
10051                 .children.as_slice() field access must byte-equal — \
10052                 the accessor is the substrate-primitive typed \
10053                 dispatch every downstream static-child-list consumer \
10054                 must route through",
10055            );
10056            assert_eq!(
10057                s.children().len(),
10058                s.children.len(),
10059                "SupervisorSpec::children().len() must byte-equal \
10060                 self.children.len() — a length-drift would silently \
10061                 split the paired partition-dispatch `.is_empty()` \
10062                 probe input from the per-child validate loop's \
10063                 traversal input",
10064            );
10065        }
10066    }
10067
10068    #[test]
10069    fn validate_reads_through_lifted_children_accessor() {
10070        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
10071        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
10072        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
10073        // when the accessor projects a non-empty slice under a
10074        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
10075        // `self.children().is_empty()` refusal probe (which must trip
10076        // [`SupervisorError::NoChildren`] when the accessor projects the
10077        // empty slice under any peer estrategia), and the per-child
10078        // validate loop's `for child in self.children()` traversal
10079        // (which must reach every entry in the same order the accessor
10080        // projects) must all key off the lifted accessor, so any future
10081        // rebrand on the typed slot's reader shape lands at exactly one
10082        // place. Pins the three-site coherence by exercising each
10083        // production consumer end-to-end: (1) the
10084        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
10085        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
10086        // refusal under the empty slice + non-`SimpleOneForOne`
10087        // estrategia across every peer variant, and (3) the per-child
10088        // duplicate-detection surface fires on the second entry of a
10089        // two-child cohort that shares a `:caixa` name (which requires
10090        // the loop to reach both entries — a first-entry-only projection
10091        // would silently pass since the dedup HashSet has room for the
10092        // first insert).
10093        //
10094        // Peer of the sibling M2
10095        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
10096        // two-consumer coherence pin on the per-`:supervisor`
10097        // sibling-restart-strategy axis, extended onto the
10098        // per-`:supervisor` static-child-list `Vec`-carry axis.
10099
10100        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
10101        // `SimpleOneForOne` estrategia must trip
10102        // `SimpleOneForOneWithStaticChildren`.
10103        let s = SupervisorSpec {
10104            estrategia: RestartStrategy::SimpleOneForOne,
10105            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
10106            ..SupervisorSpec::default()
10107        };
10108        assert_eq!(
10109            s.validate().unwrap_err(),
10110            SupervisorError::SimpleOneForOneWithStaticChildren,
10111            "SimpleOneForOne + non-empty children must trip \
10112             SimpleOneForOneWithStaticChildren — the accessor projects \
10113             a non-empty slice, and the SimpleOneForOne-arm refusal \
10114             probe reads through the lifted accessor",
10115        );
10116        assert!(
10117            !s.children().is_empty(),
10118            "the SimpleOneForOne-arm refusal input must be a non-empty \
10119             slice per the accessor's projection",
10120        );
10121
10122        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
10123        // under any peer estrategia must trip `NoChildren`.
10124        for estrategia in [
10125            RestartStrategy::OneForOne,
10126            RestartStrategy::OneForAll,
10127            RestartStrategy::RestForOne,
10128        ] {
10129            let s = SupervisorSpec {
10130                estrategia,
10131                children: Vec::new(),
10132                ..SupervisorSpec::default()
10133            };
10134            match s.validate().unwrap_err() {
10135                SupervisorError::NoChildren { estrategia: e } => {
10136                    assert_eq!(
10137                        e, estrategia,
10138                        "NoChildren.estrategia must carry the author-\
10139                         declared :supervisor :estrategia variant \
10140                         verbatim (got {e:?}, expected {estrategia:?})",
10141                    );
10142                }
10143                other => panic!(
10144                    "expected NoChildren, got {other:?} for \
10145                     estrategia={estrategia:?}"
10146                ),
10147            }
10148            assert!(
10149                s.children().is_empty(),
10150                "the non-SimpleOneForOne-arm refusal input must be the \
10151                 empty slice per the accessor's projection",
10152            );
10153        }
10154
10155        // (3) Per-child validate loop: a two-child cohort that shares a
10156        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
10157        // reach both entries through the accessor.
10158        let s = SupervisorSpec {
10159            estrategia: RestartStrategy::OneForOne,
10160            children: vec![
10161                child("worker", "^0.1", RestartPolicy::Permanent),
10162                child("worker", "^0.2", RestartPolicy::Transient),
10163            ],
10164            ..SupervisorSpec::default()
10165        };
10166        match s.validate().unwrap_err() {
10167            SupervisorError::DuplicateChildCaixa { caixa } => {
10168                assert_eq!(
10169                    caixa, "worker",
10170                    "DuplicateChildCaixa.caixa must carry the shared \
10171                     child `:caixa` name verbatim",
10172                );
10173            }
10174            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
10175        }
10176        assert_eq!(
10177            s.children().len(),
10178            2,
10179            "the per-child validate loop's traversal input must be a \
10180             two-element slice per the accessor's projection",
10181        );
10182    }
10183
10184    // Shared helper for the M2 per-`:children` per-slot-gate ≡
10185    // `validate` equivalence pins: builds an `OneForOne`-estrategia
10186    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
10187    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
10188    // bracket all pass cleanly so the sole failing surface is the
10189    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
10190    // pins the two-altitude equivalence on the paired probe.
10191    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
10192        let s = SupervisorSpec {
10193            estrategia: RestartStrategy::OneForOne,
10194            children,
10195            ..SupervisorSpec::default()
10196        };
10197        let via_gate = s.validate_children().unwrap_err();
10198        let via_validate = s.validate().unwrap_err();
10199        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
10200        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
10201        assert_eq!(
10202            via_gate, via_validate,
10203            "per-slot gate ≡ validate() must discriminate the same \
10204             refusal shape",
10205        );
10206    }
10207
10208    #[test]
10209    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
10210        // Fail-before-pass-after equivalence pin on the M2
10211        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
10212        // convergence — sibling of the M3 mesh-slot
10213        // `validate_membros_*` / `validate_contratos_*` /
10214        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
10215        // peer per-entry axes. Sweeps four of the five refusal shapes
10216        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
10217        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
10218        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
10219        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
10220        // duplicate-`:caixa` fan-out. Companion pin
10221        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
10222        // covers `ChildVersaoInvalid` (whose parser-owned reason string
10223        // needs pattern-matching, not equality) and the clean-pass
10224        // canonical fixture; together the two pins guarantee the
10225        // per-slot gate and `validate` discriminate the same set on
10226        // every per-child-covered input.
10227        assert_validate_children_matches_gate(
10228            vec![child("", "^0.1", RestartPolicy::Permanent)],
10229            &SupervisorError::EmptyChildName,
10230        );
10231        assert_validate_children_matches_gate(
10232            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
10233            &SupervisorError::ChildCaixaInvalid {
10234                caixa: "Worker".into(),
10235                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
10236            },
10237        );
10238        assert_validate_children_matches_gate(
10239            vec![child("worker", "", RestartPolicy::Permanent)],
10240            &SupervisorError::EmptyChildVersion {
10241                caixa: "worker".into(),
10242            },
10243        );
10244        assert_validate_children_matches_gate(
10245            vec![
10246                child("worker", "^0.1", RestartPolicy::Permanent),
10247                child("worker", "^0.2", RestartPolicy::Transient),
10248            ],
10249            &SupervisorError::DuplicateChildCaixa {
10250                caixa: "worker".into(),
10251            },
10252        );
10253    }
10254
10255    #[test]
10256    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
10257        // Second half of the two-altitude equivalence pin — covers the
10258        // one refusal shape whose reason string is parser-owned
10259        // (`ChildVersaoInvalid`, whose reason comes from the shared
10260        // [`crate::version::parse_requirement`] impl and may drift) and
10261        // the clean-pass canonical fixture. Sibling pin
10262        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
10263        // covers the four equality-comparable refusal shapes.
10264        let s_bad_versao = SupervisorSpec {
10265            estrategia: RestartStrategy::OneForOne,
10266            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
10267            ..SupervisorSpec::default()
10268        };
10269        let via_gate = s_bad_versao.validate_children().unwrap_err();
10270        let via_validate = s_bad_versao.validate().unwrap_err();
10271        match (&via_gate, &via_validate) {
10272            (
10273                SupervisorError::ChildVersaoInvalid {
10274                    caixa: cg,
10275                    versao: vg,
10276                    ..
10277                },
10278                SupervisorError::ChildVersaoInvalid {
10279                    caixa: cv,
10280                    versao: vv,
10281                    ..
10282                },
10283            ) => {
10284                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
10285                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
10286                assert_eq!(cv, "worker", "validate() :caixa carrier");
10287                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
10288            }
10289            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
10290        }
10291        assert_eq!(
10292            via_gate, via_validate,
10293            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
10294        );
10295
10296        let s_ok = SupervisorSpec {
10297            estrategia: RestartStrategy::OneForOne,
10298            children: vec![
10299                child("worker-a", "^0.1", RestartPolicy::Permanent),
10300                child("worker-b", "~0.2.3", RestartPolicy::Transient),
10301                child("collector", "*", RestartPolicy::Temporary),
10302            ],
10303            ..SupervisorSpec::default()
10304        };
10305        s_ok.validate_children()
10306            .expect("per-slot gate must accept the clean-pass fixture");
10307        s_ok.validate()
10308            .expect("validate() must accept the clean-pass fixture");
10309    }
10310
10311    #[test]
10312    fn validate_children_is_self_contained_on_children_slot() {
10313        // Self-containment pin: [`SupervisorSpec::validate_children`]
10314        // resolves the per-child cascade against `&self` alone, without
10315        // depending on the peer `:estrategia`/`:max-restarts`/
10316        // `:restart-window` gates having run first — same posture the M3
10317        // peer per-slot gates carry (`validate_membros`,
10318        // `validate_contratos`, `validate_entrada`, `validate_placement`,
10319        // routing through their own oracles rather than borrowing state
10320        // threaded down from `validate`). A future consumer that reaches
10321        // the per-slot gate directly on a spec whose peer slots would
10322        // fail `validate` still surfaces the per-child refusal, not the
10323        // peer refusal.
10324        //
10325        // Construct a spec whose `:max-restarts` is `0` (which would
10326        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
10327        // the partition-dispatch) and whose `:children` carries a
10328        // `DuplicateChildCaixa` shape: the per-slot gate called directly
10329        // must surface `DuplicateChildCaixa`, proving it does not depend
10330        // on the peer `:max-restarts` gate running first.
10331        let s = SupervisorSpec {
10332            estrategia: RestartStrategy::OneForOne,
10333            max_restarts: 0,
10334            restart_window: Some(Duration::from_secs(60)),
10335            children: vec![
10336                child("worker", "^0.1", RestartPolicy::Permanent),
10337                child("worker", "^0.2", RestartPolicy::Transient),
10338            ],
10339        };
10340        assert_eq!(
10341            s.validate_children().unwrap_err(),
10342            SupervisorError::DuplicateChildCaixa {
10343                caixa: "worker".into(),
10344            },
10345            "per-slot gate must resolve per-child refusal directly against \
10346             `&self` — a dependency on the peer `:max-restarts` gate \
10347             running first would surface ZeroMaxRestarts here instead",
10348        );
10349        // The peer gate is still the surface `validate` reaches — pin
10350        // the ordering to establish that `validate_children` truly runs
10351        // last in `validate`'s dispatch, so a direct call bypasses the
10352        // peer gates on any spec whose per-child cascade would fail.
10353        assert_eq!(
10354            s.validate().unwrap_err(),
10355            SupervisorError::ZeroMaxRestarts,
10356            "validate() must surface the peer `:max-restarts` gate before \
10357             reaching the per-child cascade — this pins the dispatch \
10358             ordering the per-slot gate's self-containment complements",
10359        );
10360    }
10361
10362    #[test]
10363    fn child_spec_restart_accessor_is_const_fn() {
10364        // The [`ChildSpec::restart`] per-`:children` restart-decision-
10365        // policy `Copy`-return scalar accessor is declared
10366        // `#[must_use] pub const fn` — matching the sibling M2
10367        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
10368        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
10369        // both converted in this commit), the sibling M2
10370        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
10371        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
10372        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
10373        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
10374        // `Copy`-return `pub const fn` scalar accessors on the sibling
10375        // M3 surface. Pin the `const`-eval posture here so a future
10376        // accidental downgrade to non-`const` (an added runtime helper
10377        // reachable only from a non-`const` context, an
10378        // `Option<RestartPolicy>`-shape migration on the per-child
10379        // restart-decision axis once heterogeneous per-cluster
10380        // restart-policy overlays land that would silently drop the
10381        // `const` qualifier, a manual hand-rolled shadow) trips at
10382        // caixa-core build time rather than surfacing as a downstream
10383        // `const`-context regression far from the declaration.
10384        //
10385        // Same shape as the sibling M3
10386        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
10387        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
10388        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
10389        // accessor axis — the load-bearing witness lives in the
10390        // module-scope `const fn` wrapper `restart_via_const_fn` below:
10391        // a body that calls [`ChildSpec::restart`] under a `const fn`
10392        // signature is well-formed only when the callee is itself
10393        // `const fn`, so any future accidental downgrade of
10394        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
10395        // build time (const-eval E0015 `cannot call non-const method`),
10396        // strictly stronger than a runtime `assert!(CONST)` and
10397        // side-stepping the destructor-in-const restriction that
10398        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
10399        // items on `ChildSpec`'s `String` carriers.
10400        //
10401        // The runtime body sweeps every closed-set [`RestartPolicy`]
10402        // arm and asserts the wrapped and direct dispatches agree.
10403        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
10404            c.restart()
10405        }
10406        for restart in [
10407            RestartPolicy::Permanent,
10408            RestartPolicy::Transient,
10409            RestartPolicy::Temporary,
10410        ] {
10411            let c = ChildSpec {
10412                caixa: "worker".into(),
10413                versao: "^0.1".into(),
10414                restart,
10415            };
10416            assert_eq!(
10417                restart_via_const_fn(&c),
10418                c.restart(),
10419                "const-fn-wrapped and direct dispatch on \
10420                 ChildSpec::restart must agree for {restart:?}",
10421            );
10422            assert_eq!(
10423                c.restart(),
10424                restart,
10425                "ChildSpec::restart must return the storage-side \
10426                 RestartPolicy verbatim for {restart:?} (a violation \
10427                 means the accessor stopped being a raw field-return \
10428                 copy)",
10429            );
10430        }
10431    }
10432
10433    #[test]
10434    fn supervisor_spec_estrategia_accessor_is_const_fn() {
10435        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
10436        // sibling-restart-strategy `Copy`-return scalar accessor is
10437        // declared `#[must_use] pub const fn` — matching the sibling M2
10438        // per-`:children` [`ChildSpec::restart`] (pinned by
10439        // [`child_spec_restart_accessor_is_const_fn`] above, both
10440        // converted in this commit), the sibling M2 per-`:supervisor`
10441        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
10442        // accessor already `pub const fn`, and mirroring the peer M3
10443        // mesh-slot per-`:placement`
10444        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
10445        // `pub const fn` scalar accessor whose method-name discipline
10446        // the [`SupervisorSpec::estrategia`] method was authored to
10447        // match. Pin the `const`-eval posture here so a future
10448        // accidental downgrade to non-`const` (an added runtime helper
10449        // reachable only from a non-`const` context, an
10450        // `Option<RestartStrategy>`-shape migration once the substrate
10451        // grows per-cluster strategy overlays that would silently drop
10452        // the `const` qualifier, a manual hand-rolled shadow) trips at
10453        // caixa-core build time rather than surfacing as a downstream
10454        // `const`-context regression far from the declaration.
10455        //
10456        // Same shape as the sibling
10457        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
10458        // load-bearing witness lives in the module-scope `const fn`
10459        // wrapper `estrategia_via_const_fn` below: a body that calls
10460        // [`SupervisorSpec::estrategia`] under a `const fn` signature
10461        // is well-formed only when the callee is itself `const fn`,
10462        // side-stepping the destructor-in-const restriction that would
10463        // otherwise block a direct
10464        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
10465        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
10466        // carriers.
10467        //
10468        // The runtime body sweeps every closed-set [`RestartStrategy`]
10469        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
10470        // direct dispatches agree.
10471        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
10472            s.estrategia()
10473        }
10474        for &estrategia in RestartStrategy::ALL {
10475            let s = SupervisorSpec {
10476                estrategia,
10477                max_restarts: 5,
10478                restart_window: Some(Duration::from_secs(60)),
10479                children: Vec::new(),
10480            };
10481            assert_eq!(
10482                estrategia_via_const_fn(&s),
10483                s.estrategia(),
10484                "const-fn-wrapped and direct dispatch on \
10485                 SupervisorSpec::estrategia must agree for {estrategia:?}",
10486            );
10487            assert_eq!(
10488                s.estrategia(),
10489                estrategia,
10490                "SupervisorSpec::estrategia must return the storage-side \
10491                 RestartStrategy verbatim for {estrategia:?} (a violation \
10492                 means the accessor stopped being a raw field-return \
10493                 copy)",
10494            );
10495        }
10496    }
10497
10498    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
10499    // macro definition (see the paired doc-block above the macro
10500    // definition) — every generated `<ctor>(caixa: &str) -> Self`
10501    // constructor folds the uniform `Self::<Variant> { caixa:
10502    // caixa.to_string() }` one-field struct-literal onto one substrate
10503    // primitive. The three per-variant equivalence pins below
10504    // (fail-before-pass-after by construction — a byte-mismatched macro
10505    // arm would trip its equivalence pin first) lock each generated
10506    // constructor to its struct-literal peer under `PartialEq`, so
10507    // every wire-up in [`SupervisorSpec::validate_children`] and
10508    // [`validate_no_self_supervision`] on that variant produces a
10509    // byte-equal `SupervisorError` to the pre-lift open-coded
10510    // struct-literal. The cross-axis pin that follows (non-default
10511    // caixa name) routes the sole constructor input axis through
10512    // `.to_string()`, so the fold does not silently collapse onto a
10513    // fixed name.
10514    //
10515    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
10516    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
10517    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
10518    // `missing_entry_ctor_matches_struct_literal_wrap` /
10519    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
10520    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
10521    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
10522    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
10523    // on the six sibling ctor families the recent trajectory closed
10524    // on the peer `LayoutError` / `AplicacaoError` envelopes.
10525
10526    #[test]
10527    fn empty_child_version_ctor_matches_struct_literal_wrap() {
10528        assert_eq!(
10529            SupervisorError::empty_child_version("worker"),
10530            SupervisorError::EmptyChildVersion {
10531                caixa: "worker".to_string(),
10532            },
10533            "generated empty_child_version ctor must produce byte-equal \
10534             SupervisorError to the open-coded struct-literal wrap on the \
10535             same &str fixture",
10536        );
10537    }
10538
10539    #[test]
10540    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
10541        assert_eq!(
10542            SupervisorError::duplicate_child_caixa("worker"),
10543            SupervisorError::DuplicateChildCaixa {
10544                caixa: "worker".to_string(),
10545            },
10546            "generated duplicate_child_caixa ctor must produce byte-equal \
10547             SupervisorError to the open-coded struct-literal wrap on the \
10548             same &str fixture",
10549        );
10550    }
10551
10552    #[test]
10553    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
10554        assert_eq!(
10555            SupervisorError::child_supervises_self("orquestra"),
10556            SupervisorError::ChildSupervisesSelf {
10557                caixa: "orquestra".to_string(),
10558            },
10559            "generated child_supervises_self ctor must produce byte-equal \
10560             SupervisorError to the open-coded struct-literal wrap on the \
10561             same &str fixture",
10562        );
10563    }
10564
10565    // Per-variant equivalence pins for the two lifted
10566    // [`SupervisorError::child_caixa_invalid`] /
10567    // [`SupervisorError::child_versao_invalid`] inherent constructors
10568    // (fail-before-pass-after by construction — a byte-mismatched ctor body
10569    // would trip its equivalence pin first). Each pins the ctor output to
10570    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
10571    // in [`SupervisorSpec::validate_children`] on the two variants
10572    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
10573    // struct-literal on the same scalar fixtures. Peers of the sibling
10574    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
10575    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
10576    // the peer `AplicacaoError` envelope's
10577    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
10578
10579    #[test]
10580    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
10581        let caixa = "Worker";
10582        let reason = "sample reason text";
10583        assert_eq!(
10584            SupervisorError::child_caixa_invalid(caixa, reason),
10585            SupervisorError::ChildCaixaInvalid {
10586                caixa: caixa.to_string(),
10587                reason: reason.to_string(),
10588            },
10589            "lifted child_caixa_invalid ctor must produce byte-equal \
10590             SupervisorError to the open-coded struct-literal wrap on the \
10591             same (&str, reason) fixture",
10592        );
10593    }
10594
10595    #[test]
10596    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
10597        let caixa = "worker";
10598        let versao = "not-a-req";
10599        let reason = "sample reason text";
10600        assert_eq!(
10601            SupervisorError::child_versao_invalid(caixa, versao, reason),
10602            SupervisorError::ChildVersaoInvalid {
10603                caixa: caixa.to_string(),
10604                versao: versao.to_string(),
10605                reason: reason.to_string(),
10606            },
10607            "lifted child_versao_invalid ctor must produce byte-equal \
10608             SupervisorError to the open-coded struct-literal wrap on the \
10609             same (&str, &str, reason) fixture",
10610        );
10611    }
10612
10613    #[test]
10614    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
10615        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
10616        // against a `&str`-literal vs. `format!(…)` reason input to pin
10617        // both constructors accept the `impl Into<String>` bound
10618        // uniformly, so neither wire-up site drifts under a per-arm
10619        // wrapper transformation on the caller-side `reason` axis. Peer
10620        // of the sibling
10621        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
10622        // sweep on the peer `AplicacaoError` envelope.
10623        let via_literal = "literal reason text";
10624        let via_format = format!("{} reason text", "literal");
10625        assert_eq!(
10626            SupervisorError::child_caixa_invalid("Worker", via_literal),
10627            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
10628        );
10629        assert_eq!(
10630            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
10631            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
10632        );
10633    }
10634
10635    #[test]
10636    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
10637        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
10638        // &str`) through a non-default fixture name against every
10639        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
10640        // so any wrapper-side lowercase / trim / truncate / re-order on
10641        // the `caixa.to_string()` sole-field construction surfaces
10642        // here rather than at a downstream diagnostic-shape mismatch.
10643        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
10644        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
10645        // through_to_string` / `contrato_target_ctors_route_edge_
10646        // triple_through_verbatim` / `contrato_empty_pair_ctors_
10647        // route_edge_pair_through_verbatim` cross-axis routing pins on
10648        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
10649        // here onto the `SupervisorError` `{ caixa: String }` envelope
10650        // so every substrate-primitive ctor family in caixa-core
10651        // guarantees the sole-field construction routes the caller's
10652        // `&str` through `.to_string()` verbatim.
10653        let name = "cache-v2";
10654        assert_eq!(
10655            SupervisorError::empty_child_version(name),
10656            SupervisorError::EmptyChildVersion {
10657                caixa: name.to_string(),
10658            },
10659        );
10660        assert_eq!(
10661            SupervisorError::duplicate_child_caixa(name),
10662            SupervisorError::DuplicateChildCaixa {
10663                caixa: name.to_string(),
10664            },
10665        );
10666        assert_eq!(
10667            SupervisorError::child_supervises_self(name),
10668            SupervisorError::ChildSupervisesSelf {
10669                caixa: name.to_string(),
10670            },
10671        );
10672    }
10673
10674    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
10675    //
10676    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
10677    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
10678    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
10679    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
10680    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
10681    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
10682    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
10683    // / silent constant-substitution on any one variant surfaces here rather
10684    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
10685    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
10686    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
10687    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
10688    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
10689    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
10690    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
10691    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
10692    #[test]
10693    fn no_children_ctor_matches_struct_literal_wrap() {
10694        let estrategia = RestartStrategy::OneForAll;
10695        assert_eq!(
10696            SupervisorError::no_children(estrategia),
10697            SupervisorError::NoChildren { estrategia },
10698            "generated no_children ctor must produce byte-equal \
10699             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
10700             on the same `Copy`-`RestartStrategy` fixture",
10701        );
10702    }
10703
10704    #[test]
10705    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
10706        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
10707        assert_eq!(
10708            SupervisorError::max_restarts_exceeds_cap(max_restarts),
10709            SupervisorError::MaxRestartsExceedsCap { max_restarts },
10710            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
10711             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
10712             struct-literal wrap on the same `Copy`-`u32` fixture",
10713        );
10714    }
10715
10716    #[test]
10717    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
10718        let window = Duration::from_micros(1_500);
10719        assert_eq!(
10720            SupervisorError::restart_window_not_canonical(window),
10721            SupervisorError::RestartWindowNotCanonical { window },
10722            "generated restart_window_not_canonical ctor must produce \
10723             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
10724             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
10725        );
10726    }
10727
10728    #[test]
10729    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
10730        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
10731        assert_eq!(
10732            SupervisorError::restart_window_exceeds_cap(window),
10733            SupervisorError::RestartWindowExceedsCap { window },
10734            "generated restart_window_exceeds_cap ctor must produce \
10735             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
10736             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
10737        );
10738    }
10739
10740    #[test]
10741    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
10742        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
10743        // constructor input axis through a non-default `Copy` fixture against
10744        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
10745        // side silent `.into()` / silent constant-substitution / silent field
10746        // re-name away from the canonical `estrategia | max_restarts | window`
10747        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
10748        // axis silently rerouted through some other `Copy` coercion, surfaces
10749        // here rather than at a downstream per-`:supervisor` diagnostic-shape
10750        // drift. Peer of the sibling
10751        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
10752        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
10753        // envelope's per-`:politicas` per-axis ctor family, extended here onto
10754        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
10755        // variant family folded onto a substrate primitive.
10756        //
10757        // Fixtures picked out of each variant's accept-set boundary rather
10758        // than the default value so a silent constant-substitution to a per-
10759        // variant sentinel surfaces here on the structural-equality assertion.
10760        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
10761        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
10762        // isn't the `SimpleOneForOne` arm the sibling
10763        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
10764        // `max_restarts` fixture picks an above-cap magnitude the cap arm
10765        // rejects; the two `Duration` fixtures pick the sub-millisecond and
10766        // above-cap ends of the `:restart-window` canonical-form + cap
10767        // bracket respectively.
10768        let estrategia = RestartStrategy::RestForOne;
10769        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
10770        let sub_ms = Duration::from_micros(1_500);
10771        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
10772        assert_eq!(
10773            SupervisorError::no_children(estrategia),
10774            SupervisorError::NoChildren { estrategia },
10775        );
10776        assert_eq!(
10777            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
10778            SupervisorError::MaxRestartsExceedsCap {
10779                max_restarts: above_cap_restarts,
10780            },
10781        );
10782        assert_eq!(
10783            SupervisorError::restart_window_not_canonical(sub_ms),
10784            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
10785        );
10786        assert_eq!(
10787            SupervisorError::restart_window_exceeds_cap(above_hour),
10788            SupervisorError::RestartWindowExceedsCap { window: above_hour },
10789        );
10790    }
10791
10792    #[test]
10793    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
10794        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
10795        // generated ctor `const fn` so a caller can pin a `SupervisorError`
10796        // at compile time — the same zero-runtime-work property the pre-lift
10797        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
10798        // its `Copy`-pass-through construction path (no `.to_string()` /
10799        // `.into()` allocation, no branching). If any future edit silently
10800        // drops the `const` qualifier from the macro body the per-arm `const`
10801        // bindings below fail to compile, which surfaces the regression at
10802        // the substrate-primitive definition rather than at some downstream
10803        // consumer that had come to rely on the `const`-constructibility.
10804        // Peer of the sibling
10805        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
10806        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
10807        // per-`:politicas` per-axis ctor family.
10808        const NO_CHILDREN: SupervisorError =
10809            SupervisorError::no_children(RestartStrategy::OneForAll);
10810        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
10811        const WINDOW_NC: SupervisorError =
10812            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
10813        const WINDOW_CAP: SupervisorError =
10814            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
10815        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
10816        assert!(matches!(
10817            MAX_RESTARTS_CAP,
10818            SupervisorError::MaxRestartsExceedsCap { .. }
10819        ));
10820        assert!(matches!(
10821            WINDOW_NC,
10822            SupervisorError::RestartWindowNotCanonical { .. }
10823        ));
10824        assert!(matches!(
10825            WINDOW_CAP,
10826            SupervisorError::RestartWindowExceedsCap { .. }
10827        ));
10828    }
10829}