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/// Per-child restart policy.
619///
620/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
621#[derive(
622    Serialize,
623    Deserialize,
624    Debug,
625    Clone,
626    Copy,
627    PartialEq,
628    Eq,
629    Hash,
630    gen_platform::TypedDispatcher,
631    gen_platform::Discriminant,
632    gen_platform::IsVariant,
633    gen_platform::FromStrKind,
634)]
635pub enum RestartPolicy {
636    /// Always restart the child, regardless of how it died. Used for
637    /// long-running services that must always be up.
638    Permanent,
639    /// Never restart. Used for one-shot work whose completion is
640    /// itself the success signal (`oneShot` triggers map here).
641    Temporary,
642    /// Restart only when the child died *abnormally* (non-zero exit
643    /// or unhandled exception). A clean exit completes the child.
644    Transient,
645}
646
647impl Default for RestartPolicy {
648    fn default() -> Self {
649        // Route the [`Default for RestartPolicy`] impl's return arm through
650        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
651        // `pub const` rather than a raw `Self::Permanent` arm — one source
652        // of truth for the Erlang/OTP-canonical `permanent` worker-child
653        // default across the two production consumers that currently
654        // dispatch on it (this impl at the [`RestartPolicy::default`] call
655        // and the serde-side `#[serde(default)]` on
656        // [`ChildSpec::restart`] that resolves an author-omitted
657        // `:children :restart` slot through `RestartPolicy::default()`).
658        // Peer of the sibling per-`:supervisor` axis
659        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
660        // route (95ffacc) — the two impls now share one substrate-primitive
661        // lift discipline, so any future coherent rebrand of the OTP-shape
662        // supervisor+child default set migrates through typed constants in
663        // lockstep instead of splitting a lifted supervisor half against
664        // an open-coded child half. Pinned by
665        // `restart_policy_default_routes_through_lifted_default` +
666        // `child_spec_serde_default_restart_routes_through_lifted_default`
667        // in the tests module.
668        SUPERVISOR_CHILD_RESTART_DEFAULT
669    }
670}
671
672impl RestartPolicy {
673    /// Exhaustive iteration surface for every consumer that walks the
674    /// closed three-arm [`RestartPolicy`] discriminator set (the future
675    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
676    /// per-child admission-webhook rejection body naming the accepted-
677    /// `:restart` list, a future `feira supervisor --restart …` CLI
678    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
679    /// over the slice, the future `feira app graph` per-child restart
680    /// column, any future round-trip fuzz harness that sweeps every
681    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
682    /// theory
683    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
684    /// might reach for once the three canonical OTP restart policies
685    /// stop covering the substrate's discovered load-shape) extends
686    /// this slice as one edit and every consumer picks up the new entry
687    /// by construction; the compiler-checked exhaustiveness on the
688    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
689    /// is the build-time guarantee that no arm forgets to grow.
690    ///
691    /// Peer of the sibling closed-set typed enums'
692    /// [`RestartStrategy::ALL`] (4eec29c) /
693    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
694    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
695    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
696    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
697    /// surfaces — the sixth (and the third and final M2 OTP-shape)
698    /// closed-set typed enum on the caixa surface to converge onto the
699    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
700    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
701    /// sibling-restart-strategy axis; this closes the per-child
702    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
703    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
704
705    /// Canonical PascalCase discriminator scalar this variant serializes
706    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
707    /// arms return the paired
708    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
709    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
710    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
711    /// constants so every substrate consumer that dispatches on the
712    /// per-child restart-decision policy (the future wasm-operator's
713    /// per-child post-exit restart-decision branch, the future M4
714    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
715    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
716    /// reconciliation scheduler's per-child-policy fan-out) reads the
717    /// same byte-string the `Serialize` derive emits — the pin test in
718    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
719    /// asserts the two paths agree, peer of the M2
720    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
721    /// sibling-restart-strategy axis and the M3
722    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
723    /// per-Aplicacao distribution-strategy axis — the third of three
724    /// OTP-shaped closed-enum discriminator axes on the caixa typed
725    /// surface to converge onto the same three-path-convergence
726    /// (`Serialize` derive → `as_str` helper → lifted constant)
727    /// drift-detection posture.
728    #[must_use]
729    pub const fn as_str(self) -> &'static str {
730        match self {
731            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
732            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
733            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
734        }
735    }
736
737    /// Substrate-canonical reverse projection on the `:children :restart`
738    /// closed-set axis — parses the `PascalCase` discriminator scalar
739    /// back to the typed variant, or `None` when `s` is outside the
740    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
741    /// the same lifted
742    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
743    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
744    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
745    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
746    /// of the round-trip migrate through one caixa-core edit on any
747    /// future arm addition.
748    ///
749    /// Prior to this lift the substrate carried only the forward
750    /// `Self → &str` projection on the OTP per-child restart-policy
751    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
752    /// impl routed through it, the `Serialize` derive that emits the
753    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
754    /// plus the kebab-case dispatcher-catalog identity via
755    /// [`Self::discriminant`] — every non-serde consumer that wanted to
756    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
757    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
758    /// "Transient" => …, _ => … }` cascade that expressed no
759    /// compile-time link back to the typed variant's canonical lifted
760    /// constant. A future variant rename or per-arm serde-attribute
761    /// drift would silently split the wire byte-string one non-serde
762    /// consumer parsed from the one the emitter wrote, with the failure
763    /// surfacing at the operator's reconcile posture (a `:temporary`
764    /// `oneShot` child being restarted on clean exit, treating the
765    /// successful-completion signal as failure and re-running the
766    /// completion-terminal one-shot indefinitely; a `:transient` child
767    /// that clean-exited being restarted, masking the clean-completion
768    /// contract) far from the rebrand commit and with no field naming
769    /// the drift.
770    ///
771    /// Distinct axis from the [`std::str::FromStr`] impl the
772    /// [`gen_platform::FromStrKind`] derive already installs on this
773    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
774    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
775    /// `"transient"` — the inverse of [`Self::discriminant`]), while
776    /// this method inverts the `PascalCase` wire byte-string
777    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
778    /// catalog identity live in kebab-case (where every peer catalog
779    /// identifier already lives) without forcing a wire-format rename
780    /// on the tatara-lisp author surface (`:restart Permanent`,
781    /// `PascalCase`) — the same two-axis distinction the sibling
782    /// [`RestartStrategy::from_wire`] (4eec29c) /
783    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
784    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
785    /// carry on their peer closed-set typed-enum wire round-trips.
786    ///
787    /// Same closed-set-reverse-projection discipline the sibling
788    /// [`RestartStrategy::from_wire`] (4eec29c) /
789    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
790    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
791    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
792    /// carry on the peer wire-side `str → Self` axes — extended onto
793    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
794    /// sixth substrate-side closed-set typed enum (and the third and
795    /// final OTP-shape closed-enum discriminator axis) to converge on
796    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
797    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
798    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
799    /// derive already installs on the sibling kebab-case axis. Returns
800    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
801    /// shapes: the caller picks the diagnostic form appropriate for
802    /// its use site.
803    #[must_use]
804    pub fn from_wire(s: &str) -> Option<Self> {
805        match s {
806            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
807            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
808            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
809            _ => None,
810        }
811    }
812}
813
814/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
815/// pretty-printed byte-string every consumer that formats the policy as
816/// user-facing text lands on (the future wasm-operator's per-child
817/// post-exit restart-decision diagnostic line, the future `feira app
818/// graph` per-child restart column, the future M4
819/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
820/// admission-webhook rejection body) reaches for the same lifted
821/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
822/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
823/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
824/// wire-format `Serialize` derive already emits under
825/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
826/// [`RestartPolicy::as_str`] helper already returns.
827///
828/// Pre-convergence the two paths structurally disagreed — the
829/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
830/// route (now retired here) sent [`std::fmt::Display`] through the
831/// gen-platform discriminant catalog string, which arrives kebab-case as
832/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
833/// (whose variant names each collapse to their own lowercase form under
834/// the kebab-case transform), while the wire format ran as `PascalCase`
835/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
836/// serde derive. Every consumer that formatted the policy for a
837/// diagnostic line, a graph column, or a rejection body under
838/// `format!("{v}")` therefore landed under a different byte-string than
839/// the wire format the operator's per-child-policy dispatch keyed off —
840/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
841/// diagnostic quoting `"permanent"` while the wire scalar the operator
842/// probed was `"Permanent"`) surfaced as a confused correlate at
843/// operator-log time far from the two-declaration site.
844///
845/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
846/// path: every `format!("{v}")` call reaches the same lifted
847/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
848/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
849/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
850/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
851/// byte-string per variant. A future variant rename or
852/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
853/// exactly one place, structurally.
854///
855/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
856/// (from `#[derive(gen_platform::Discriminant)]`) still returns
857/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
858/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
859/// registration keys the catalog off the same kebab identity. The two
860/// naming worlds now live on separate typed methods (`Display` /
861/// `as_str` for the wire byte-string, `discriminant` for the catalog
862/// identity) rather than sharing one `Display` route that structurally
863/// disagrees with the wire format.
864///
865/// Pin tests
866/// [`tests::restart_policy_display_routes_through_as_str_helper`]
867/// and
868/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
869/// assert the three paths agree byte-for-byte on every variant, so a
870/// future variant rename or per-arm serde attribute drift is a build
871/// error visible at caixa-core test time, not a silent per-consumer
872/// dispatch miss at apply / reconcile time.
873///
874/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
875/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
876/// and the sibling [`RestartStrategy`] `Display` impl on the
877/// per-supervisor sibling-restart-strategy axis — same three-path-
878/// convergence discipline, extended to close the third and final of
879/// three OTP-shaped closed-enum discriminator axes on the caixa typed
880/// surface.
881impl std::fmt::Display for RestartPolicy {
882    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
883        f.write_str(self.as_str())
884    }
885}
886
887/// Substrate-canonical [`AsRef<str>`] projection on the M2
888/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
889/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
890/// scalar accessor the paired [`std::fmt::Display`] impl and the
891/// un-`rename`d [`serde::Serialize`] derive already key off, so any
892/// future consumer that binds a [`RestartPolicy`] through the
893/// standard-library `impl AsRef<str>` bound (a future
894/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
895/// composes the emitted `PascalCase` wire scalar into a
896/// [`std::process::Command::arg`] shell-out of the future
897/// wasm-operator's per-child admission gate, a per-child structured-
898/// log recorder on the future `caixa-operator`'s hierarchical
899/// reconciliation surface that accepts `impl AsRef<str>` at the
900/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
901/// lookup keyed on the restart-policy wire byte through
902/// `map.get::<str>(policy.as_ref())` on a future per-policy
903/// dispatch table) reaches the paired
904/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
905/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
906/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
907/// lifted-const through one substrate-primitive dispatch rather
908/// than an open-coded `.as_str()` projection at every wire-up.
909///
910/// Peer of the sibling [`std::fmt::Display`] impl on the same
911/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
912/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
913/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
914/// byte-string per instance by construction. A future variant rename
915/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
916/// enum reaches every one of the three paths (plus the wire-format
917/// `Serialize` derive that already routes through the same lifted
918/// const) through exactly one caixa-core edit.
919///
920/// Same "route the trait impl through the substrate-primitive
921/// accessor" discipline the sibling [`crate::CaixaVersion`]
922/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
923/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
924/// the axis onto the paired per-child-restart-decision-policy
925/// sibling on the same M2 `:supervisor` slot (the second M2
926/// OTP-shape closed-set typed enum to converge onto the standard-
927/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
928/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
929/// primitive so a caller who has one has both; before this lift,
930/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
931/// [`AsRef<str>`] impl the convention names.
932///
933/// Pinned load-bearing by
934/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
935/// (byte-parity pin against [`RestartPolicy::as_str`] across the
936/// three-arm closed set) and
937/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
938/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
939/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
940/// arm) — any future silent detour that routes the impl through a
941/// divergent projection (a per-arm inline `match self { … }`
942/// re-inlining that opens a compile-time link to the un-lifted
943/// arm-literal, a swap onto the kebab-case
944/// [`gen_platform::Discriminant`] catalog identity that would
945/// collide the wire axis with the dispatcher-catalog axis) trips at
946/// caixa-core test time under `assert_eq!` rather than at a
947/// downstream `impl AsRef<str>`-bound consumer's silent split.
948impl AsRef<str> for RestartPolicy {
949    fn as_ref(&self) -> &str {
950        self.as_str()
951    }
952}
953
954/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
955/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
956/// byte-for-byte through the paired substrate-primitive
957/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
958/// consumer that binds a `PascalCase` `:children :restart` wire
959/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
960/// axis (a future [`caixa-feira`] `feira supervisor --restart
961/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
962/// `let restart: RestartPolicy = s.try_into()?`, a future
963/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
964/// `spec.children[*].restart: String` field through
965/// `RestartPolicy::try_from(&s)?`, a generic
966/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
967/// set typed enums) reaches the same three-arm accept-set the sibling
968/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
969/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
970/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
971/// … }` cascade whose arm-set has no compile-time link back to the
972/// substrate primitive.
973///
974/// Complements the pre-existing forward-projection triple
975/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
976/// with the paired trait-idiomatic reverse-projection axis: Rust-side
977/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
978/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
979/// caller who can project *out to* a `&str` can also project *in from*
980/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
981/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
982/// lint the sibling method-named [`RestartPolicy::from_wire`] would
983/// trigger under a `FromStr` impl and to avoid colliding with the
984/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
985/// already installs on the paired *kebab-case dispatcher-catalog* axis
986/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
987/// inverse of [`Self::discriminant`]) — this impl closes the trait-
988/// idiomatic reverse axis on the *`PascalCase` wire* half without
989/// disturbing either the method-named `from_wire` shape every sibling
990/// closed-set typed enum on the substrate already carries or the
991/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
992/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
993///
994/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
995/// `Option<Self>` return-shape's deliberate deferral of error typing: the
996/// caller picks the diagnostic form appropriate for its use site (a
997/// future `feira supervisor --restart` arg-parse composes its own
998/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
999/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1000/// wraps the `Err(())` outcome with the accepted-set enumeration for
1001/// operator diagnostics, a `Result::map_err` at the call site lifts the
1002/// unit-error to a per-verb error type). Same shape the peer
1003/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1004/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1005/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1006/// their peer closed-set typed enums' reverse projections.
1007///
1008/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1009/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1010/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1011/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1012/// might reach for once the three canonical OTP restart policies stop
1013/// covering the substrate's discovered load-shape) grows the trait-
1014/// idiomatic axis by construction — one caixa-core edit on
1015/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1016/// projection every existing consumer keys off and the trait-idiomatic
1017/// reverse projection this impl exposes, without a coordinated rewrite
1018/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1019///
1020/// Extends the substrate-wide closed-set-enum reverse-projection family
1021/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1022/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1023/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1024/// closed-enum discriminator axis on the caixa surface — the paired
1025/// per-child `:children :restart` closed set the future wasm-operator's
1026/// hierarchical reconciliation scheduler's per-child post-exit
1027/// restart-decision branch keys off end-to-end.
1028///
1029/// Pinned load-bearing by
1030/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1031/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1032/// three-arm accept-set),
1033/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1034/// (rejection witness against silent accept-set widening), and
1035/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1036/// (cross-axis partition pin locking the trait and method-named
1037/// projections onto one accept-set).
1038impl TryFrom<&str> for RestartPolicy {
1039    type Error = ();
1040
1041    fn try_from(s: &str) -> Result<Self, Self::Error> {
1042        Self::from_wire(s).ok_or(())
1043    }
1044}
1045
1046/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1047/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1048/// byte-for-byte through the paired substrate-primitive
1049/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1050/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1051/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1052/// &str` with `'static` lifetime, so the trait's return-type promise is
1053/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1054/// literal.
1055///
1056/// Every future consumer that specifically needs `&'static str` lifetime
1057/// bytes on the per-child restart-decision axis (a
1058/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1059/// arm's typing demands `&'static str`, a
1060/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1061/// on the future M4 admission-webhook rejection body where the
1062/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1063/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1064/// or error formatter that requires the `'static` bound) reaches the same
1065/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1066/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1067/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1068/// primitive dispatch rather than an open-coded per-arm literal cascade
1069/// whose arm-set has no compile-time link back to the substrate primitive.
1070///
1071/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1072/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1073/// the second (and second-of-two-in-M2) closed-set typed enum on the
1074/// caixa surface to converge onto the paired trait-idiomatic forward-
1075/// projection axis. With this lift the paired per-child
1076/// `:children :restart` closed-set typed enum carries the full sibling
1077/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1078/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1079/// lift) plus the round-trip witness through both the trait-idiomatic
1080/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1081/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1082/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1083/// (an OTP-`intrinsic` fourth arm the theory
1084/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1085/// might reach for once the three canonical OTP restart policies stop
1086/// covering the substrate's discovered load-shape) grows the trait-
1087/// idiomatic forward axis by construction: one caixa-core edit on
1088/// [`RestartPolicy::as_str`] extends every one of the five sibling
1089/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1090/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1091/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1092/// bytes) without a coordinated rewrite across every future
1093/// `Into<&'static str>`-bound consumer's arm-set.
1094///
1095/// Pinned load-bearing by
1096/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1097/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1098/// three-arm emit-set, plus a `const`-context materialization witness for
1099/// the `&'static str` lifetime promise) and
1100/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1101/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1102/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1103/// round-trip witness through the paired trait-idiomatic reverse-
1104/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1105/// `policy.into::<&'static str>()` output re-parses back through
1106/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1107/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1108impl From<RestartPolicy> for &'static str {
1109    fn from(policy: RestartPolicy) -> &'static str {
1110        policy.as_str()
1111    }
1112}
1113
1114/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
1115/// *borrowed* input onto the `&'static str` axis — the borrowed-input
1116/// companion to the paired owned-input [`From<RestartPolicy> for
1117/// &'static str`] impl immediately above. Routes byte-for-byte through
1118/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
1119/// fn` accessor so every consumer that binds a `&RestartPolicy`
1120/// through the standard-library `.into()` / [`From<&Self> for &'static
1121/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
1122/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
1123/// whose iterator over `&'static [RestartPolicy]` yields
1124/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
1125/// [`From<RestartPolicy>`] axis alone forces every call site through
1126/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
1127/// rather than the direct trait-idiomatic projection; a future generic
1128/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
1129/// that walks the `iter().map(Into::into)` shape verbatim across every
1130/// substrate-wide closed-set typed enum; the future wasm-operator's
1131/// per-child post-exit restart-decision diagnostic line that composes
1132/// the accepted-set enumeration from an iterated
1133/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1134/// per-arm `match p { … }` cascade; a future
1135/// `HashMap::<&'static str, RestartPolicy>::from_iter(
1136///     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
1137/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
1138/// cannot compose without this borrowed-input axis in place) reaches
1139/// the same three-arm lifted
1140/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1141/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1142/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1143/// paired owned-input [`From<RestartPolicy> for &'static str`], the
1144/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
1145/// [`RestartPolicy::as_str`] surfaces already return.
1146///
1147/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
1148/// forward-projection family opened on [`crate::dep::DepList`]
1149/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
1150/// [`crate::CaixaDialeto`] (807b0b5), and the paired
1151/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
1152/// (e941836). Rust's `From` trait does not auto-derive the
1153/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
1154/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
1155/// exist in `core`), so every closed-set typed enum that carries the
1156/// owned-input axis but not the borrowed-input axis forces every
1157/// borrowed-input call site through a `.copied()` /
1158/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
1159/// type bounds have no compile-time link to the substrate primitive.
1160/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
1161/// OTP-shape peer to converge onto this campaign — sibling of the
1162/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
1163/// with this lift both closed-set typed enums on the M2 `:supervisor`
1164/// slot now carry the full sibling quintet ([`std::fmt::Display`],
1165/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
1166/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
1167/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
1168/// forward-projection axis on the M2 OTP-shape slot as a unit.
1169///
1170/// Same three-path convergence discipline as the paired owned-input
1171/// impl (this borrowed-input axis, the paired owned-input
1172/// [`From<RestartPolicy> for &'static str`], and
1173/// [`RestartPolicy::as_str`] all route through the same lifted
1174/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
1175/// variant rename or per-arm serde-attribute drift reaches every one
1176/// of the six sibling forward-projection paths
1177/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1178/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
1179/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
1180/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
1181/// edit.
1182///
1183/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
1184/// parse share the same `PascalCase` vocabulary by construction, so
1185/// the borrowed-input forward axis and the reverse axis compose
1186/// directly — the round-trip witness pin below locks this direct
1187/// composition without the intermediate wire-vocab hop the peer
1188/// [`crate::CaixaKind`] axis pair requires.
1189///
1190/// Pinned load-bearing by
1191/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
1192/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1193/// three-arm emit-set via a borrowed input, plus a `const`-context
1194/// materialization witness for the `&'static str` lifetime promise,
1195/// plus a blanket `.into()` shape) and
1196/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
1197/// (cross-axis partition pin against the paired owned-input
1198/// [`From<RestartPolicy> for &'static str`] impl, plus a
1199/// `.iter().map(Into::into)` pipe witness over
1200/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1201/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
1202/// Self` round-trip without the wire-vocab intermediate the peer
1203/// [`crate::CaixaKind`] axis pair requires).
1204impl From<&RestartPolicy> for &'static str {
1205    fn from(policy: &RestartPolicy) -> &'static str {
1206        policy.as_str()
1207    }
1208}
1209
1210// Fleet-wide dispatcher-catalog registrations for caixa's OTP
1211// supervisor surface — two more typed shadows over Erlang/OTP
1212// primitives the substrate now mechanically tracks (see
1213// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
1214// theory/TYPED-ABSORPTION.md for the absorption arc).
1215gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
1216gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
1217
1218/// One child entry in the supervisor's `:children` list.
1219///
1220/// Every child references another caixa by `:caixa <nome>` + version
1221/// constraint. The supervisor materializes one ComputeUnit per entry.
1222#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1223#[serde(rename_all = "camelCase")]
1224pub struct ChildSpec {
1225    /// The child caixa's `:nome`. Must resolve via the same dependency
1226    /// resolution path as `:deps` (caixa-resolver).
1227    pub caixa: String,
1228
1229    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
1230    /// [`crate::dep::Dep::versao`].
1231    pub versao: String,
1232
1233    /// Restart policy — an author-omitted slot degrades onto the
1234    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
1235    /// (`permanent`, the Erlang/OTP worker-child default) through the
1236    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
1237    /// to.
1238    #[serde(default)]
1239    pub restart: RestartPolicy,
1240}
1241
1242impl ChildSpec {
1243    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
1244    /// accessor every consumer that reads the OTP-shape supervised
1245    /// child's identity keys off — returns the author-declared
1246    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
1247    /// from the typed slot's own [`String`] storage.
1248    ///
1249    /// The `:children :caixa` slot carries the DNS-1123 label — the
1250    /// child caixa's `:nome` — that every emitted cluster artifact
1251    /// derives its `metadata.name` from verbatim: the rendered
1252    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
1253    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
1254    /// identity, and the per-child K8s Service `metadata.name` the
1255    /// future wasm-operator (M3) provisions for inter-child supervision-
1256    /// tree wiring. Every downstream consumer that fans on the child's
1257    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
1258    /// per-child DNS-1123 gate at
1259    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
1260    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
1261    /// [`validate_no_self_supervision`] cross-slot equality check
1262    /// against the parent's `:nome`, every `SupervisorError` variant
1263    /// carrying the offending child caixa verbatim for `feira lint`
1264    /// rendering, the future wasm-operator's hierarchical reconciliation
1265    /// scheduler's per-child ComputeUnit-name projection, the future M4
1266    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1267    /// admission webhook).
1268    ///
1269    /// Prior to this lift the `.caixa` byte-string was accessed inline
1270    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
1271    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
1272    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
1273    /// carriers' `child.caixa.clone()`, the dedup key's
1274    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
1275    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
1276    /// field-accesses that expressed no compile-time link back to the
1277    /// typed slot. A future extension of the `:children :caixa` axis to
1278    /// a richer author surface (a per-cluster alias table the operator
1279    /// pins through a future `:placement`-scoped slot on the supervisor
1280    /// tree, a namespace-qualified rewrite the M4 CR materializer
1281    /// applies per-CR, a per-child overlay from the future `:children
1282    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1283    /// acknowledges) would have had to be threaded through every
1284    /// open-coded copy in lockstep or one consumer would silently
1285    /// disagree with the peers on which caixa a given child resolves to
1286    /// — a child-set lookup that treated the name as `"cart-worker"`
1287    /// while the peer duplicate-detector treated it as
1288    /// `"tenant-a/cart-worker"` would silently split the
1289    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
1290    /// self-supervision detector's parent-equality check, a two-consumer
1291    /// split at the validator far from the source `caixa.lisp` with no
1292    /// field naming the identity-drift root cause. Lifting the resolution
1293    /// rule to a typed method on the substrate primitive means every
1294    /// downstream consumer of the Supervisor's per-`:children` identity
1295    /// surface reaches for exactly one typed dispatch — the resolver's
1296    /// accept-set migrates as a unit on any future axis addition.
1297    ///
1298    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
1299    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
1300    /// mesh-slot surface — same "one typed dispatch on the substrate
1301    /// primitive, thin projections at each consumer" discipline extended
1302    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
1303    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
1304    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
1305    /// accessor discipline for the shared substrate concept "another
1306    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
1307    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
1308    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
1309    /// slot family's typed-accessor discipline now spans both the
1310    /// upgrade axis (`:upgrade-from`) and the supervision axis
1311    /// (`:children`), matching the closed M3 mesh-slot accessor family's
1312    /// shape. Named `nome()` to match the tatara-lisp author-surface
1313    /// term the field's docstring already reaches for ("The child
1314    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
1315    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
1316    /// discipline the substrate already carries — the accessor's name
1317    /// maps directly onto the canonical caixa-identity vocabulary rather
1318    /// than shadowing the field's storage-side `caixa` label.
1319    #[must_use]
1320    pub const fn nome(&self) -> &str {
1321        self.caixa.as_str()
1322    }
1323
1324    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
1325    /// requirement scalar accessor every consumer that reads the OTP-shape
1326    /// supervised child's version pin keys off — returns the author-declared
1327    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
1328    /// the typed slot's own [`String`] storage.
1329    ///
1330    /// The `:children :versao` slot carries the Cargo-shaped semver
1331    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
1332    /// which release of the supervised child caixa the OTP-shape supervisor
1333    /// tree materializes against — the same requirement grammar the peer
1334    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
1335    /// shared [`crate::render::require_valid_versao_requirement`] cascade
1336    /// and the shared [`crate::version::parse_requirement`] parser. Every
1337    /// downstream consumer that fans on the child's version pin keys off
1338    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
1339    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
1340    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
1341    /// for `feira lint` rendering, every future per-cluster version-lock
1342    /// overlay the caixa-operator's hierarchical reconciliation scheduler
1343    /// pins through a future `:placement`-scoped supervisor-tree slot, the
1344    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1345    /// per-child version resolver, the future wasm-operator's per-child
1346    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
1347    ///
1348    /// Prior to this lift the `.versao` byte-string was accessed inline at
1349    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
1350    /// [`SupervisorSpec::validate`] requirement-gate call
1351    /// `require_valid_versao_requirement(&child.versao, …)` and the
1352    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
1353    /// `versao: child.versao.clone()` — two open-coded field-accesses that
1354    /// expressed no compile-time link back to the typed slot. A future
1355    /// extension of the `:children :versao` axis to a richer author surface
1356    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1357    /// flow, a lacre-projected concrete-version rewrite the operator
1358    /// materializes at CR-admission time, a future `:children :versao-lock`
1359    /// per-cluster override slot the wasm-operator's hierarchical
1360    /// reconciliation scheduler authors per-CR) would have had to be
1361    /// threaded through both open-coded copies in lockstep or one consumer
1362    /// would silently disagree with the peer on which release constraint a
1363    /// given child resolves to — the requirement-gate call reading
1364    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
1365    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
1366    /// the actual gate rejection input, a two-consumer split at the
1367    /// validator far from the source `caixa.lisp` with no field naming the
1368    /// version-pin drift root cause. Lifting the resolution rule to a typed
1369    /// method on the substrate primitive means every downstream
1370    /// requirement-facing consumer of the Supervisor's per-`:children`
1371    /// version-pin surface reaches for exactly one typed dispatch — the
1372    /// resolver's accept-set migrates as a unit on any future axis addition.
1373    ///
1374    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
1375    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
1376    /// surface — same "one typed dispatch on the substrate primitive, thin
1377    /// projections at each consumer" discipline extended onto the M2
1378    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
1379    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
1380    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
1381    /// one accessor discipline for the shared substrate concept "another
1382    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
1383    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
1384    /// `:nome` scalar accessor — the pair
1385    /// `(nome(), versao_requirement())` jointly projects the
1386    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
1387    /// that fans on per-child identity + version pin keys off, closing the
1388    /// last unlifted per-`:children` `String`-carry axis so every downstream
1389    /// per-`:children` reader now routes through a typed dispatch on the
1390    /// substrate primitive. Named `versao_requirement()` rather than
1391    /// `versao()` because the field's storage-side `.versao` label is
1392    /// already the author-surface term (`:versao`); the accessor's name
1393    /// carries the semantic role — the semver *requirement* string the
1394    /// shared [`crate::version::parse_requirement`] entry-point consumes —
1395    /// so a raw field access and a typed dispatch read differently at every
1396    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
1397    /// naming discipline verbatim.
1398    #[must_use]
1399    pub const fn versao_requirement(&self) -> &str {
1400        self.versao.as_str()
1401    }
1402
1403    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
1404    /// per-child post-exit restart-decision policy scalar accessor every
1405    /// consumer that dispatches on the supervised child's post-exit
1406    /// reconcile posture keys off — returns the author-declared
1407    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
1408    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
1409    /// storage.
1410    ///
1411    /// The `:children :restart` slot carries the closed-set OTP-shaped
1412    /// per-child restart-decision policy discriminator
1413    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
1414    /// worker-child default; [`RestartPolicy::Transient`] — restart only
1415    /// on abnormal exit, the OTP `transient` clean-completion-aware
1416    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
1417    /// `temporary` one-shot default) that every downstream consumer of
1418    /// the Supervisor's per-child post-exit reconcile branch keys off.
1419    /// Every future downstream consumer that fans on the per-child
1420    /// restart-decision keys off this scalar (the future `feira app
1421    /// graph` per-child restart column, the future wasm-operator's
1422    /// per-child post-exit restart-decision branch, the future M4
1423    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1424    /// admission webhook, the `caixa-operator`'s hierarchical
1425    /// reconciliation scheduler's per-child post-exit reconcile branch,
1426    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
1427    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1428    /// pin threads through).
1429    ///
1430    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
1431    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
1432    /// scalar accessor and the M3 mesh-slot
1433    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
1434    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
1435    /// — same "one typed dispatch on the substrate primitive,
1436    /// `Copy`-projected closed-set enum-arm discriminator that partitions
1437    /// the downstream renderer's per-arm fan-out" discipline extended
1438    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
1439    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
1440    /// [`ChildSpec`] type — companion to the sibling per-`:children`
1441    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
1442    /// and the per-`:children` [`ChildSpec::versao_requirement`]
1443    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
1444    /// on the sibling `String`-carry axes. The triple
1445    /// `(nome(), versao_requirement(), restart())` jointly projects the
1446    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
1447    /// tree consumer that fans on per-child identity + version pin +
1448    /// restart-decision keys off, closing the last unlifted per-`:children`
1449    /// axis so every downstream per-`:children` reader now routes through
1450    /// a typed dispatch on the substrate primitive. Named `restart()` to
1451    /// match the storage field's name and the author-surface
1452    /// `:children :restart` slot term verbatim; the accessor's identity
1453    /// name maps onto the canonical OTP-shape per-child restart-decision-
1454    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
1455    /// carries.
1456    ///
1457    /// Declared `pub const fn` to close the last non-`const`
1458    /// `Copy`-return raw-field-getter posture on the M2
1459    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
1460    /// of the sibling M2 per-`:supervisor`
1461    /// [`SupervisorSpec::estrategia`] (converted in this commit)
1462    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
1463    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1464    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
1465    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
1466    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
1467    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
1468    /// downstream substrate-side `const`-context consumer of the
1469    /// per-`:children` restart-decision-policy scalar (a future
1470    /// module-scope `const _:() = assert!(matches!(child.restart(),
1471    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
1472    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1473    /// admission-webhook `const fn` per-child restart-decision floor
1474    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
1475    /// composer over the substrate primitive that fans on the per-child
1476    /// restart-decision policy at compile time) now reaches through the
1477    /// same typed dispatch on the substrate primitive at const-eval
1478    /// time as at runtime. A future non-`Copy`-return promotion of the
1479    /// scalar (an `Option<RestartPolicy>`-shape migration on the
1480    /// per-child restart-decision axis once heterogeneous per-cluster
1481    /// restart-policy overlays land, a per-tenant restart-policy-alias
1482    /// table the M4 CR materializer resolves per-CR) that would drop
1483    /// the `const` qualifier fails the fail-before-pass-after pin
1484    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
1485    /// build time rather than surfacing as a downstream consumer
1486    /// regression.
1487    #[must_use]
1488    pub const fn restart(&self) -> RestartPolicy {
1489        self.restart
1490    }
1491}
1492
1493/// Supervisor-typed slots that live alongside the standard Caixa
1494/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
1495/// the manifest stays a single typed form; this struct exists for
1496/// validation + conversion.
1497#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1498#[serde(rename_all = "camelCase")]
1499pub struct SupervisorSpec {
1500    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
1501    #[serde(default)]
1502    pub estrategia: RestartStrategy,
1503
1504    /// Max restarts within [`Self::restart_window`] before the
1505    /// supervisor itself terminates (and its parent supervisor decides
1506    /// what to do). Default 5.
1507    #[serde(default = "default_max_restarts")]
1508    pub max_restarts: u32,
1509
1510    /// Sliding window for `max_restarts`. Authored as a duration
1511    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
1512    /// is rejected by [`Self::validate`] — Erlang/OTP's
1513    /// `MaxIntensity / Period` invariant requires a positive window
1514    /// (a zero-period supervisor either trips on the first failure or
1515    /// never trips, depending on operator interpretation, neither of
1516    /// which is the author's intent). Omit the slot to express "no
1517    /// reset"; carry a positive duration to express the sliding window.
1518    #[serde(
1519        default,
1520        skip_serializing_if = "Option::is_none",
1521        with = "duration_codec"
1522    )]
1523    pub restart_window: Option<Duration>,
1524
1525    /// Static children. Empty for `SimpleOneForOne` (children added
1526    /// dynamically); required for the other three strategies.
1527    #[serde(default)]
1528    pub children: Vec<ChildSpec>,
1529}
1530
1531const fn default_max_restarts() -> u32 {
1532    // Route the private serde-`#[serde(default = "…")]` helper through
1533    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
1534    // `pub const` rather than the raw `5` literal — one source of truth
1535    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
1536    // default across the two production consumers that currently
1537    // dispatch on it (this helper via `#[serde(default = "…")]` on
1538    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
1539    // impl at line 962). Pinned by
1540    // `default_max_restarts_helper_routes_through_lifted_default` +
1541    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
1542    // in the tests module; peer of the sibling caixa-core
1543    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
1544    // that now routes its author-omitted `:max-restarts` arm through
1545    // the same lifted constant.
1546    SUPERVISOR_MAX_RESTARTS_DEFAULT
1547}
1548
1549/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
1550/// count default for the `:supervisor :max-restarts` axis — the
1551/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
1552/// Erlang's worker-supervisor default, extracted as a typed `pub const`
1553/// so every substrate-side consumer that resolves "what
1554/// [`SupervisorSpec::max_restarts`] value does an author-omitted
1555/// `:max-restarts` slot degrade onto?" reaches for exactly one
1556/// substrate-primitive `u32`.
1557///
1558/// The `:max-restarts` default axis has two production consumers on the
1559/// substrate side today (both prior to this lift folded onto raw `5`
1560/// literals with no compile-time link back to a shared truth): the
1561/// serde-`#[serde(default = "default_max_restarts")]` helper on
1562/// [`SupervisorSpec::max_restarts`] that every author-omitted
1563/// `:supervisor :max-restarts` slot lands in past the derive-macro's
1564/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
1565/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
1566/// the composed [`SupervisorSpec`] altitude reaches through
1567/// (`feira app graph`, the future wasm-operator's per-supervisor
1568/// restart-intensity counter, the future M4
1569/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1570/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
1571/// A pair of open-coded `5`s across two files that expressed no
1572/// compile-time link back to the shared OTP-canonical default — a
1573/// future rebrand of the default (a tightening to Elixir's
1574/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
1575/// the operator pins through a future
1576/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
1577/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1578/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
1579/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
1580/// per-child-cohort roadmap lands) would have had to be threaded
1581/// through both open-coded copies in lockstep or the wire-format
1582/// author-omitted arm and the view-construction author-omitted arm
1583/// would silently disagree on which restart-budget an omitted
1584/// `:max-restarts` resolves to (an author writing `:supervisor
1585/// (:max-restarts ())` would round-trip through serde with the new
1586/// default while `supervisor_view` silently continued to compose the
1587/// stale `5`, or vice versa), a two-consumer split at the composition
1588/// boundary far from the source `caixa.lisp` with no field naming the
1589/// default-drift root cause. Lifting the resolution rule to a typed
1590/// `pub const` on the substrate primitive means every downstream
1591/// consumer of the per-Supervisor default-restart-budget-count surface
1592/// reaches for exactly one substrate-primitive `u32` — the resolver's
1593/// accepted value migrates as a unit on any future axis change.
1594///
1595/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1596/// worker-supervisor default (the closest canonical OTP-shape
1597/// production reference the substrate carries, matching the sibling
1598/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
1599/// this constant with on the paired sliding-window axis). Two orders of
1600/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
1601/// (the upper bracket on the same axis, sibling of this lower default;
1602/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
1603/// axis and now share one accessor discipline on the substrate) and
1604/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
1605/// restart floor — the "one restart, then escalate" default is
1606/// deliberately loose enough to absorb a short burst of transient
1607/// child failures without escalating past the supervisor's parent
1608/// while remaining tight enough to trip the `MaxIntensity / Period`
1609/// ratio's escalation on a genuinely-stuck child within the sibling
1610/// `60s` sliding window.
1611///
1612/// Lifted as a typed `pub const` so the bound has exactly one source
1613/// of truth — the serde-side wire-format author-omitted arm at
1614/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
1615/// struct-literal default field, and the caixa-core
1616/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
1617/// arm all read from one place. Same shape every other typed default
1618/// in this crate carries (the sibling
1619/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
1620/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
1621/// sibling `:restart-window` axis, and the peer
1622/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1623/// per-renderer defaults on the caixa-flux / caixa-helm rendering
1624/// axes).
1625pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
1626
1627/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
1628/// validated [`SupervisorSpec::max_restarts`] past
1629/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
1630///
1631/// The typed field is `u32` (the zero-floor arm
1632/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
1633/// so a programmatic struct literal
1634/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
1635/// author-surface form (`:max-restarts 4294967295` or any
1636/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
1637/// cleanly through serde — a structurally unbounded `u32` ceiling. The
1638/// runtime substrate consuming the value (Erlang/OTP's
1639/// `MaxIntensity / Period` ratio, the future wasm-operator's
1640/// per-supervisor restart-intensity counter, the M4
1641/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
1642/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
1643/// escalation threshold is structurally so high that no realistic
1644/// restarts-per-`:restart-window` traffic shape can reach it, the
1645/// supervisor never escalates to its parent, and a bad child can loop
1646/// inside the window indefinitely with the parent supervisor structurally
1647/// never receiving the "this subtree has exceeded its restart budget"
1648/// signal the typed slot is meant to express — the canonical
1649/// "supervisor intensity declared, no escalation" footgun, exactly the
1650/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
1651/// on the `:politicas :circuit-breaker :max-failures` axis (both are
1652/// "trip the next-higher protection layer after N events in a rolling
1653/// window" counters with identical degenerate-at-the-high-end shape).
1654///
1655/// The `1000` ceiling matches the sibling
1656/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
1657/// peer — same "events-per-window trip threshold" semantics, same `u32`
1658/// type, same no-op-at-the-high-end failure mode) so the M4
1659/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
1660/// and the future wasm-operator's per-supervisor restart-intensity
1661/// counter reach for either field knowing the value is in `1..=1000`
1662/// without re-validating at the reconciler layer. The cap sits two
1663/// orders of magnitude above every documented Erlang/OTP production
1664/// playbook recommendation (Learn You Some Erlang's
1665/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
1666/// `max_restarts: 3` default, OTP's `supervisor` callback module
1667/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
1668/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
1669/// default) and below the clearly-pathological "effectively no
1670/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
1671/// author can plausibly want at hyperscale (a long-running supervisor
1672/// over a very-flaky pool tolerating thousands of transient restarts
1673/// before escalating), but a hard wall above which the typed policy is
1674/// structurally a no-op carried verbatim on every emitted child-restart
1675/// reconciliation contract.
1676///
1677/// Lifted as a typed `pub const` so the bound has exactly one source of
1678/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1679/// materializer's admission webhook and the wasm-operator-side
1680/// per-supervisor restart-intensity reconciler read from one place. Same
1681/// shape every other typed upper bound in this crate carries
1682/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1683/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1684/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1685/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1686/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1687/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1688pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
1689
1690/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
1691/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
1692/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
1693/// (inclusive on both ends, integer-millisecond magnitudes by the
1694/// canonical-form gate immediately preceding).
1695///
1696/// The typed field is `Option<Duration>` (the zero-floor arm
1697/// [`SupervisorError::RestartWindowZero`] already rejects
1698/// `Some(Duration::ZERO)`, and the canonical-form arm
1699/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
1700/// sub-millisecond residue), so a programmatic struct literal
1701/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
1702/// .. }` — 24h) and the equivalent author-surface form
1703/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
1704/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
1705/// cleanly through serde — a structurally unbounded `Duration` ceiling.
1706/// A `:restart-window` value far above the documented Erlang/OTP
1707/// `MaxIntensity / Period` production-playbook band (Learn You Some
1708/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
1709/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
1710/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
1711/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
1712/// degenerates the supervisor's restart-intensity counter into a
1713/// lifetime counter: the rolling failure-counting window is structurally
1714/// so long that transient restarts are never forgotten, so the
1715/// `MaxIntensity / Period` ratio degenerates from "trip the parent
1716/// supervisor when the child has exceeded its restart budget *within
1717/// the recent window*" to "trip the parent when the child has exceeded
1718/// its restart budget *over its lifetime*" — every transient restart
1719/// counts against the budget forever, the supervisor's reset semantic
1720/// never reaches the child, and the typed `:restart-window` slot
1721/// becomes a no-op rolling window carried on every emitted hierarchical
1722/// reconciliation contract. The canonical
1723/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
1724/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
1725/// `:politicas :circuit-breaker :window` axis with identical shape (both
1726/// are "rolling failure-counting window with a per-`Period` reset" Duration
1727/// axes whose lifetime-counter degenerate at the high end is the same
1728/// "the reset semantic never fires" CSE invariant violation).
1729///
1730/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
1731/// the shared duration codec emits (`"<n>h"` for any integer-hour
1732/// magnitude) — every value in the canonical authoring form's
1733/// `<integer><unit>` grammar at or below this cap renders to a clean
1734/// canonical string — and matches the three sibling typed-`Duration`
1735/// caps already lifted to this surface
1736/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1737/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
1738/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
1739/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
1740/// per-supervisor `:supervisor :restart-window` — now share a single
1741/// uniform top edge at the codec's largest emitted unit so the next
1742/// typed-slot wiring (the future wasm-operator's per-supervisor
1743/// `MaxIntensity / Period` reconciler, the M4
1744/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1745/// webhook, the `caixa-operator`'s hierarchical reconciliation
1746/// scheduler) reaches for any of the four knowing the value is in
1747/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
1748/// two orders of magnitude above every documented Erlang/OTP / Elixir /
1749/// Riak Core / RabbitMQ production-playbook recommendation band
1750/// (`5s..=300s`) and below the clearly-pathological "rolling window
1751/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
1752/// a value the author can plausibly want for a very-low-traffic
1753/// long-tail failure-restart window over a hyperscale-flaky child pool,
1754/// but a hard wall above which the rolling-window contract is
1755/// structurally a lifetime-counter contract.
1756///
1757/// Lifted as a typed `pub const` so the bound has exactly one source
1758/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1759/// materializer's admission webhook, the wasm-operator-side
1760/// per-supervisor `MaxIntensity / Period` reconciler, and the
1761/// `caixa-operator`'s hierarchical reconciliation scheduler all read
1762/// from one place. Same shape every other typed upper bound in this
1763/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
1764/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1765/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1766/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1767/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1768/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1769/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
1770/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1771/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1772pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
1773
1774/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
1775/// default for the `:supervisor :restart-window` axis — the canonical
1776/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
1777/// worker-supervisor default, extracted as a typed `pub const` so every
1778/// substrate-side consumer that resolves "what
1779/// [`SupervisorSpec::restart_window`] value does an author-omitted
1780/// `:restart-window` slot degrade onto?" reaches for exactly one
1781/// substrate-primitive [`Duration`].
1782///
1783/// The `:restart-window` default axis has one production consumer on the
1784/// substrate side today: the [`Default for SupervisorSpec`] impl's
1785/// struct-literal `restart_window` field, which prior to this lift folded
1786/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
1787/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
1788/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
1789/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
1790/// *not* fall back to this default on the sibling `:restart-window` axis
1791/// — an author-omitted `:supervisor :restart-window` composes to
1792/// `restart_window: None` (the shared codec's soft-swallow shape),
1793/// keeping author-declared intent ("no reset — never escalate on rolling
1794/// window") distinct from the [`Default for SupervisorSpec`] "canonical
1795/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
1796/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
1797/// default was split across two files with no compile-time link between
1798/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
1799/// `MaxIntensity` half at the substrate primitive while the `Period`
1800/// half rode as an open-coded literal at the composition site, so a
1801/// future coherent rebrand of the paired canonical (a tightening to
1802/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
1803/// per-cluster overlay the operator pins through a future
1804/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
1805/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1806/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
1807/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
1808/// roadmap lands) would have had to migrate the `MaxIntensity` half
1809/// through the lifted constant and the `Period` half through a raw
1810/// literal in lockstep or the two halves of the same OTP-canonical
1811/// default would silently drift out of pairing. Lifting the resolution
1812/// rule to a typed `pub const` on the substrate primitive means the
1813/// paired OTP-canonical default migrates as one unit on any future
1814/// axis change.
1815///
1816/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1817/// worker-supervisor default (the closest canonical OTP-shape
1818/// production reference the substrate carries, matching the paired
1819/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
1820/// constant is the `Period` denominator of on the same
1821/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
1822/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
1823/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
1824/// this lower default; both are typed [`Duration`] const bounds on the
1825/// `:supervisor :restart-window` axis and now share one accessor
1826/// discipline on the substrate) and above the OTP-`supervisor`
1827/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
1828/// rolling window" default is deliberately loose enough to absorb a
1829/// short burst of transient child failures without escalating past the
1830/// supervisor's parent while remaining tight enough for the paired
1831/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
1832/// stuck child within a human-scale observation window.
1833///
1834/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1835/// exactly one source of truth on each half — the sibling
1836/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
1837/// `Period` `60s` half now share the same substrate-primitive lift
1838/// discipline. Same shape every other typed default in this crate
1839/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
1840/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
1841/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
1842/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
1843/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
1844/// caixa-flux / caixa-helm rendering axes).
1845pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
1846
1847/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
1848/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
1849/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
1850/// worker-supervisor default, extracted as a typed `pub const` so every
1851/// substrate-side consumer that resolves "what
1852/// [`SupervisorSpec::estrategia`] variant does an author-omitted
1853/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
1854/// primitive [`RestartStrategy`].
1855///
1856/// The `:estrategia` default axis has three production consumers on the
1857/// substrate side today: the [`Default for RestartStrategy`] impl's
1858/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
1859/// `estrategia` field, and the
1860/// [`crate::manifest::Caixa::supervisor_view`] fold's
1861/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
1862/// collapse arm — three entry points onto the same OTP-canonical
1863/// `one_for_one` value that prior to this lift folded onto a raw
1864/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
1865/// implicit `RestartStrategy::default()` routes at the sibling consumers,
1866/// with no compile-time link back to the paired
1867/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
1868/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
1869/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
1870/// triple was split across three altitudes with no compile-time link
1871/// between the halves: the `MaxIntensity` half rode through the lifted
1872/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
1873/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1874/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
1875/// discriminator at the [`Default for RestartStrategy`] impl, so a future
1876/// coherent rebrand of the triple (Elixir's `{:one_for_one,
1877/// max_restarts: 3, max_seconds: 5}` — same strategy, different
1878/// intensity/period; an OTP `rest_for_one` widening once the substrate
1879/// discovers startup-order-coupled child cohorts as the more common
1880/// worker-supervisor default; a per-cluster overlay the operator pins
1881/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
1882/// §III.2 supervision-canary roadmap acknowledges) would have had to
1883/// migrate the `MaxIntensity` + `Period` halves through the lifted
1884/// constants and the `one_for_one` half through an open-coded arm in
1885/// lockstep or the three halves of the same OTP-canonical default would
1886/// silently drift out of pairing. Lifting the resolution rule to a typed
1887/// `pub const` on the substrate primitive means the paired OTP-canonical
1888/// worker-supervisor default migrates as one unit on any future axis
1889/// change.
1890///
1891/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
1892/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
1893/// closest canonical OTP-shape production reference the substrate
1894/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
1895/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1896/// `60s` `Period` half). The `one_for_one` strategy — restart only the
1897/// failed child, leaving siblings untouched — is the default for tree-of-
1898/// independent-workers use cases the substrate's [`RestartStrategy`]
1899/// discriminator's own docstring already carries as the default arm; it
1900/// composes with the `{5, 60}` restart-intensity ratio to name the same
1901/// substrate-canonical "canonical worker-supervisor" shape the paired
1902/// halves close on their respective axes.
1903///
1904/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1905/// exactly one source of truth on each of its three halves — the sibling
1906/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
1907/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
1908/// this `one_for_one` strategy half now share the same substrate-
1909/// primitive lift discipline. Same shape every other typed default in
1910/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
1911/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
1912/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
1913/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
1914/// upper caps on the paired sibling axes, and the peer
1915/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1916/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
1917pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
1918
1919/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
1920/// default for the `:children :restart` axis — the OTP `permanent`
1921/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
1922/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
1923/// `pub const` so every substrate-side consumer that resolves "what
1924/// [`ChildSpec::restart`] variant does an author-omitted `:children
1925/// :restart` slot degrade onto?" reaches for exactly one substrate-
1926/// primitive [`RestartPolicy`].
1927///
1928/// Completes the OTP-shape supervisor-tree default set at the substrate
1929/// primitive. The per-`:supervisor` axis already carries all three of its
1930/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1931/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
1932/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1933/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
1934/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
1935/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
1936/// the M2 `:supervisor` slot family. The split mattered because the two
1937/// axes resolve *together* on every author-omitted supervisor: a
1938/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
1939/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
1940/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
1941/// `permanent` through an open-coded enum arm, so a future coherent
1942/// rebrand of the OTP-shape default set (an Elixir-shaped
1943/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
1944/// per-cluster overlay the operator pins through the MESH-COMPOSITION
1945/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
1946/// once the substrate discovers clean-completion-aware children as the
1947/// more common child shape) would have had to migrate three halves
1948/// through typed constants and the fourth through a raw enum arm in
1949/// lockstep or the supervisor-level and child-level defaults would
1950/// silently drift apart.
1951///
1952/// The `:children :restart` default axis has two production consumers on
1953/// the substrate side today: the [`Default for RestartPolicy`] impl's
1954/// return arm, and the serde-side `#[serde(default)]` on
1955/// [`ChildSpec::restart`] that resolves an author-omitted `:children
1956/// :restart` slot through that same impl. Both now key off this one
1957/// substrate primitive, so the future wasm-operator's per-child post-exit
1958/// restart-decision branch, the future M4
1959/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1960/// admission webhook, and the `caixa-operator`'s hierarchical
1961/// reconciliation scheduler's per-child fan-out all reach for one typed
1962/// identifier when they resolve an omitted per-child restart posture.
1963///
1964/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
1965/// worker-child restart type — always restart the child regardless of how
1966/// it died, the canonical posture for long-running services that must
1967/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1968/// `one_for_one` tree-of-independent-workers strategy this constant pairs
1969/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
1970/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
1971/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
1972/// [`RestartPolicy::Temporary`] — never restart) express deliberate
1973/// one-shot / clean-completion-aware postures an author declares
1974/// explicitly, never a posture an omitted slot should silently assume.
1975pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
1976
1977/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
1978/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
1979/// `pub const fn` constructor rather than a struct-literal cascade over
1980/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
1981/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1982/// lifted consts — one source of truth for the Erlang/OTP-canonical
1983/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
1984/// paths every downstream consumer already reaches through (the
1985/// hand-authored-until-now [`Default::default`] the
1986/// `..SupervisorSpec::default()` struct-update-syntax on every
1987/// one-axis-under-test fixture in this crate's test module rests on,
1988/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
1989/// every `const`-context consumer reaches through).
1990///
1991/// Extends the [`Default`]-through-const-ctor fold discipline the
1992/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
1993/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
1994/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
1995/// and [`crate::BehaviorSpec`]
1996/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
1997/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
1998/// typed-slot spec family — extended here onto the M2 supervisor-slot
1999/// [`SupervisorSpec`] whose canonical baseline is not "everything
2000/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
2001/// supervisor triple. The `empty()` peer's naming did not fit
2002/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
2003/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
2004/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
2005/// the sibling `Option`-only slots fold to), so this peer is named
2006/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
2007/// existing per-arm pin tests
2008/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
2009/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
2010/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2011/// already reach for. Pinned load-bearing by
2012/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
2013/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
2014/// [`PartialEq`], sharpening the sibling
2015/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
2016/// pins from a per-field lift into a whole-struct one-source-of-truth
2017/// pin — the derived-until-now [`Default::default`] and the
2018/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
2019/// construction, not by coincidence).
2020impl Default for SupervisorSpec {
2021    #[inline]
2022    fn default() -> Self {
2023        Self::otp_canonical()
2024    }
2025}
2026
2027impl SupervisorSpec {
2028    /// `const`-context peer of the [`Default for SupervisorSpec`]
2029    /// impl (which routes through this constructor) — returns the
2030    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
2031    /// baseline this crate reaches for in every fixture-builder
2032    /// `..SupervisorSpec::default()` struct-update expression and
2033    /// every downstream `SupervisorSpec::default()` seed.
2034    ///
2035    /// Each field routes through the same substrate-canonical
2036    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
2037    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
2038    /// per-arm pin tests
2039    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
2040    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
2041    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2042    /// already assert, so a future coherent rebrand of the OTP-canonical
2043    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
2044    /// cluster overlay via a future `:restart-window-overrides` slot, a
2045    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
2046    /// absorption roadmap acknowledges) migrates through three typed
2047    /// constants in lockstep, and the paired [`Default`] impl inherits
2048    /// every future extension by construction.
2049    ///
2050    /// `pub const fn` rather than the derived-style `Default::default`
2051    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
2052    /// [`Default::default`] is not `const` on stable Rust, and
2053    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
2054    /// every consumer through a [`Clone::clone`]. The `pub const fn`
2055    /// discipline lets `const`-context callers construct the OTP-
2056    /// canonical baseline at compile time without runtime dispatch on
2057    /// the derived [`Default::default`], the same posture the sibling
2058    /// [`crate::LimitsSpec::empty`] (9739971) /
2059    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
2060    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
2061    /// spec `pub const fn` constructors carry on the sibling
2062    /// "everything `None`" baseline axis.
2063    ///
2064    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
2065    /// of the derived-style [`Default`]" family — sibling of the
2066    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
2067    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
2068    /// baseline" trio, extended here onto the M2 supervisor-slot
2069    /// [`SupervisorSpec`] whose canonical baseline is not "everything
2070    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
2071    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
2072    /// than `empty()` to name the actual invariant the return value
2073    /// pins — the same phrasing already used in the per-arm pin tests
2074    /// on this file. Pinned load-bearing by
2075    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
2076    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
2077    #[must_use]
2078    pub const fn otp_canonical() -> Self {
2079        Self {
2080            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
2081            max_restarts: default_max_restarts(),
2082            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2083            children: Vec::new(),
2084        }
2085    }
2086
2087    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
2088    /// sibling-restart-strategy scalar accessor every consumer that
2089    /// dispatches on the supervisor's per-sibling restart-decision shape
2090    /// keys off — returns the author-declared `:supervisor :estrategia`
2091    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
2092    /// the typed slot's own [`RestartStrategy`] storage.
2093    ///
2094    /// The `:supervisor :estrategia` slot carries the closed-set
2095    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
2096    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
2097    /// [`RestartStrategy::OneForAll`] — restart every child on any child
2098    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
2099    /// [`RestartStrategy::RestForOne`] — restart the failed child and
2100    /// every child started after it, the Erlang/OTP `rest_for_one`
2101    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
2102    /// dynamic children of the same shape, the Erlang/OTP
2103    /// `simple_one_for_one` per-session default) that every downstream
2104    /// consumer of the Supervisor's per-sibling restart-decision fan-out
2105    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
2106    /// paired coherently with the sibling `:children` axis
2107    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
2108    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
2109    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
2110    /// downstream consumer that reads the strategy keys off this scalar
2111    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2112    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
2113    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
2114    /// `estrategia:` field, the future `feira app graph` per-Supervisor
2115    /// strategy print line, the future wasm-operator's per-supervisor
2116    /// sibling-restart-strategy branch, the future M4
2117    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
2118    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
2119    /// reconciliation scheduler's per-strategy fan-out).
2120    ///
2121    /// Prior to this lift the `.estrategia` field was accessed inline at
2122    /// two production sites in `caixa-core/src/supervisor.rs` — the
2123    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2124    /// `match self.estrategia { … }` partition dispatch, and the
2125    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
2126    /// carrier at `estrategia: self.estrategia` — two open-coded
2127    /// field-accesses that expressed no compile-time link back to the
2128    /// typed slot. A future extension of the `:supervisor :estrategia`
2129    /// axis to a richer author surface (a per-cluster strategy override
2130    /// the operator pins through a future `:supervisor :estrategia-overrides`
2131    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2132    /// acknowledges, a per-tenant strategy-alias table the M4 CR
2133    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
2134    /// derivation the future adaptive-supervision engine computes from
2135    /// child-failure-history topology, a per-child-cohort strategy split
2136    /// the future `RestForCohort` extension acknowledged by the
2137    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
2138    /// would have had to be threaded through every open-coded copy in
2139    /// lockstep — one consumer reading the raw variant while a peer read
2140    /// the operator-resolved variant would silently split the
2141    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
2142    /// the actual partition-dispatch input the empty-children refusal
2143    /// arm reached under, a two-consumer split at the validator far from
2144    /// the source `caixa.lisp` with no field naming the strategy-drift
2145    /// root cause. Lifting the resolution rule to a typed method on the
2146    /// substrate primitive means every downstream consumer of the
2147    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
2148    /// reaches for exactly one typed dispatch — the resolver's accept-set
2149    /// migrates as a unit on any future axis addition.
2150    ///
2151    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
2152    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
2153    /// per-`:placement` distribution-strategy axis — same "one typed
2154    /// dispatch on the substrate primitive, thin projections at each
2155    /// consumer" discipline extended onto the M2 supervisor-slot
2156    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
2157    /// scalar axis. The two typed axes (`Placement::estrategia` on the
2158    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
2159    /// Supervisor side) now share one accessor discipline for the shared
2160    /// substrate concept "a `Copy`-projected closed-set enum-arm
2161    /// discriminator that partitions the downstream renderer's per-arm
2162    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
2163    /// `SupervisorSpec` type — companion to the sibling per-`:children`
2164    /// [`crate::ChildSpec::nome`] (57c61d0) /
2165    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2166    /// scalar accessors on the sibling per-`:children` `String`-carry
2167    /// axes. Named `estrategia()` to match the storage field's name and
2168    /// the peer [`crate::Placement::estrategia`] method-name discipline
2169    /// verbatim; the accessor's identity name maps onto the canonical
2170    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
2171    /// docstring already carries.
2172    ///
2173    /// Declared `pub const fn` to close the M2 supervisor-slot
2174    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
2175    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
2176    /// (converted in this commit) `Copy`-composite-enum accessor, peer
2177    /// of the sibling M2 per-`:supervisor`
2178    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2179    /// already lifted, and mirror of the peer M3 mesh-slot
2180    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
2181    /// `Copy`-return `pub const fn` scalar accessor whose method-name
2182    /// discipline this accessor was authored to match. Every downstream
2183    /// substrate-side `const`-context consumer of the per-`:supervisor`
2184    /// sibling-restart-strategy scalar (a future module-scope `const
2185    /// _:() = assert!(matches!(sup.estrategia(),
2186    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
2187    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2188    /// admission-webhook `const fn` per-supervisor strategy-arm floor
2189    /// over a typed [`SupervisorSpec`], any future `const fn`
2190    /// supervisor-tree composer over the substrate primitive that fans
2191    /// on the sibling-restart-strategy at compile time) now reaches
2192    /// through the same typed dispatch on the substrate primitive at
2193    /// const-eval time as at runtime. A future non-`Copy`-return
2194    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
2195    /// migration once the substrate grows per-cluster strategy overlays
2196    /// the [`SupervisorSpec`] docstring already anticipates, a
2197    /// per-tenant strategy-alias table the M4 CR materializer resolves
2198    /// per-CR) that would drop the `const` qualifier fails the
2199    /// fail-before-pass-after pin
2200    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
2201    /// caixa-core build time rather than surfacing as a downstream
2202    /// consumer regression.
2203    #[must_use]
2204    pub const fn estrategia(&self) -> RestartStrategy {
2205        self.estrategia
2206    }
2207
2208    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
2209    /// `MaxIntensity` restart-budget scalar accessor every consumer that
2210    /// reads the supervisor's per-`:restart-window` restart-budget count
2211    /// keys off — returns the author-declared `:supervisor :max-restarts`
2212    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
2213    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
2214    /// borrow of `&self` past the call). Non-optional (the `u32` field
2215    /// carries the restart-budget count as a required axis with a
2216    /// [`default_max_restarts`]-supplied default; the zero-floor arm
2217    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
2218    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
2219    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
2220    ///
2221    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
2222    /// `MaxIntensity` restart-budget count that pairs with the sibling
2223    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
2224    /// restart-intensity ratio the supervisor trips its own escalation on
2225    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
2226    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
2227    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
2228    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
2229    /// upper-cap bracket at
2230    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
2231    /// wasm-operator's per-supervisor restart-intensity counter's
2232    /// budget-vs-count comparator, the future M4
2233    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2234    /// webhook, the `caixa-operator`'s hierarchical reconciliation
2235    /// scheduler's per-supervisor escalation-decision branch, every
2236    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
2237    /// offending count verbatim for `feira lint` rendering).
2238    ///
2239    /// Prior to this lift the `.max_restarts` field was accessed inline at
2240    /// one production site in `caixa-core/src/supervisor.rs` — the
2241    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
2242    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
2243    /// that expressed no compile-time link back to the typed slot. A
2244    /// future extension of the `:max-restarts` axis to a richer author
2245    /// surface (a per-cluster restart-budget override the operator pins
2246    /// through a future `:supervisor :max-restarts-overrides` slot the
2247    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
2248    /// a per-tenant restart-budget-alias table the M4 CR materializer
2249    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
2250    /// the future adaptive-supervision engine computes from child-failure-
2251    /// history topology, a promotion of the plain `u32` count to a richer
2252    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
2253    /// budget-partition slot comes into scope) would have had to be
2254    /// threaded through every open-coded copy in lockstep or the validate
2255    /// gate and the future M4 emit path would silently disagree on which
2256    /// restart-budget count a given supervisor resolves to — an author's
2257    /// `:max-restarts 5` would satisfy validate while the emit path
2258    /// silently read a drifted other value (a `:max-restarts 10000`
2259    /// no-op supervisor at the emit boundary would carry the author's
2260    /// declared `5` verbatim in `feira lint` output while the future
2261    /// wasm-operator's restart-intensity counter operated under the
2262    /// drifted count), a two-consumer split at the validator far from the
2263    /// source `caixa.lisp` with no field naming the restart-budget-drift
2264    /// root cause. Lifting the resolution rule to a typed method on the
2265    /// substrate primitive means every downstream consumer of the
2266    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
2267    /// for exactly one typed dispatch — the resolver's accept-set migrates
2268    /// as a unit on any future axis addition.
2269    ///
2270    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
2271    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
2272    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
2273    /// outlier-detection trip-threshold axis — same "one typed dispatch on
2274    /// the substrate primitive, thin projections at each consumer"
2275    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
2276    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
2277    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
2278    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
2279    /// one accessor discipline for the shared substrate concept "a
2280    /// `Copy`-projected required `u32` count that trips the next-higher
2281    /// protection layer after N events in a rolling window" — both are
2282    /// counters with identical degenerate-at-the-high-end shape and share
2283    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
2284    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
2285    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
2286    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
2287    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
2288    /// the storage field's name verbatim and the peer
2289    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
2290    /// accessor's identity maps onto the canonical OTP-shape supervision
2291    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
2292    /// already carries.
2293    #[must_use]
2294    pub const fn max_restarts(&self) -> u32 {
2295        self.max_restarts
2296    }
2297
2298    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
2299    /// `Period` sliding-window scalar accessor every consumer of the
2300    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
2301    /// keys off — returns the author-declared `:supervisor :restart-window`
2302    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
2303    /// the typed slot's own `Option<Duration>` storage (`Duration` is
2304    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
2305    /// value; no borrow of `&self` past the call). `None` when the slot is
2306    /// absent (the canonical "never reset — every restart across the
2307    /// supervisor's lifetime counts against the sibling `:max-restarts`
2308    /// budget" sentinel the field's own docstring names and the peer
2309    /// `validate_accepts_none_restart_window` pin locks in on the
2310    /// [`SupervisorSpec::validate`] entry-side).
2311    ///
2312    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
2313    /// `Period` sliding-observation-interval that pairs with the sibling
2314    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
2315    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
2316    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
2317    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
2318    /// default). The typed slot's `Option<Duration>` accept-set —
2319    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
2320    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
2321    /// `Period > 0`; a zero period either trips on the first failure or
2322    /// never trips depending on operator interpretation, neither of which
2323    /// is the author's intent — omit the slot to express "no reset";
2324    /// carry a positive duration to express the sliding window),
2325    /// integer-millisecond canonical form enforced through
2326    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
2327    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
2328    /// future wasm-operator's per-supervisor restart-intensity counter
2329    /// quantizes at milliseconds), upper-bounded by
2330    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
2331    /// supervisor rolling window any operationally-reachable supervisor
2332    /// can honor without spanning multiple scheduler epochs the
2333    /// hierarchical-reconciliation scheduler treats as independent) —
2334    /// maps onto the future wasm-operator (M3) per-supervisor
2335    /// restart-intensity counter's rolling-observation-interval, the
2336    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2337    /// per-`spec.restartWindow` admission webhook, and the sibling
2338    /// `duration_codec`-serialized wire scalar every downstream consumer
2339    /// of the supervisor's per-`:supervisor` restart-intensity denominator
2340    /// keys off.
2341    ///
2342    /// Prior to this lift the `.restart_window` field was accessed inline
2343    /// at one production site in `caixa-core/src/supervisor.rs` — the
2344    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
2345    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
2346    /// open-coded field-access that expressed no compile-time link back to
2347    /// the typed slot. A future extension of the `:restart-window` axis to
2348    /// a richer author surface (a per-cluster restart-window override the
2349    /// operator pins through a future `:supervisor :restart-window-overrides`
2350    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2351    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
2352    /// materializer resolves per-CR, a per-supervisor dynamic
2353    /// restart-window derivation the future adaptive-supervision engine
2354    /// computes from child-failure-history topology, a promotion of the
2355    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
2356    /// pair once Erlang/OTP's per-child-cohort observation-interval-
2357    /// partition slot comes into scope) would have had to be threaded
2358    /// through every open-coded copy in lockstep or the validate gate and
2359    /// the future M4 emit path would silently disagree on which
2360    /// restart-window a given supervisor resolves to — an author's
2361    /// `:restart-window "60s"` would satisfy validate while the emit path
2362    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
2363    /// authored slot at the emit boundary would carry the author's
2364    /// declared window verbatim in `feira lint` output while the future
2365    /// wasm-operator's restart-intensity counter operated under a
2366    /// drifted window, or vice versa: an author's `:restart-window ()`
2367    /// would carry the "never reset" sentinel through validate while the
2368    /// emit path silently substituted a default sliding window), a
2369    /// two-consumer split at the validator far from the source
2370    /// `caixa.lisp` with no field naming the restart-window-drift root
2371    /// cause. Lifting the resolution rule to a typed method on the
2372    /// substrate primitive means every downstream consumer of the
2373    /// Supervisor's per-`:supervisor` restart-intensity-denominator
2374    /// surface reaches for exactly one typed dispatch — the resolver's
2375    /// accept-set migrates as a unit on any future axis addition.
2376    ///
2377    /// Third `Copy`-return accessor on the M2 supervisor-slot
2378    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
2379    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
2380    /// payload rather than a `Copy`-scalar, and the per-`:children`
2381    /// [`crate::ChildSpec::nome`] (57c61d0) /
2382    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2383    /// scalar accessors already close the per-element `String`-carry
2384    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
2385    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
2386    /// per-outermost-call wall-clock-deadline axis and the peer M3
2387    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
2388    /// accessor on the `:politicas` slot's per-call-deadline axis — all
2389    /// three share the shared substrate concept "a `Copy`-projected
2390    /// optional `Duration` that carries a positive integer-millisecond
2391    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
2392    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
2393    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
2394    /// bracket-helper the three axes each route through. Named
2395    /// `restart_window()` to match the storage field's name verbatim and
2396    /// the peer [`crate::LimitsSpec::wall_clock`] /
2397    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
2398    /// accessor's identity maps onto the canonical OTP-shape supervision
2399    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
2400    /// already carries.
2401    #[must_use]
2402    pub const fn restart_window(&self) -> Option<Duration> {
2403        self.restart_window
2404    }
2405
2406    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
2407    /// static-child-list slice accessor every consumer that walks the
2408    /// supervisor's declared child set keys off — returns the author-
2409    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
2410    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
2411    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
2412    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
2413    /// through). Non-optional: an empty slice is the load-bearing
2414    /// "author declared `:children ()`" sentinel every consumer of the
2415    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
2416    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
2417    /// three strategies require a non-empty slice — the paired
2418    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
2419    /// [`SupervisorError::NoChildren`] refusal cascade pins the
2420    /// partition on both arms).
2421    ///
2422    /// The `:supervisor :children` slot carries the OTP-shaped static
2423    /// child list the supervisor materializes one ComputeUnit per
2424    /// entry from — the Erlang/OTP `supervisor:init/1`'s
2425    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
2426    /// through the tatara-lisp `:children` author surface onto a typed
2427    /// `Vec<ChildSpec>` whose per-element `(nome(),
2428    /// versao_requirement(), restart)` triple the per-child
2429    /// [`SupervisorSpec::validate`] loop already gates through the
2430    /// lifted [`ChildSpec::nome`] (57c61d0) /
2431    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
2432    /// Every downstream consumer that fans on the static child list
2433    /// keys off this slice (the [`SupervisorSpec::validate`]
2434    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
2435    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
2436    /// per-child DNS-1123 / semver-requirement / duplicate-detection
2437    /// fan-out loop, every future wasm-operator (M3) per-supervisor
2438    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
2439    /// materialization loop, the future M4
2440    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2441    /// admission-webhook fan-out, the future `feira app graph`
2442    /// per-supervisor tree-print traversal).
2443    ///
2444    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
2445    /// inline at three production sites in `caixa-core/src/supervisor.rs`
2446    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
2447    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
2448    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
2449    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
2450    /// validate loop's `for child in &self.children` traversal head —
2451    /// three open-coded field-accesses that expressed no compile-time
2452    /// link back to the typed slot. A future extension of the
2453    /// `:supervisor :children` axis to a richer author surface (a
2454    /// per-cluster child-set overlay the operator pins through a future
2455    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
2456    /// supervision-canary roadmap acknowledges, a per-tenant
2457    /// child-set-alias table the M4 CR materializer resolves per-CR,
2458    /// a per-supervisor dynamic-child derivation the future adaptive-
2459    /// supervision engine computes from child-failure-history topology,
2460    /// a promotion of the plain `Vec<ChildSpec>` to a richer
2461    /// `{static, dynamic}` partition once Erlang/OTP's
2462    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
2463    /// would have had to be threaded through all three open-coded copies
2464    /// in lockstep or one consumer would silently disagree with the
2465    /// peers on which child-set a given supervisor resolves to — the
2466    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
2467    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
2468    /// would silently split the partition-dispatch's two-arm coherence
2469    /// (a supervisor that satisfies neither arm's precondition, or that
2470    /// satisfies both, at the cost of the paired
2471    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
2472    /// silently drifting from the per-child validate loop's actual
2473    /// traversal input), a three-consumer split at the validator far
2474    /// from the source `caixa.lisp` with no field naming the
2475    /// child-set-drift root cause. Lifting the resolution rule to a
2476    /// typed method on the substrate primitive means every downstream
2477    /// consumer of the Supervisor's per-`:supervisor` static-child-list
2478    /// surface reaches for exactly one typed dispatch — the resolver's
2479    /// accept-set migrates as a unit on any future axis addition.
2480    ///
2481    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
2482    /// — the seed for the same "one typed dispatch on the substrate
2483    /// primitive, thin projections at each consumer" discipline the
2484    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
2485    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
2486    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
2487    /// onto the first `Vec`-carry axis on the substrate. The four peer
2488    /// `Vec`-carry axes still unlifted at the time of this seed —
2489    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
2490    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
2491    /// (`Vec<Membro>` per-Aplicacao member list),
2492    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
2493    /// per-Aplicacao WIT-typed edge list),
2494    /// [`crate::UpgradeFromEntry::instructions`]
2495    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
2496    /// — inherit this accessor's discipline as future compounding runs
2497    /// migrate their consumers onto the shared slice-return shape.
2498    /// Fourth (and final) accessor on the M2 supervisor-slot
2499    /// `SupervisorSpec` type, sibling to the three `Copy`-return
2500    /// [`SupervisorSpec::estrategia`] (eafb619) /
2501    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
2502    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
2503    /// the last unlifted per-`:supervisor` field axis (the
2504    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
2505    /// per-`:supervisor` reader now routes through a typed dispatch on
2506    /// the substrate primitive. Named `children()` to match the storage
2507    /// field's name verbatim and the tatara-lisp author-surface term
2508    /// (`:children`) the field's own docstring already carries; the
2509    /// accessor's identity maps onto the canonical OTP-shape
2510    /// supervision vocabulary the [`SupervisorSpec::children`] field's
2511    /// docstring already reaches for ("Static children ..."). Returns
2512    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
2513    /// consumer of the child list treats it as a read-only sequence —
2514    /// the slice-view is the narrowest borrow that supports every
2515    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
2516    /// index, `.len()`) without leaking the backing `Vec`'s
2517    /// grow/push/reserve surface that no consumer of the typed view
2518    /// reaches for (the storage-side `Vec` remains reachable through
2519    /// the `pub children` field for the mutation-carrying
2520    /// `Caixa::supervisor_view` fold-in path in
2521    /// `manifest.rs:supervisor_view`).
2522    #[must_use]
2523    pub const fn children(&self) -> &[ChildSpec] {
2524        self.children.as_slice()
2525    }
2526
2527    /// Validate the supervisor's typed shape — strategy ↔ children
2528    /// invariants, max_restarts > 0, restart_window > 0 when set,
2529    /// per-child non-empty + duplicate-free names.
2530    ///
2531    /// Mirrors the value-shape discipline applied to every other
2532    /// typed slot:
2533    ///
2534    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
2535    ///     same "0 means the opposite of what you think" footgun
2536    ///     closed for `:politicas :timeout` (Envoy interprets a zero
2537    ///     timeout as `infinite`), `:politicas :circuit-breaker
2538    ///     :window`, and `:limits :wall-clock`. The
2539    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
2540    ///     `supervisor` requires `Period > 0`; a zero period either
2541    ///     trips on the first failure or never trips depending on
2542    ///     operator interpretation, neither of which is the
2543    ///     author's intent. Omit `:restart-window` to express "no
2544    ///     reset"; carry a positive duration to express the window.
2545    ///   - duplicate `:children` `:caixa` names are the same
2546    ///     graph-node-set / multiset distinction closed for
2547    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
2548    ///     and `:entrada :paths` (eb3456d). Two children with the
2549    ///     same `:caixa` materialize as two ComputeUnits with the
2550    ///     same name in the cluster's HelmRelease values, one
2551    ///     silently overwriting the other. Erlang/OTP's
2552    ///     `child_spec.id` is required-unique per supervisor;
2553    ///     pleme-io enforces the same set-not-multiset shape on
2554    ///     `:caixa` (the load-bearing identity in our renderer).
2555    pub fn validate(&self) -> Result<(), SupervisorError> {
2556        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
2557        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2558        // error carrier's `estrategia:` field through the lifted
2559        // [`SupervisorSpec::estrategia`] accessor rather than the raw
2560        // `self.estrategia` field access — the two production consumers
2561        // of the per-`:supervisor` sibling-restart-strategy scalar now
2562        // key off exactly one typed dispatch on the substrate primitive,
2563        // so any future rebrand on the axis (a per-cluster strategy
2564        // override the operator pins through a future `:supervisor
2565        // :estrategia-overrides` slot, a per-tenant strategy-alias table
2566        // the M4 CR materializer resolves per-CR) migrates as a single
2567        // caixa-core edit rather than a coordinated rewrite of the two
2568        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
2569        // (921fe1b) four-consumer migration on the per-`:placement`
2570        // distribution-strategy axis.
2571        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
2572        // dispatch's paired `.is_empty()` cross-slot refusal probes
2573        // (the `SimpleOneForOne`-arm
2574        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
2575        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2576        // refusal) through the lifted [`SupervisorSpec::children`]
2577        // slice-return accessor rather than the raw `self.children`
2578        // field access — the two paired production consumers of the
2579        // per-`:supervisor` static-child-list scalar-shape now key off
2580        // exactly one typed dispatch on the substrate primitive, so any
2581        // future rebrand on the axis (a per-cluster child-set overlay
2582        // the operator pins through a future `:supervisor
2583        // :children-overrides` slot, a per-tenant child-set-alias table
2584        // the M4 CR materializer resolves per-CR) migrates as a single
2585        // caixa-core edit rather than a coordinated rewrite of the
2586        // paired arms — first slice-return migration on any typed slot,
2587        // seed for the peer per-`:placement :clusters`,
2588        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
2589        // :instructions` `Vec`-carry axes.
2590        match self.estrategia() {
2591            RestartStrategy::SimpleOneForOne => {
2592                // SimpleOneForOne: children added at runtime. Static
2593                // list must be empty (one shape declared elsewhere).
2594                if !self.children().is_empty() {
2595                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
2596                }
2597            }
2598            _ => {
2599                if self.children().is_empty() {
2600                    return Err(SupervisorError::no_children(self.estrategia()));
2601                }
2602            }
2603        }
2604        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
2605        // axis. See [`crate::render::require_positive_bounded_u32`] for
2606        // the ordering discipline (zero-floor arm strictly precedes cap
2607        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
2608        // diagnostic with its counter-axis remediation directly named,
2609        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
2610        // cap-arm miss). Until this bracket landed the top edge ran all
2611        // the way to `u32::MAX` and a struct-literal
2612        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
2613        // equivalent author-surface `:max-restarts 100000` /
2614        // `:max-restarts 4294967295` typo landing in the slot) silently
2615        // passed validate. The runtime substrate consuming the value
2616        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
2617        // wasm-operator's per-supervisor restart-intensity counter, the
2618        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2619        // admission webhook) then turned a typed `:max-restarts`
2620        // policy into a no-op supervisor: the escalation threshold is
2621        // structurally so high that no realistic
2622        // restarts-per-`:restart-window` traffic shape can reach it,
2623        // the supervisor never escalates to its parent, and a bad
2624        // child can loop inside the window indefinitely with the
2625        // parent supervisor structurally never receiving the "this
2626        // subtree has exceeded its restart budget" signal the typed
2627        // slot is meant to express. The bracket set is
2628        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
2629        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
2630        // the sibling `:politicas :circuit-breaker :max-failures` axis:
2631        // both are "trip the next-higher protection layer after N
2632        // events in a rolling window" counters with identical
2633        // degenerate-at-the-high-end shape and now share one canonical
2634        // bracket helper. The bracket precedes the sibling
2635        // `:restart-window` zero-floor / canonical-millisecond arms so
2636        // an over-cap `max_restarts` paired with a structurally invalid
2637        // window surfaces the bracket diagnostic first, mirroring the
2638        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
2639        // ordering on the peer `:politicas :circuit-breaker` slot.
2640        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
2641        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
2642        // accessor rather than the raw `self.max_restarts` field access —
2643        // the one production consumer of the per-`:supervisor`
2644        // restart-budget-count scalar now keys off exactly one typed
2645        // dispatch on the substrate primitive, so any future rebrand on
2646        // the axis (a per-cluster restart-budget override the operator
2647        // pins through a future `:supervisor :max-restarts-overrides`
2648        // slot, a per-tenant restart-budget-alias table the M4 CR
2649        // materializer resolves per-CR) migrates as a single caixa-core
2650        // edit rather than a coordinated rewrite — sibling of the peer M3
2651        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
2652        // the per-`:politicas :circuit-breaker :max-failures` axis.
2653        crate::render::require_positive_bounded_u32(
2654            self.max_restarts(),
2655            SUPERVISOR_MAX_RESTARTS_MAX,
2656            || SupervisorError::ZeroMaxRestarts,
2657            SupervisorError::max_restarts_exceeds_cap,
2658        )?;
2659        // Route the [`SupervisorSpec::validate`] `:restart-window`
2660        // zero-floor + integer-millisecond canonical-form + upper-cap
2661        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
2662        // accessor rather than the raw `self.restart_window` field access —
2663        // the one production consumer of the per-`:supervisor`
2664        // restart-intensity-denominator scalar now keys off exactly one
2665        // typed dispatch on the substrate primitive, so any future rebrand
2666        // on the axis (a per-cluster restart-window override the operator
2667        // pins through a future `:supervisor :restart-window-overrides`
2668        // slot, a per-tenant restart-window-alias table the M4 CR
2669        // materializer resolves per-CR) migrates as a single caixa-core
2670        // edit rather than a coordinated rewrite — sibling of the peer M2
2671        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
2672        // on the per-`:limits :wall-clock` axis and the peer M3
2673        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
2674        // per-`:politicas :timeout` axis.
2675        if let Some(w) = self.restart_window() {
2676            // Zero-floor + integer-millisecond canonical-form +
2677            // upper-cap bracket on the typed `:restart-window` axis.
2678            // See
2679            // [`crate::render::require_positive_canonical_bounded_duration`]
2680            // for the full three-arm ordering discipline (zero-floor
2681            // strictly precedes canonical-form so `Duration::ZERO`
2682            // surfaces the self-locating `RestartWindowZero`
2683            // diagnostic; canonical-form strictly precedes the cap arm
2684            // so a sub-millisecond above-cap value surfaces the more
2685            // fundamental round-trip-shape diagnostic first) and the
2686            // three peer typed-`Duration` sites that share this
2687            // canonical bracket ([`crate::MeshPolicy::timeout`],
2688            // [`crate::CircuitBreaker::window`],
2689            // [`crate::LimitsSpec::wall_clock`]). Every validated
2690            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2691            // (1ms..=1h), integer-millisecond granularity.
2692            crate::render::require_positive_canonical_bounded_duration(
2693                w,
2694                SUPERVISOR_RESTART_WINDOW_MAX,
2695                || SupervisorError::RestartWindowZero,
2696                SupervisorError::restart_window_not_canonical,
2697                SupervisorError::restart_window_exceeds_cap,
2698            )?;
2699        }
2700        // Route the per-child DNS-1123 / semver-requirement / duplicate-
2701        // detection fan-out loop through the lifted named per-slot gate
2702        // [`SupervisorSpec::validate_children`] rather than an inline
2703        // three-per-child cascade — every future consumer that wants to
2704        // re-check only the `:children` slot's per-entry axes (the M4
2705        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2706        // admission webhook re-validating one added/renamed child, the
2707        // future wasm-operator's per-child dynamic-add re-validator on
2708        // the `SimpleOneForOne` runtime-add path once dynamic-children
2709        // graduate to a typed slot, a future partial re-validator on a
2710        // per-`:children`-entry patch) reaches every per-entry axis
2711        // through one dispatch rather than re-inlining the three-arm
2712        // cascade in lockstep with `validate` or paying the peer
2713        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
2714        // reach one entry check. Sibling of the peer M3 mesh-slot
2715        // per-slot gate family (`validate_membros` — the exact peer on
2716        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
2717        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
2718        // `validate_placement`; `validate_politicas` routing through
2719        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
2720        // per-slot gate discipline now spans both the M3 mesh-slot
2721        // family and the M2 `:children` per-child-cascade axis on one
2722        // shape: one named per-slot gate per typed per-entry loop.
2723        self.validate_children()?;
2724        Ok(())
2725    }
2726
2727    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
2728    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
2729    /// gate, and duplicate-`:caixa` dedup arm into one call every
2730    /// consumer that wants to re-validate one `:children` entry (or the
2731    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
2732    /// admits reaches through.
2733    ///
2734    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
2735    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
2736    /// three-per-entry shape (DNS-1123 name + semver-requirement +
2737    /// duplicate-`:caixa` dedup), lifted to one named substrate
2738    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2739    /// materializer's admission webhook re-checking one added or renamed
2740    /// child, the future wasm-operator's per-child dynamic-add
2741    /// re-validator on the `SimpleOneForOne` runtime-add path once
2742    /// dynamic-children graduate to a typed slot, a future partial
2743    /// re-validator on a per-`:children`-entry patch — each reaches the
2744    /// three per-entry axes through this one dispatch rather than
2745    /// re-inlining the three-arm cascade in lockstep with `validate`
2746    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
2747    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
2748    /// reach one entry check.
2749    ///
2750    /// Self-contained on `&self` — resolves its own dedup `HashSet`
2751    /// through [`SupervisorSpec::children`] rather than borrowing one
2752    /// threaded down from `validate`, the same posture the peer M3
2753    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
2754    /// [`crate::AplicacaoSpec::validate_contratos`],
2755    /// [`crate::AplicacaoSpec::validate_entrada`],
2756    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
2757    /// consumer that reaches this gate directly (without first calling
2758    /// `validate`) still runs the full per-child cascade — pinned by
2759    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2760    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2761    /// + `validate_children_is_self_contained_on_children_slot`.
2762    ///
2763    /// The three per-entry arms run in the same canonical order the
2764    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
2765    /// the diagnostic every author-declared per-`:children` entry surfaces
2766    /// through `validate` is byte-equal to the diagnostic this gate
2767    /// surfaces when called directly — the equivalence-pin pair
2768    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2769    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2770    /// asserts the two altitudes discriminate the same set on every
2771    /// per-entry-covered input.
2772    pub fn validate_children(&self) -> Result<(), SupervisorError> {
2773        let mut seen = std::collections::HashSet::new();
2774        for child in self.children() {
2775            // Every emitted cluster artifact's `metadata.name` for a
2776            // supervised child derives from this `:children :caixa` value
2777            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
2778            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
2779            // label value on every child's pod identity, and the per-
2780            // child K8s [`Service`][svc] `metadata.name` the future
2781            // wasm-operator (M3) provisions for inter-child supervision
2782            // tree wiring. Each apiserver-side schema on each landing
2783            // site enforces the DNS-1123 label rule on admission; a
2784            // structurally invalid child name (`"Worker"`, `"my_worker"`,
2785            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
2786            // UUID-shaped mistaken-identity slug) silently passes the
2787            // prior empty-/duplicate-only gate and the failure surfaces
2788            // at `kubectl apply` time as a `metadata.name: Invalid value`
2789            // rejection, far from the source caixa.lisp, with no field
2790            // naming the offending `:children` entry. Lifting the gate
2791            // to caixa-build time mirrors the `:membros :caixa` value-
2792            // shape trajectory (3f9d7a0) and the `:placement :clusters`
2793            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
2794            // identifier axis — the supervisor tree's child names —
2795            // through the lifted
2796            // [`crate::render::require_valid_dns_1123_label`] gate the
2797            // seven peer name axes (`:membros :caixa`, `:placement
2798            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
2799            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
2800            // route through, so drift between the eight axes' accepted
2801            // DNS-1123-label sets is structurally impossible.
2802            //
2803            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
2804            crate::render::require_valid_dns_1123_label(
2805                child.nome(),
2806                || SupervisorError::EmptyChildName,
2807                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
2808            )?;
2809            // The author surface for `:children :versao` is the same
2810            // Cargo-shaped semver requirement string `:deps :versao` and
2811            // `:membros :versao` carry — and the lacre pipeline resolves
2812            // all three axes through the same
2813            // [`crate::version::parse_requirement`] entry-point. The
2814            // shared [`crate::render::require_valid_versao_requirement`]
2815            // helper brackets the empty-first + parse cascade both peer
2816            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
2817            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
2818            // :versao`) route through, so drift between the three axes'
2819            // accepted requirement sets is structurally impossible and
2820            // the parse-side no-op the empty-first arm closes (semver's
2821            // empty parse yields an implicit `*`) lives in exactly one
2822            // predicate. Every `ChildSpec::versao` past validate is
2823            // round-trippable through [`crate::parse_requirement`]
2824            // without re-checking at the resolver layer, and the three
2825            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
2826            // are now structurally equivalent by construction.
2827            crate::render::require_valid_versao_requirement(
2828                child.versao_requirement(),
2829                || SupervisorError::empty_child_version(child.nome()),
2830                |reason| {
2831                    SupervisorError::child_versao_invalid(
2832                        child.nome(),
2833                        child.versao_requirement(),
2834                        reason,
2835                    )
2836                },
2837            )?;
2838            crate::render::insert_first_seen(&mut seen, child.nome(), || {
2839                SupervisorError::duplicate_child_caixa(child.nome())
2840            })?;
2841        }
2842        Ok(())
2843    }
2844}
2845
2846/// Cross-slot coherence gate on the supervision tree: no
2847/// `:children :caixa` entry may name the supervisor's own `:nome`.
2848///
2849/// A supervisor that lists itself as a child is a degenerate self-parent
2850/// — the supervision tree is a DAG rooted at the supervisor (OTP child
2851/// specs reference *distinct* child processes; a supervisor is never its
2852/// own child), and the wasm-operator's hierarchical reconciliation would
2853/// otherwise be handed a node that is its own parent: a one-node cycle it
2854/// either rejects far from the source `caixa.lisp` or recurses on. Because
2855/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
2856/// lacre closure root), a child whose `:caixa` equals the supervisor's
2857/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
2858///
2859/// Lives outside [`SupervisorSpec::validate`] because the typed view
2860/// carries the children but not the parent `:nome`; mirrors the
2861/// cross-slot precedence gate `validate_upgrade_from_against_versao`
2862/// (which likewise reads one slot against another at the
2863/// [`crate::layout`] wire-up site) and the mesh self-edge gate
2864/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
2865/// node to itself is structurally not a tree/mesh edge" discipline, here
2866/// on the supervision-tree axis.
2867pub fn validate_no_self_supervision(
2868    children: &[ChildSpec],
2869    parent_nome: &str,
2870) -> Result<(), SupervisorError> {
2871    for child in children {
2872        if child.nome() == parent_nome {
2873            return Err(SupervisorError::child_supervises_self(parent_nome));
2874        }
2875    }
2876    Ok(())
2877}
2878
2879#[derive(Debug, Error, PartialEq, Eq)]
2880pub enum SupervisorError {
2881    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
2882    NoChildren { estrategia: RestartStrategy },
2883    #[error(
2884        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
2885    )]
2886    SimpleOneForOneWithStaticChildren,
2887    #[error(":max-restarts must be > 0")]
2888    ZeroMaxRestarts,
2889    #[error(
2890        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
2891         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
2892         restart-intensity policy into a no-op supervisor: the escalation threshold is \
2893         structurally so high that no realistic restarts-per-:restart-window traffic shape \
2894         can reach it, so the supervisor never escalates to its parent and a bad child can \
2895         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
2896         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
2897         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2898         materializer's admission webhook) emits a `:max-restarts` declaration that is \
2899         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
2900         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
2901         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
2902         band) or restructure the supervision tree (split the flaky child into its own \
2903         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
2904    )]
2905    MaxRestartsExceedsCap { max_restarts: u32 },
2906    #[error(
2907        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
2908         requires Period > 0; a zero window either trips on the first failure or \
2909         never trips depending on operator interpretation. Omit :restart-window to \
2910         express `never reset`; carry a positive duration to express the window."
2911    )]
2912    RestartWindowZero,
2913    #[error(
2914        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
2915         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
2916         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
2917         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
2918         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
2919    )]
2920    RestartWindowNotCanonical { window: Duration },
2921    #[error(
2922        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
2923         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
2924         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
2925         failure-counting window is structurally so long that transient restarts are never \
2926         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
2927         when the child has exceeded its restart budget within the recent window` to `trip the \
2928         parent when the child has exceeded its restart budget over its lifetime`, and the \
2929         supervisor's reset semantic never reaches the child — every typed-slot consumer \
2930         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
2931         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2932         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
2933         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
2934         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
2935         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
2936         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
2937         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
2938         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
2939         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
2940         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
2941         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
2942         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
2943         hiding it behind a rolling-window declaration the cap arm rejects)"
2944    )]
2945    RestartWindowExceedsCap { window: Duration },
2946    #[error("child entry has empty :caixa name")]
2947    EmptyChildName,
2948    #[error(
2949        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
2950         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
2951         name / label value the child name lands in — the per-child \
2952         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
2953         label value, and the future wasm-operator per-child Service `metadata.name` \
2954         — each apiserver-side schema rejects names that don't match; use a \
2955         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
2956    )]
2957    ChildCaixaInvalid { caixa: String, reason: String },
2958    #[error("child {caixa:?} has empty :versao constraint")]
2959    EmptyChildVersion { caixa: String },
2960    #[error(
2961        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
2962         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
2963         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
2964         `:membros :versao` carry; the lacre pipeline resolves all three \
2965         through the same parser)"
2966    )]
2967    ChildVersaoInvalid {
2968        caixa: String,
2969        versao: String,
2970        reason: String,
2971    },
2972    #[error(
2973        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
2974         child_spec.id per supervisor; duplicate children materialize as duplicate \
2975         ComputeUnits in the rendered chart, one silently overwriting the other)"
2976    )]
2977    DuplicateChildCaixa { caixa: String },
2978    #[error(
2979        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
2980         never its own child (the supervision tree is a DAG rooted at the supervisor; \
2981         OTP child specs reference distinct child processes). Since every :nome is a \
2982         globally-unique substrate identity, a child naming the supervisor's own :nome \
2983         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
2984         self-referential :children entry or rename it to the actual child caixa."
2985    )]
2986    ChildSupervisesSelf { caixa: String },
2987}
2988
2989// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
2990// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
2991// and [`validate_no_self_supervision`] onto one substrate primitive per
2992// typed variant — the sibling on `SupervisorError` of the four uniform-shape
2993// `LayoutError`-envelope constructor families the peer
2994// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
2995// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
2996// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
2997// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
2998// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
2999// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
3000// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
3001// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
3002// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
3003// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
3004// variants on `{ de, para }`) already at that discipline on the peer
3005// `AplicacaoError` envelopes.
3006//
3007// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
3008// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
3009// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
3010// self-supervision arm) opened the identical
3011// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
3012// the exact "same block re-inlined at every consumer" shape the PRIME
3013// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
3014// `AplicacaoError` families each closed on their sibling envelopes. The
3015// three variants share one `{ caixa: String }` shape, so the fold routes
3016// each wire-up site through one dispatch per typed variant.
3017//
3018// The macro below generates one static constructor per variant of shape
3019// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
3020// collapses onto one dispatch:
3021// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
3022// struct-literal on the same `&str` fixture. The uniform one-field
3023// construction (`caixa: caixa.to_string()`) is spelled once — inside the
3024// macro — rather than at every wire-up site. Every constructor is
3025// `#[must_use]` so a caller who mistakenly discards the constructed error
3026// trips a compile warning at the wire-up site.
3027//
3028// Every future consumer that wants to construct one of these three
3029// variants outside `SupervisorSpec::validate_children` /
3030// `validate_no_self_supervision` — a deferred
3031// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3032// webhook re-checking one added/renamed child, a future
3033// `feira validate --supervisor` per-caixa admission verb, a per-child
3034// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
3035// once dynamic-children graduate to a typed slot, a per-Supervisor
3036// overlay resolver rejecting a duplicate/self-supervising child against
3037// a cluster-local snapshot — now reaches each variant through one call
3038// rather than re-inlining the three-line struct-literal in lockstep
3039// with the three in-crate wire-up sites.
3040macro_rules! supervisor_caixa_only_ctors {
3041    ($($ctor:ident => $variant:ident),* $(,)?) => {
3042        impl SupervisorError {
3043            $(
3044                #[doc = concat!(
3045                    "Construct a [`SupervisorError::",
3046                    stringify!($variant),
3047                    "`] naming the offending `:children :caixa` (or ",
3048                    "supervisor `:nome`, on the self-supervision arm). ",
3049                    "Folds the uniform `Self::",
3050                    stringify!($variant),
3051                    " { caixa: caixa.to_string() }` one-field ",
3052                    "struct-literal onto one substrate primitive so ",
3053                    "every [`SupervisorSpec::validate_children`] / ",
3054                    "[`validate_no_self_supervision`] wire-up on this ",
3055                    "variant reads through one dispatch rather than the ",
3056                    "pre-lift open-coded struct-literal block."
3057                )]
3058                #[must_use]
3059                pub fn $ctor(caixa: &str) -> Self {
3060                    Self::$variant { caixa: caixa.to_string() }
3061                }
3062            )*
3063        }
3064    };
3065}
3066
3067supervisor_caixa_only_ctors! {
3068    empty_child_version => EmptyChildVersion,
3069    duplicate_child_caixa => DuplicateChildCaixa,
3070    child_supervises_self => ChildSupervisesSelf,
3071}
3072
3073// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
3074// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
3075// one substrate primitive per typed variant — the M2 supervisor-side siblings
3076// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
3077// already lifted through the sibling
3078// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
3079// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
3080// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
3081// String }` two-slot shape the peer seven-variant
3082// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
3083// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
3084// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
3085// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
3086// variant carries the `{ caixa: String, versao: String, reason: String }`
3087// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
3088// carries on the same `:versao` value-shape.
3089//
3090// Each of the two wire-up sites opened the same closure-shaped
3091// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
3092// [versao: child.versao_requirement().to_string(),] reason }` block inside
3093// the paired [`crate::render::require_valid_dns_1123_label`] and
3094// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
3095// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
3096// as a bug, on the same altitude the peer `AplicacaoError` /
3097// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
3098// families already closed on their sibling envelopes.
3099//
3100// The two `#[must_use]` inherent constructors below fold each wire-up onto
3101// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
3102// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
3103// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
3104// The uniform per-field `.to_string()` / `.into()` construction is spelled
3105// once — inside each ctor body — rather than at every wire-up site. The
3106// `reason: impl Into<String>` bound accepts both `&str` literals and
3107// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
3108// diagnostic shape at the lift, matching the peer
3109// [`aplicacao_field_reason_ctors!`] and
3110// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
3111// sibling envelopes.
3112//
3113// Every future consumer that wants to construct one of these two variants
3114// outside `SupervisorSpec::validate_children` — a deferred
3115// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
3116// re-checking one added/renamed child's `:caixa` or `:versao`, a future
3117// `feira validate --supervisor` per-caixa admission verb, a per-child
3118// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
3119// dynamic-children graduate to a typed slot, a per-Supervisor overlay
3120// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
3121// cluster-local snapshot — now reaches each variant through one call rather
3122// than re-inlining the per-shape struct-literal block in lockstep with the
3123// two in-crate wire-up sites.
3124impl SupervisorError {
3125    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
3126    /// offending `:children :caixa` value under the given `reason`. Folds
3127    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
3128    /// reason: reason.into() }` two-slot struct-literal onto one substrate
3129    /// primitive so every wire-up on this variant reads through one
3130    /// dispatch, matching the peer
3131    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
3132    /// sibling `AplicacaoError { caixa: String, reason: String }`
3133    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
3134    /// outputs through the `impl Into<String>` bound.
3135    #[must_use]
3136    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
3137        Self::ChildCaixaInvalid {
3138            caixa: caixa.to_string(),
3139            reason: reason.into(),
3140        }
3141    }
3142
3143    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
3144    /// offending `:children :caixa` and its `:versao` requirement under
3145    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
3146    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
3147    /// reason.into() }` three-slot struct-literal onto one substrate
3148    /// primitive so every wire-up on this variant reads through one
3149    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
3150    /// { caixa, versao, reason }` three-slot axis on the peer
3151    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
3152    /// and `format!(…)` outputs through the `impl Into<String>` bound.
3153    #[must_use]
3154    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
3155        Self::ChildVersaoInvalid {
3156            caixa: caixa.to_string(),
3157            versao: versao.to_string(),
3158            reason: reason.into(),
3159        }
3160    }
3161}
3162
3163// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
3164// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
3165// three bracket-arms — one struct-literal at the `:children`-empty
3166// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
3167// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
3168// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
3169// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
3170// [`crate::render::require_positive_canonical_bounded_duration`]
3171// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
3172// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
3173// primitive per typed variant, matching the sibling
3174// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
3175// variants on the same `{ <field>: Duration | u32 }` shape) at that
3176// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
3177// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
3178// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
3179// wire-up site through one dispatch per typed variant without a runtime-
3180// work delta.
3181//
3182// Each of the four wire-up sites opened the identical
3183// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
3184// exact "same block re-inlined at every consumer" shape the PRIME
3185// DIRECTIVE names as a bug, on the same altitude the peer
3186// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
3187// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
3188// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
3189// the fold routes each wire-up site through one dispatch per typed
3190// variant.
3191//
3192// The macro below generates one static constructor per variant of shape
3193// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
3194// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
3195// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
3196// fixture — as a direct call at the [`SupervisorSpec::validate`]
3197// `:children`-empty refusal, or as a bare function pointer in the
3198// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
3199// [`crate::render::require_positive_bounded_u32`] /
3200// [`crate::render::require_positive_canonical_bounded_duration`] gate
3201// carries — rather than the pre-lift open-coded one-line closure over
3202// the same one-field struct-literal. `const fn` preserves the `Copy`-
3203// pass-through's zero-runtime-work property verbatim. Every constructor
3204// is `#[must_use]` so a caller who mistakenly discards the constructed
3205// error trips a compile warning at the wire-up site.
3206//
3207// Every future consumer that wants to construct one of these four
3208// variants outside `SupervisorSpec::validate` — a deferred
3209// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3210// webhook re-checking one edited `:estrategia` / `:max-restarts` /
3211// `:restart-window` slot against the cap + canonical-form cascade, a
3212// future `feira validate --supervisor` per-caixa admission verb re-
3213// running the shape gates on demand, a per-Supervisor overlay resolver
3214// rejecting an author-supplied slot against a cluster-local snapshot —
3215// now reaches each variant through one call rather than re-inlining the
3216// per-shape struct-literal block in lockstep with the four in-crate
3217// wire-up sites.
3218macro_rules! supervisor_scalar_ctors {
3219    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
3220        impl SupervisorError {
3221            $(
3222                #[doc = concat!(
3223                    "Construct a [`SupervisorError::",
3224                    stringify!($variant),
3225                    "`] naming the offending per-`:supervisor` `",
3226                    stringify!($field),
3227                    "` scalar. Folds the uniform `Self::",
3228                    stringify!($variant),
3229                    " { ",
3230                    stringify!($field),
3231                    " }` one-field `Copy`-pass-through struct-literal onto ",
3232                    "one substrate primitive so every per-axis wire-up on ",
3233                    "this variant reads through one dispatch — as a direct ",
3234                    "call (`SupervisorError::",
3235                    stringify!($ctor),
3236                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
3237                    "the same `Copy`-`",
3238                    stringify!($ty),
3239                    "` fixture) or as a bare function pointer in the ",
3240                    "`impl FnOnce(",
3241                    stringify!($ty),
3242                    ") -> SupervisorError` bracket-closure slot every ",
3243                    "`crate::render::require_positive_bounded_*` / ",
3244                    "`crate::render::require_positive_canonical_bounded_*` ",
3245                    "gate carries — rather than the pre-lift open-coded ",
3246                    "one-line closure over the same one-field struct-",
3247                    "literal. `const fn` preserves the `Copy`-pass-through's ",
3248                    "zero-runtime-work property verbatim."
3249                )]
3250                #[must_use]
3251                pub const fn $ctor($field: $ty) -> Self {
3252                    Self::$variant { $field }
3253                }
3254            )*
3255        }
3256    };
3257}
3258
3259supervisor_scalar_ctors! {
3260    no_children => NoChildren { estrategia: RestartStrategy },
3261    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
3262    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
3263    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
3264}
3265
3266/// Shared duration string codec for the typed slots that take a
3267/// duration (`restart_window`, `MeshPolicy::timeout`,
3268/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
3269/// reuse it without duplicating the parser.
3270pub mod duration_codec {
3271    use super::Duration;
3272    use serde::{Deserializer, Serializer};
3273
3274    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
3275        // Route through the canonical [`crate::render::serialize_option_via_str`]
3276        // — the substrate-side single-owner primitive for the forward
3277        // arm of the typed-magnitude codec family. See its docstring
3278        // for the full sibling roster.
3279        crate::render::serialize_option_via_str(v, s, render)
3280    }
3281
3282    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
3283        // Route through the canonical [`crate::render::deserialize_option_via_str`]
3284        // — the substrate-side single-owner primitive for the reverse
3285        // arm of the typed-magnitude codec family. See its docstring
3286        // for the full sibling roster.
3287        crate::render::deserialize_option_via_str(d, parse)
3288    }
3289
3290    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
3291        // Paired whitespace-rejection arm — same canonical-form
3292        // render-determinism discipline as the peer
3293        // `limits::parse_byte_size` / `limits::parse_duration` /
3294        // `limits::parse_millicores` /
3295        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
3296        // byte-scan closes the WhatWG-conformant whitespace bytes
3297        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
3298        // `char::is_whitespace` scan closes the strictly-complementary
3299        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
3300        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
3301        // codepoints) that `str::trim` at parse entry silently strips.
3302        // Either drift class would round-trip through `render` to a
3303        // *different* canonical form on next emit — breaking the
3304        // THEORY.md Part V render-determinism contract on three typed-
3305        // duration slots at once (`:supervisor :restart-window`,
3306        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
3307        // via the shared codec.
3308        //
3309        // Routed through the lifted [`crate::render::reject_whitespace`]
3310        // primitive — the substrate-side single-owner paired-arm gate
3311        // every typed-magnitude codec in caixa-core shares.
3312        crate::render::reject_whitespace::<String, _, _>(
3313            s,
3314            |b| {
3315                format!(
3316                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
3317                 authoring form for the typed duration slots routed through this shared codec \
3318                 (`:supervisor :restart-window`, `:politicas :timeout`, \
3319                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3320                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
3321                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
3322                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
3323                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
3324                 Part V render-determinism contract every typed slot carries. Strip every \
3325                 whitespace byte (write `\"30s\"` verbatim)"
3326                )
3327            },
3328            |ch| {
3329                format!(
3330                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
3331                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
3332                 duration slots routed through this shared codec (`:supervisor \
3333                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
3334                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
3335                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
3336                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
3337                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
3338                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
3339                 `White_Space` property, strictly wider than the ASCII byte set) silently \
3340                 strips it at parse entry, and the value round-trips through `render` to \
3341                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
3342                 the THEORY.md Part V render-determinism contract every typed slot \
3343                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
3344                 verbatim with only ASCII bytes)",
3345                    cp = ch as u32
3346                )
3347            },
3348        )?;
3349        let s = s.trim();
3350        // Routed through the lifted
3351        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
3352        // the single-owner split every ASCII-alphabetic-unit typed-
3353        // magnitude codec in caixa-core (`limits::parse_byte_size` /
3354        // `limits::parse_duration` / this shared duration codec) shares.
3355        // See its docstring for the full sibling roster on the same
3356        // primitive altitude.
3357        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
3358        let num_trim = num_part.trim();
3359        // The canonical authoring form for every typed slot routed
3360        // through this shared codec — `:supervisor :restart-window`,
3361        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
3362        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
3363        // non-negative integer with no decimal point and no leading
3364        // sign, so the parser's accepted set must match for
3365        // serialize/deserialize to round-trip without canonical-form
3366        // drift. Until this gate landed the parser accepted any
3367        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
3368        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
3369        // tripped the value to a *different* canonical string on the
3370        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
3371        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
3372        // — breaking the THEORY.md Part V render-determinism contract
3373        // on three typed slots at once. Same canonical-form discipline
3374        // `crate::limits::parse_duration` (818dd38, the immediate
3375        // predecessor on the peer `:limits :wall-clock` codec) applies;
3376        // this gate lifts the discipline onto the shared codec that
3377        // backs the remaining three typed-duration slots in caixa-core.
3378        //
3379        // Strict canonical form: every byte of the magnitude is an
3380        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
3381        // inputs the gate distinguishes "non-canonical-but-numeric"
3382        // (parses as f64 or i64 — surfaced with a self-locating
3383        // diagnostic naming the canonical authoring form, the
3384        // round-trip drift each rejected shape would produce on first
3385        // serialize, and the canonical-form remediation) from
3386        // "garbage" (parses as neither — surfaced with the existing
3387        // narrower "bad duration magnitude" wording so its diagnostic
3388        // shape remains stable for the parser-shape footgun case).
3389        // The pre-existing `num < 0.0` arm is now unreachable — the
3390        // digit-only gate strictly precedes magnitude parsing, and a
3391        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
3392        // non-canonical-but-numeric branch with the `-30` named
3393        // verbatim in the diagnostic rather than the prior
3394        // value-laundered "negative duration in \"-30s\"" wording.
3395        //
3396        // Routed through the lifted
3397        // [`crate::render::is_digit_only_magnitude`] predicate — the
3398        // same source of truth the four peer typed-magnitude codec
3399        // sites share.
3400        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
3401        if !digit_only {
3402            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
3403            if numeric {
3404                return Err(format!(
3405                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
3406                     canonical authoring form for the typed duration slots routed through \
3407                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3408                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3409                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
3410                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
3411                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
3412                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
3413                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
3414                     THEORY.md Part V render-determinism contract every typed slot carries. \
3415                     Pick an integer magnitude in the unit that divides cleanly (write \
3416                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
3417                ));
3418            }
3419            return Err(format!("bad duration magnitude in {s:?}"));
3420        }
3421        // Leading-zero arm — peer with the `rate_limit_codec` leading-
3422        // zero arm (4f46830) on the same canonical-form render-
3423        // determinism axis. The digit-only gate accepts `"030s"`,
3424        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
3425        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
3426        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
3427        // *different* canonical string on the next emit, breaking the
3428        // THEORY.md Part V render-determinism contract the same way
3429        // `"+30s"` did before the leading-`+` arm landed. The single-
3430        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
3431        // losslessly through `render` (`render(Duration::ZERO)` emits
3432        // `"0s"`) — the downstream semantic-zero gates (e.g.
3433        // `SupervisorError::ZeroRestartWindow` on
3434        // `:supervisor :restart-window`,
3435        // `AplicacaoError::PolicyTimeoutZero` /
3436        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
3437        // duration slots) refuse zero-magnitude authoring at the typed-
3438        // validate layer above, so the single-byte `"0"` stays in the
3439        // accepted set at this codec layer and the diagnostic
3440        // partitioning between canonical-form drift (this arm) and
3441        // semantic-zero (the downstream gates) remains stable.
3442        // Peer with the future leading-zero arms on the two remaining
3443        // typed-magnitude codecs the trajectory acknowledges:
3444        // `limits::parse_duration` backing `:limits :wall-clock`,
3445        // `limits::parse_byte_size` backing `:limits :memory` — each
3446        // carries the same canonical-form-drift class today; this
3447        // gate lands the discipline on the shared duration codec
3448        // first because the `rate_limit_codec` predecessor on the
3449        // same canonical-form-drift axis is the closest peer on the
3450        // trajectory.
3451        //
3452        // Routed through the lifted
3453        // [`crate::render::is_leading_zero_padded_magnitude`]
3454        // predicate — the same source of truth the four peer
3455        // typed-magnitude codec sites share.
3456        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
3457            return Err(format!(
3458                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
3459                 canonical authoring form for the typed duration slots routed through \
3460                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3461                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3462                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
3463                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
3464                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
3465                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
3466                 serialize — breaking the THEORY.md Part V render-determinism contract \
3467                 every typed slot carries. Strip the leading zeros (write \
3468                 `\"30s\"` instead of `\"030s\"`)"
3469            ));
3470        }
3471        // The digit-only gate guarantees every byte is `[0-9]`, and
3472        // the leading-zero arm above guarantees the magnitude is
3473        // either the single byte `"0"` or starts with `[1-9]`, so
3474        // the only way `u64::from_str` can fail here is overflow (the
3475        // magnitude exceeds `u64::MAX`). Surface that with an
3476        // overflow-shaped wording so the diagnostic names the offending
3477        // magnitude verbatim rather than collapsing onto the
3478        // non-canonical arm. The codec now operates on `u64` end-to-end
3479        // — every accepted magnitude is integer-exact; no f64 mantissa
3480        // drift between author-supplied magnitude and the consumer's
3481        // `Duration` value. Same shape `crate::limits::parse_duration`
3482        // (818dd38) carries on the peer `:limits :wall-clock` axis.
3483        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
3484            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
3485        })?;
3486        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
3487        // unit-arm dispatch through the canonical
3488        // [`crate::render::duration_from_integer_magnitude_and_unit`]
3489        // primitive — the substrate-side single-owner unit-dispatch
3490        // table every typed-duration codec in caixa-core routes
3491        // through (peer: `crate::limits::parse_duration` backing
3492        // `:limits :wall-clock`). Every unit conversion is integer-
3493        // exact for an integer magnitude; overflow surfaces via the
3494        // typed `DurationUnitError::Overflow { multiplier }`
3495        // discriminant so this arm reconstructs the pre-lift
3496        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
3497        // wording verbatim from `num` / `unit_trim` / the returned
3498        // `multiplier`, and the unknown-unit arm reconstructs the
3499        // pre-lift `"unknown duration unit \"<other>\""` wording from
3500        // the caller-scoped `unit_trim`. Load-bearing pinned by
3501        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
3502        let unit_trim = unit.trim();
3503        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
3504            |e| match e {
3505                crate::render::DurationUnitError::Overflow { multiplier } => format!(
3506                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
3507                ),
3508                crate::render::DurationUnitError::UnknownUnit => {
3509                    format!("unknown duration unit {unit_trim:?}")
3510                }
3511            },
3512        )?;
3513        Ok(dur)
3514    }
3515
3516    /// Render a [`Duration`] in the canonical pleme-io duration string
3517    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
3518    /// caixa typed-duration slot serializes to and the same form K8s
3519    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
3520    /// EnvoyConfig per-route timeouts both expect (an integer
3521    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
3522    /// `+`). Lifted to `pub` so caixa-side renderers
3523    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
3524    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
3525    /// emitter, the future caixa-otel collector pipeline emitter) can
3526    /// consume the same canonical formatter without re-inlining the
3527    /// magnitude/unit decision tree (and inheriting the same drift
3528    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
3529    /// downstream apply-time parsing in non-obvious ways).
3530    pub fn render(d: Duration) -> String {
3531        let total_ms = d.as_millis();
3532        if total_ms == 0 {
3533            return "0s".into();
3534        }
3535        if total_ms.is_multiple_of(3600 * 1000) {
3536            return format!("{}h", total_ms / (3600 * 1000));
3537        }
3538        if total_ms.is_multiple_of(60 * 1000) {
3539            return format!("{}m", total_ms / (60 * 1000));
3540        }
3541        if total_ms.is_multiple_of(1000) {
3542            return format!("{}s", total_ms / 1000);
3543        }
3544        format!("{total_ms}ms")
3545    }
3546
3547    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
3548    ///
3549    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
3550    /// largest divisor unit, so any sub-millisecond residue
3551    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
3552    /// §V.2.7 render-determinism contract:
3553    ///
3554    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
3555    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
3556    ///     `1_000_000` ns ≠ original `1_500_000` ns;
3557    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
3558    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
3559    ///     on every typed-`Duration` slot then rejects on re-validate.
3560    ///
3561    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
3562    /// the codec's round-trippable accepted set lives in exactly one place —
3563    /// every typed-`Duration` slot that routes through this shared codec
3564    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
3565    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
3566    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
3567    /// every typed-`Duration` slot whose own codec shares the same
3568    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
3569    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
3570    /// pair) calls this predicate from its `validate()` to bracket the
3571    /// accepted set against the codec's accepted set, structurally. Drift
3572    /// between the codec's granularity and any typed slot's accepted set is
3573    /// then a single-source-of-truth edit at this predicate rather than a
3574    /// silent round-trip break the next consumer discovers at apply time.
3575    ///
3576    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
3577    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
3578    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
3579    /// family — same "typed-slot's valid set matches its codec's accepted
3580    /// set, structurally" discipline carried at the codec layer.
3581    #[must_use]
3582    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
3583        d.subsec_nanos().is_multiple_of(1_000_000)
3584    }
3585}
3586
3587/// Required-Duration variant for fields that aren't Option<Duration>.
3588pub mod duration_codec_required {
3589    use super::Duration;
3590    use serde::{Deserialize, Deserializer, Serializer};
3591
3592    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
3593        s.serialize_str(&super::duration_codec::render(*v))
3594    }
3595
3596    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
3597        let s = String::deserialize(d)?;
3598        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
3599    }
3600}
3601
3602#[cfg(test)]
3603mod tests {
3604    use super::*;
3605
3606    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
3607        ChildSpec {
3608            caixa: name.into(),
3609            versao: ver.into(),
3610            restart,
3611        }
3612    }
3613
3614    #[test]
3615    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
3616        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
3617        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
3618        // posture. Each accessor projects the per-`:children :caixa`
3619        // / per-`:children :versao` [`String`] storage through the
3620        // `pub const fn` [`String::as_str`] (const-stable since Rust
3621        // 1.87, well within the workspace MSRV) — any future
3622        // accidental downgrade to non-`const` fails the corresponding
3623        // `<name>_via_const_fn` wrapper at caixa-core build time with
3624        // E0015 (`cannot call non-const method`), strictly stronger
3625        // than a runtime `assert!`. Sibling of the peer
3626        // per-M2/M3/universal-axis `String → &str` scalar-accessor
3627        // family pins on the sibling `const`-eval-surface passes
3628        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
3629        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
3630        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
3631        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
3632        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
3633        // [`crate::aplicacao::Entrada::destination`] at the M3
3634        // ingress axis,
3635        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
3636        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
3637        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
3638        // axis, and the per-`:contratos`
3639        // [`crate::aplicacao::WitContract::source`] /
3640        // [`crate::aplicacao::WitContract::destination`] /
3641        // [`crate::aplicacao::WitContract::world_ref`] trio the
3642        // sibling pin at 279823b already anchors).
3643        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
3644            c.nome()
3645        }
3646        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
3647            c.versao_requirement()
3648        }
3649        for (caixa, versao) in [
3650            ("worker-a", "^0.1"),
3651            ("worker-b", "~0.2.3"),
3652            ("collector", "*"),
3653        ] {
3654            let c = child(caixa, versao, RestartPolicy::Permanent);
3655            assert_eq!(nome_via_const_fn(&c), c.nome());
3656            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
3657            assert_eq!(c.nome(), caixa);
3658            assert_eq!(c.versao_requirement(), versao);
3659        }
3660    }
3661
3662    #[test]
3663    fn supervisor_children_slice_return_accessor_is_const_fn() {
3664        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
3665        // `const`-eval-surface posture. The accessor destructures the
3666        // per-`:children` `Vec<ChildSpec>` storage through the
3667        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
3668        // 1.66, well within the workspace MSRV) — any future
3669        // accidental downgrade to non-`const` fails
3670        // `children_via_const_fn` at caixa-core build time with E0015
3671        // (`cannot call non-const method`), strictly stronger than a
3672        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
3673        // `Vec → &[T]` slice-return accessor family pin
3674        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
3675        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
3676        // per-`:membros` / per-`:contratos` slice-return axes, and of
3677        // the peer M2 upgrade-appup axis pin
3678        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
3679        // on the per-`:upgrade-from :instructions` slice-return axis.
3680        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
3681            s.children()
3682        }
3683        // Sweep both the empty-children (leaf-supervisor with no
3684        // static children — the `SimpleOneForOne` dynamic-child
3685        // arm's canonical shape) and the populated-children
3686        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
3687        // arm's canonical shape) axes so the accessor carries a
3688        // const-dispatch pin on both arms.
3689        let s_empty = SupervisorSpec {
3690            estrategia: RestartStrategy::SimpleOneForOne,
3691            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3692            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3693            children: vec![],
3694        };
3695        assert!(children_via_const_fn(&s_empty).is_empty());
3696        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
3697        let s_full = SupervisorSpec {
3698            estrategia: RestartStrategy::OneForOne,
3699            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3700            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3701            children: vec![
3702                child("worker-a", "^0.1", RestartPolicy::Permanent),
3703                child("worker-b", "~0.2.3", RestartPolicy::Transient),
3704                child("collector", "*", RestartPolicy::Temporary),
3705            ],
3706        };
3707        assert_eq!(children_via_const_fn(&s_full).len(), 3);
3708        assert_eq!(children_via_const_fn(&s_full), s_full.children());
3709    }
3710
3711    #[test]
3712    fn default_has_one_for_one_and_5_restarts_in_60s() {
3713        let s = SupervisorSpec::default();
3714        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
3715        assert_eq!(s.max_restarts, 5);
3716        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
3717        assert!(s.children.is_empty());
3718    }
3719
3720    #[test]
3721    fn validate_one_for_one_requires_children() {
3722        let mut s = SupervisorSpec::default();
3723        s.children = vec![];
3724        assert!(matches!(
3725            s.validate().unwrap_err(),
3726            SupervisorError::NoChildren { .. }
3727        ));
3728        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
3729        s.validate().unwrap();
3730    }
3731
3732    #[test]
3733    fn validate_simple_one_for_one_forbids_static_children() {
3734        let mut s = SupervisorSpec {
3735            estrategia: RestartStrategy::SimpleOneForOne,
3736            ..SupervisorSpec::default()
3737        };
3738        s.children
3739            .push(child("w", "^0.1", RestartPolicy::Permanent));
3740        assert_eq!(
3741            s.validate().unwrap_err(),
3742            SupervisorError::SimpleOneForOneWithStaticChildren
3743        );
3744        s.children.clear();
3745        s.validate().unwrap();
3746    }
3747
3748    #[test]
3749    fn validate_rejects_zero_max_restarts() {
3750        let s = SupervisorSpec {
3751            max_restarts: 0,
3752            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3753            ..SupervisorSpec::default()
3754        };
3755        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
3756    }
3757
3758    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
3759    //
3760    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
3761    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
3762    // `:supervisor :max-restarts` axis — both fields are "trip the
3763    // next-higher protection layer after N events in a rolling window"
3764    // counters with identical degenerate-at-the-high-end shape, so the
3765    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
3766    // exactly as it lies in `1..=1000` on the breaker side.
3767
3768    #[test]
3769    fn validate_rejects_max_restarts_above_cap() {
3770        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
3771        // 1` is structurally one past the cap and silently passed
3772        // validate on every pre-gate codebase because the typed slot's
3773        // only check was the zero-floor arm. The no-op-supervisor vector
3774        // only surfaced at the runtime substrate (Erlang/OTP
3775        // MaxIntensity/Period ratio, the future wasm-operator's
3776        // per-supervisor restart-intensity counter) far from the source
3777        // caixa.lisp with no field naming the offending supervisor.
3778        let s = SupervisorSpec {
3779            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3780            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3781            ..SupervisorSpec::default()
3782        };
3783        assert_eq!(
3784            s.validate().unwrap_err(),
3785            SupervisorError::MaxRestartsExceedsCap {
3786                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3787            }
3788        );
3789    }
3790
3791    #[test]
3792    fn validate_rejects_max_restarts_far_above_cap() {
3793        // The `u32::MAX` worst case — the four-billion-restart
3794        // threshold a typo (`:max-restarts 4294967295`) or a
3795        // struct-literal copy-paste lands in the slot. Pin the cap
3796        // arm's coverage explicitly across the full `u32` overflow so
3797        // a future relaxation that drops the upper bound surfaces
3798        // here. Same shape every other typed-cap arm on this surface
3799        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
3800        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
3801        let s = SupervisorSpec {
3802            max_restarts: u32::MAX,
3803            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3804            ..SupervisorSpec::default()
3805        };
3806        assert_eq!(
3807            s.validate().unwrap_err(),
3808            SupervisorError::MaxRestartsExceedsCap {
3809                max_restarts: u32::MAX,
3810            }
3811        );
3812    }
3813
3814    #[test]
3815    fn validate_accepts_max_restarts_at_cap() {
3816        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
3817        // must validate. The cap is inclusive on the top edge,
3818        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
3819        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
3820        // discipline on the sibling capped axes. Pin the boundary
3821        // explicitly so a future off-by-one tightening
3822        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
3823        // here as a test failure rather than a silent contract
3824        // narrowing.
3825        let s = SupervisorSpec {
3826            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
3827            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3828            ..SupervisorSpec::default()
3829        };
3830        s.validate()
3831            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
3832    }
3833
3834    #[test]
3835    fn validate_accepts_max_restarts_typical_values() {
3836        // The documented production-playbook band positive-control
3837        // sweep — every value Erlang/OTP / Elixir / Riak Core /
3838        // RabbitMQ recommend (1..=100) must pass, plus a sweep
3839        // through the hyperscale band (200, 500, 1000) the cap
3840        // accepts. Pin the inclusive validated set explicitly so a
3841        // future tightening of the ceiling surfaces here.
3842        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
3843            let s = SupervisorSpec {
3844                max_restarts: n,
3845                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3846                ..SupervisorSpec::default()
3847            };
3848            s.validate()
3849                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
3850        }
3851    }
3852
3853    #[test]
3854    fn zero_max_restarts_takes_precedence_over_cap() {
3855        // The cross-arm ordering pin: `0` is structurally outside
3856        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
3857        // (cap), but the zero-floor diagnostic is the more
3858        // self-locating one (it directly names the counter-axis
3859        // remediation), so the validate gate must fire on zero first.
3860        // Same shape every other zero-then-shape ordering on this
3861        // surface uses (PolicyRetriesZero then
3862        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
3863        // PolicyBreakerMaxFailuresExceedsCap).
3864        let s = SupervisorSpec {
3865            max_restarts: 0,
3866            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3867            ..SupervisorSpec::default()
3868        };
3869        assert_eq!(
3870            s.validate().unwrap_err(),
3871            SupervisorError::ZeroMaxRestarts,
3872            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
3873        );
3874    }
3875
3876    #[test]
3877    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
3878        // The cross-arm ordering pin between the cap and the sibling
3879        // `:restart-window` gates (zero-window, canonical-window). A
3880        // supervisor carrying both an over-cap `max_restarts` AND a
3881        // structurally invalid window (zero, sub-ms) must surface the
3882        // cap diagnostic first — the cap arm is wired immediately
3883        // after the zero-restart arm and strictly before the window
3884        // arms, so the offending value the diagnostic names matches
3885        // the order the author would discover the gates by reading
3886        // top-to-bottom through `SupervisorSpec::validate`. Pin the
3887        // order so a future refactor that reorders the arms surfaces
3888        // here as a test failure rather than a silent diagnostic
3889        // regression. Peer of
3890        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
3891        // on the sibling `:politicas :circuit-breaker` slot.
3892        let s = SupervisorSpec {
3893            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3894            restart_window: Some(Duration::ZERO),
3895            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3896            ..SupervisorSpec::default()
3897        };
3898        assert_eq!(
3899            s.validate().unwrap_err(),
3900            SupervisorError::MaxRestartsExceedsCap {
3901                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3902            },
3903            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
3904        );
3905    }
3906
3907    #[test]
3908    fn max_restarts_cap_diagnostic_carries_offending_value() {
3909        // The diagnostic-shape pin: the offending `u32` is carried
3910        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
3911        // variant so the surfaced error message names the value the
3912        // author wrote (`":supervisor :max-restarts (50000) exceeds the
3913        // supervisor-policy ceiling …"`), not just the cap. Same
3914        // self-locating diagnostic shape every other typed-cap arm on
3915        // this surface carries
3916        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
3917        // the offending failure count verbatim,
3918        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
3919        // retries count verbatim).
3920        let s = SupervisorSpec {
3921            max_restarts: 50_000,
3922            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3923            ..SupervisorSpec::default()
3924        };
3925        let err = s.validate().unwrap_err();
3926        assert!(
3927            matches!(
3928                err,
3929                SupervisorError::MaxRestartsExceedsCap {
3930                    max_restarts: 50_000
3931                }
3932            ),
3933            "got {err:?}"
3934        );
3935        let msg = err.to_string();
3936        assert!(
3937            msg.contains("50000"),
3938            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
3939        );
3940    }
3941
3942    #[test]
3943    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
3944        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
3945        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
3946        // half of Learn You Some Erlang's worker-supervisor default,
3947        // sibling of the `60s` `Period` half that the paired
3948        // [`Default for SupervisorSpec`] impl already pins on the
3949        // sibling `restart_window` axis. Pinning the literal here
3950        // surfaces a future rebrand (a tightening to Elixir's `3`,
3951        // a widening to a per-cluster overlay the operator pins
3952        // through a future `:max-restarts-overrides` slot) as a
3953        // deliberate test edit, not a silent contract migration.
3954        // Peer of the sibling
3955        // [`supervisor_max_restarts_cap_pins_canonical_value`]
3956        // upper-bracket pin on the same axis.
3957        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
3958    }
3959
3960    #[test]
3961    fn default_max_restarts_helper_routes_through_lifted_default() {
3962        // Composition pin: the private `default_max_restarts()`
3963        // serde-`#[serde(default = "…")]` helper on
3964        // [`SupervisorSpec::max_restarts`] must route through the
3965        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3966        // typed `pub const` rather than a raw `5` literal. Prior to
3967        // the lift the helper carried an inline `5` with no compile-
3968        // time link back to the shared default, so the wire-format
3969        // author-omitted arm and the caixa-core
3970        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
3971        // arm could silently split on any future default rebrand.
3972        // Byte-parity against the lifted constant closes the split.
3973        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
3974    }
3975
3976    #[test]
3977    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
3978        // Composition pin: the [`Default for SupervisorSpec`] impl's
3979        // struct-literal `max_restarts` field must route through the
3980        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3981        // typed `pub const` (via the private helper this test's
3982        // sibling `default_max_restarts_helper_routes_through_lifted_default`
3983        // already pins onto the constant). Structurally: every
3984        // `SupervisorSpec::default()` call must yield a
3985        // `max_restarts` field byte-equal to the lifted constant
3986        // (the two paired defaults — the serde-side wire-format arm
3987        // and the struct-literal default arm — cannot silently split
3988        // on any future default rebrand). Peer of the sibling
3989        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
3990        // — this pin closes the byte-parity arm on the two paired
3991        // altitude entry points onto the shared substrate constant.
3992        assert_eq!(
3993            SupervisorSpec::default().max_restarts(),
3994            SUPERVISOR_MAX_RESTARTS_DEFAULT,
3995        );
3996    }
3997
3998    #[test]
3999    fn supervisor_restart_window_default_pins_otp_canonical_value() {
4000        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
4001        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
4002        // Learn You Some Erlang's worker-supervisor default, paired
4003        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
4004        // `MaxIntensity` half this constant is the sliding-window
4005        // denominator of on the same `MaxIntensity / Period`
4006        // restart-intensity ratio. Pinning the literal here surfaces a
4007        // future coherent rebrand of the paired default (Elixir's
4008        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
4009        // the operator pins through a future
4010        // `:restart-window-overrides` slot) as a deliberate test edit,
4011        // not a silent contract migration. Peer of the sibling
4012        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
4013        // paired-half pin on the same OTP-canonical default and the
4014        // [`supervisor_restart_window_cap_pins_canonical_value`]
4015        // upper-bracket pin on the same axis.
4016        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
4017    }
4018
4019    #[test]
4020    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
4021        // Composition pin: the [`Default for SupervisorSpec`] impl's
4022        // struct-literal `restart_window` field must route through the
4023        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4024        // typed `pub const` rather than a raw
4025        // `Duration::from_secs(60)` literal. Prior to this lift the
4026        // paired `{intensity, 5, 60}` OTP-canonical default was split
4027        // across two altitudes with no compile-time link between the
4028        // halves — the `MaxIntensity` half rode through the lifted
4029        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
4030        // `Period` half rode as an open-coded literal at the
4031        // composition site, so a future coherent rebrand of the paired
4032        // canonical would have had to migrate one half through the
4033        // constant and the other through a raw literal in lockstep.
4034        // Byte-parity against the lifted constant on the `Period` half
4035        // closes the split — the paired OTP-canonical default now
4036        // migrates as one unit on any future axis change. Peer of the
4037        // sibling
4038        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4039        // byte-parity pin on the paired `MaxIntensity` half.
4040        assert_eq!(
4041            SupervisorSpec::default().restart_window(),
4042            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4043        );
4044    }
4045
4046    #[test]
4047    fn supervisor_estrategia_default_pins_otp_canonical_value() {
4048        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
4049        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
4050        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
4051        // canonical default, paired with the sibling
4052        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
4053        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
4054        // this constant is the strategy discriminator of on the same
4055        // OTP-canonical worker-supervisor default. Pinning the arm here
4056        // surfaces a future coherent rebrand of the paired triple (Elixir's
4057        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
4058        // intensity/period axes leaving this strategy arm untouched, an OTP
4059        // `rest_for_one` widening once the substrate discovers startup-
4060        // order-coupled child cohorts as the more common worker-supervisor
4061        // shape, a per-cluster overlay the operator pins through a future
4062        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
4063        // supervision-canary roadmap acknowledges) as a deliberate test
4064        // edit, not a silent contract migration. Peer of the sibling
4065        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
4066        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4067        // paired-half pins on the same OTP-canonical default.
4068        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
4069    }
4070
4071    #[test]
4072    fn restart_strategy_default_routes_through_lifted_default() {
4073        // Composition pin: the [`Default for RestartStrategy`] impl's
4074        // return arm must route through the substrate-canonical
4075        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
4076        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
4077        // an inline `Self::OneForOne` with no compile-time link back to
4078        // the shared OTP-canonical `one_for_one` strategy the paired
4079        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
4080        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
4081        // `.unwrap_or_default()` (now
4082        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
4083        // so a future rebrand of the OTP-canonical strategy default (an
4084        // OTP `rest_for_one` widening once the substrate discovers
4085        // startup-order-coupled child cohorts as the more common worker-
4086        // supervisor shape, a per-cluster overlay the operator pins
4087        // through a future `:estrategia-overrides` slot) would have had to
4088        // be threaded through the `Default` impl and the two peer routes
4089        // in lockstep or the three consumers would silently split. Byte-
4090        // parity against the lifted constant closes the split. Peer of
4091        // the sibling
4092        // [`default_max_restarts_helper_routes_through_lifted_default`] +
4093        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4094        // composition pins on the paired `MaxIntensity` + `Period` halves.
4095        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
4096    }
4097
4098    #[test]
4099    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
4100        // Composition pin: the [`Default for SupervisorSpec`] impl's
4101        // struct-literal `estrategia` field must route through the
4102        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
4103        // `pub const` (either directly, or via the
4104        // [`RestartStrategy::default`] impl that the sibling
4105        // `restart_strategy_default_routes_through_lifted_default` pin
4106        // already routes onto the constant). Structurally: every
4107        // `SupervisorSpec::default()` call must yield an `estrategia`
4108        // field byte-equal to the lifted constant (the three paired
4109        // defaults — the [`Default for RestartStrategy`] impl arm, the
4110        // struct-literal default arm here, and the
4111        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
4112        // silently split on any future default rebrand). Peer of the
4113        // sibling
4114        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4115        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4116        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
4117        // of the same `SupervisorSpec::default()` composed altitude.
4118        assert_eq!(
4119            SupervisorSpec::default().estrategia(),
4120            SUPERVISOR_ESTRATEGIA_DEFAULT,
4121        );
4122    }
4123
4124    #[test]
4125    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
4126        // Composition pin: the [`Default for SupervisorSpec`] impl must
4127        // route through the substrate-canonical
4128        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
4129        // rather than a re-hand-authored struct-literal cascade. Sharpens
4130        // the sibling per-arm
4131        // `supervisor_spec_default_*_routes_through_lifted_default` pins
4132        // from a per-field lift into a whole-struct one-source-of-truth
4133        // pin — the derived-until-now [`Default::default`] and the
4134        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
4135        // construction, not by coincidence.
4136        //
4137        // A future extension of the OTP-canonical baseline (a fifth
4138        // `restart_intensity` field the Erlang/OTP `#supervisor` record
4139        // grows, a per-child-cohort split of the `restart_window` /
4140        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
4141        // CR materializer's admission-time overlay pass) reaches both
4142        // paths through exactly one edit on
4143        // [`SupervisorSpec::otp_canonical`] — the derived path could
4144        // silently disagree with the constructor's shape on any new
4145        // field whose [`Default::default`] resolves to a different arm
4146        // than the OTP-canonical baseline the constructor names, while
4147        // this delegated impl reaches the constructor directly and
4148        // picks up every future extension by construction.
4149        //
4150        // Fourth peer on the M2 / M3 typed-slot-spec
4151        // [`Default`]-through-const-ctor fold family — sibling of the
4152        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
4153        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
4154        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
4155        // (91641a4), and [`crate::BehaviorSpec`]
4156        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
4157        // per-`Option`-only-typed-slot folds — extended here onto the
4158        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
4159        // is not "everything `None`" but the Erlang/OTP-canonical
4160        // `{one_for_one, 5, 60}` worker-supervisor triple.
4161        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
4162    }
4163
4164    #[test]
4165    fn supervisor_spec_otp_canonical_byte_equals_default() {
4166        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
4167        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
4168        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
4169        // pin already asserts against the [`Default::default`] path.
4170        // Sharpens the pair-invariant into a per-constructor pin so a
4171        // future extension of [`SupervisorSpec`] with a fifth field
4172        // whose OTP-canonical shape is non-`Default::default`-equivalent
4173        // trips at caixa-core test time rather than at a downstream
4174        // consumer that composed [`SupervisorSpec::otp_canonical`] with
4175        // [`SupervisorSpec::validate`] as its "canonical baseline
4176        // seed".
4177        let canonical = SupervisorSpec::otp_canonical();
4178        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
4179        assert_eq!(canonical.max_restarts, 5);
4180        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
4181        assert!(canonical.children.is_empty());
4182    }
4183
4184    #[test]
4185    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
4186        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
4187        // remain callable from a `const`-bound position so downstream
4188        // `const`-context callers wanting a canonical OTP-baseline seed
4189        // can construct one at compile time without runtime dispatch on
4190        // the derived [`Default::default`]. Peer of the sibling
4191        // `pub const fn` [`crate::LimitsSpec::empty`] /
4192        // [`crate::aplicacao::MeshPolicy::empty`] /
4193        // [`crate::BehaviorSpec::empty`] constructors on the sibling
4194        // typed-slot-spec `pub const fn` axis. If a future edit breaks
4195        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
4196        // (a non-`const` field-default helper, a non-`const`-stable
4197        // container type promotion), this evaluation fails at
4198        // build time on this file rather than at a downstream
4199        // `const`-context call site.
4200        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
4201        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
4202        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
4203        assert_eq!(
4204            CANONICAL.restart_window,
4205            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4206        );
4207        assert!(CANONICAL.children.is_empty());
4208    }
4209
4210    #[test]
4211    fn supervisor_child_restart_default_pins_otp_canonical_value() {
4212        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
4213        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
4214        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
4215        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
4216        // half of the same OTP-shape supervisor-tree default set whose
4217        // per-`:supervisor` halves the sibling
4218        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
4219        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
4220        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
4221        // arm here surfaces a future rebrand of the per-child default (an
4222        // OTP-`transient` widening once the substrate discovers clean-
4223        // completion-aware children as the more common child shape, a
4224        // per-cluster overlay the operator pins through a future
4225        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
4226        // supervision-canary roadmap acknowledges) as a deliberate test
4227        // edit, not a silent contract migration. Peer of the sibling
4228        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
4229        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
4230        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4231        // value pins on the per-`:supervisor` halves.
4232        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
4233    }
4234
4235    #[test]
4236    fn restart_policy_default_routes_through_lifted_default() {
4237        // Composition pin: the [`Default for RestartPolicy`] impl's return
4238        // arm must route through the substrate-canonical
4239        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
4240        // than a raw `Self::Permanent` arm. Prior to the lift the impl
4241        // carried an inline `Self::Permanent` with no compile-time link
4242        // back to the OTP-shape supervisor-tree default set whose three
4243        // per-`:supervisor` halves already rode through lifted constants
4244        // — so a future coherent rebrand of the set would have had to
4245        // migrate three halves through typed constants and this fourth
4246        // through a raw enum arm in lockstep or the supervisor-level and
4247        // child-level defaults would silently drift apart. Byte-parity
4248        // against the lifted constant closes the split. Peer of the
4249        // sibling
4250        // [`restart_strategy_default_routes_through_lifted_default`]
4251        // composition pin on the per-`:supervisor` `:estrategia` axis.
4252        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
4253    }
4254
4255    #[test]
4256    fn child_spec_serde_default_restart_routes_through_lifted_default() {
4257        // Composition pin: the serde-side `#[serde(default)]` on
4258        // [`ChildSpec::restart`] — the wire-format author-omitted
4259        // `:children :restart` arm — must resolve onto the substrate-
4260        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
4261        // (via the [`Default for RestartPolicy`] impl the sibling
4262        // `restart_policy_default_routes_through_lifted_default` pin
4263        // already routes onto the constant). Structurally: a `ChildSpec`
4264        // deserialized from a payload that omits the `restart` key must
4265        // yield a `restart` field byte-equal to the lifted constant, so
4266        // the wire-format author-omitted arm and the
4267        // [`RestartPolicy::default`] impl arm cannot silently split on any
4268        // future default rebrand. Peer of the sibling
4269        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
4270        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4271        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4272        // byte-parity pins on the per-`:supervisor` halves of the same
4273        // author-omitted-slot resolution surface.
4274        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
4275            .expect("ChildSpec must deserialize with the restart key omitted");
4276        assert_eq!(
4277            omitted.restart(),
4278            SUPERVISOR_CHILD_RESTART_DEFAULT,
4279            "an author-omitted :children :restart slot must degrade onto \
4280             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
4281             {:?}, expected {:?})",
4282            omitted.restart(),
4283            SUPERVISOR_CHILD_RESTART_DEFAULT,
4284        );
4285    }
4286
4287    #[test]
4288    fn supervisor_max_restarts_cap_pins_canonical_value() {
4289        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
4290        // 1000 — the same ceiling the peer
4291        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
4292        // `:politicas :circuit-breaker :max-failures` axis (both are
4293        // "trip the next-higher protection layer after N events in a
4294        // rolling window" counters with identical
4295        // degenerate-at-the-high-end shape; uniform top edge so the
4296        // M4 CR materializers and the wasm-operator reconciler reach
4297        // for either field knowing the value is in `1..=1000`). Two
4298        // orders of magnitude above every documented Erlang/OTP /
4299        // Elixir / Riak Core / RabbitMQ production-playbook
4300        // recommendation band and below the clearly-pathological
4301        // "effectively no escalation" floor (10_000, 100_000,
4302        // u32::MAX). Pinning the literal value here surfaces a future
4303        // drift (a relaxation to 10_000, a tightening to 100) as a
4304        // deliberate test edit, not a silent contract narrowing.
4305        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
4306    }
4307
4308    #[test]
4309    fn validate_rejects_empty_child_name() {
4310        let s = SupervisorSpec {
4311            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4312            ..SupervisorSpec::default()
4313        };
4314        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
4315    }
4316
4317    #[test]
4318    fn validate_rejects_empty_child_version() {
4319        let s = SupervisorSpec {
4320            children: vec![child("w", "", RestartPolicy::Permanent)],
4321            ..SupervisorSpec::default()
4322        };
4323        assert!(matches!(
4324            s.validate().unwrap_err(),
4325            SupervisorError::EmptyChildVersion { .. }
4326        ));
4327    }
4328
4329    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
4330
4331    #[test]
4332    fn validate_rejects_invalid_child_versao_requirement() {
4333        // The fail-before-pass-after pin: a non-empty but malformed
4334        // semver requirement (`"^bad-version"`) silently passed
4335        // `validate()` on every pre-gate codebase because the prior
4336        // shape only refused the empty string. The parse failure
4337        // surfaced far downstream at lacre-resolve time with a
4338        // `semver::Error` that didn't name which `:children` entry
4339        // carried the typo. The new gate moves the check to caixa-build
4340        // time at the source caixa.lisp — the third `:versao` typed
4341        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
4342        // structural parity.
4343        let s = SupervisorSpec {
4344            children: vec![
4345                child("worker", "^0.1", RestartPolicy::Permanent),
4346                child("cache", "^bad-version", RestartPolicy::Transient),
4347            ],
4348            ..SupervisorSpec::default()
4349        };
4350        let err = s.validate().unwrap_err();
4351        assert!(
4352            matches!(
4353                err,
4354                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4355                    if caixa == "cache" && versao == "^bad-version"
4356            ),
4357            "got {err:?}"
4358        );
4359    }
4360
4361    #[test]
4362    fn validate_rejects_child_versao_with_double_caret_typo() {
4363        // `"^^0.1"` is the canonical doubled-caret typo — looks
4364        // Cargo-shaped on first glance but fails the parser because
4365        // semver doesn't accept stacked operators. Pin this
4366        // adjacent-shape footgun explicitly so a future relaxation that
4367        // accepts "looks-canonical-but-isn't" forms surfaces here.
4368        let s = SupervisorSpec {
4369            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
4370            ..SupervisorSpec::default()
4371        };
4372        let err = s.validate().unwrap_err();
4373        assert!(
4374            matches!(
4375                err,
4376                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4377                    if caixa == "worker" && versao == "^^0.1"
4378            ),
4379            "got {err:?}"
4380        );
4381    }
4382
4383    #[test]
4384    fn validate_rejects_child_versao_with_v_prefixed_tag() {
4385        // `"v0.1"` is the canonical "git-tag-shape leaking into the
4386        // semver requirement slot" typo — an author copies the
4387        // publish-side git-tag string verbatim into `:versao`, but
4388        // Cargo's semver parser rejects the leading `v`. Same
4389        // adjacent-shape footgun pinned for `:membros :versao`
4390        // (9888b13).
4391        let s = SupervisorSpec {
4392            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
4393            ..SupervisorSpec::default()
4394        };
4395        let err = s.validate().unwrap_err();
4396        assert!(
4397            matches!(
4398                err,
4399                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4400                    if caixa == "worker" && versao == "v0.1"
4401            ),
4402            "got {err:?}"
4403        );
4404    }
4405
4406    #[test]
4407    fn validate_accepts_canonical_child_versao_forms() {
4408        // The Cargo-shaped requirement forms `:deps :versao` and
4409        // `:membros :versao` already accept via
4410        // `crate::parse_requirement` must pass the children gate
4411        // without re-validating at the resolver layer. Pin every leg so
4412        // a future tightening of the canonical set surfaces here as a
4413        // test failure.
4414        for form in [
4415            "^0.1",      // caret — minor-range pin (the most common shape)
4416            "~0.1.2",    // tilde — patch-range pin
4417            "0.1.0",     // exact — single-version pin
4418            "*",         // wildcard — any version (semver::VersionReq::STAR)
4419            ">=0.1, <2", // multi-range — comma-separated comparators
4420        ] {
4421            let s = SupervisorSpec {
4422                children: vec![child("worker", form, RestartPolicy::Permanent)],
4423                ..SupervisorSpec::default()
4424            };
4425            s.validate()
4426                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4427        }
4428    }
4429
4430    #[test]
4431    fn child_versao_empty_takes_precedence_over_invalid() {
4432        // Order pin: the existing `EmptyChildVersion` diagnostic (which
4433        // doesn't try to parse) fires before the new
4434        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
4435        // `:versao` keeps its narrower error message —
4436        // `parse_requirement` would also reject `""`, but the
4437        // empty-string arm is the more self-locating diagnostic for the
4438        // author. Same ordering discipline as
4439        // `membro_versao_empty_takes_precedence_over_invalid` in
4440        // aplicacao.rs.
4441        let s = SupervisorSpec {
4442            children: vec![child("worker", "", RestartPolicy::Permanent)],
4443            ..SupervisorSpec::default()
4444        };
4445        let err = s.validate().unwrap_err();
4446        assert!(
4447            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
4448            "got {err:?}"
4449        );
4450    }
4451
4452    #[test]
4453    fn child_versao_invalid_fires_before_duplicate_check() {
4454        // Order pin: a malformed requirement on a non-duplicate entry
4455        // surfaces *its own* diagnostic (which names the offending
4456        // `:versao` string), even when a later entry would otherwise
4457        // collapse onto an earlier name. The per-entry shape gate runs
4458        // inline before the duplicate-key insert — parallel to
4459        // `membro_versao_invalid_fires_before_duplicate_check` in
4460        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
4461        let s = SupervisorSpec {
4462            children: vec![
4463                child("worker", "^bad", RestartPolicy::Permanent),
4464                child("cache", "^0.1", RestartPolicy::Transient),
4465                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4466            ],
4467            ..SupervisorSpec::default()
4468        };
4469        let err = s.validate().unwrap_err();
4470        assert!(
4471            matches!(
4472                err,
4473                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
4474            ),
4475            "got {err:?}"
4476        );
4477    }
4478
4479    #[test]
4480    fn child_versao_invalid_diagnostic_carries_offending_versao() {
4481        // The diagnostic-shape pin: the error names the offending
4482        // `:versao` value verbatim so the author can grep their
4483        // caixa.lisp without re-running the build, and carries a
4484        // non-empty `reason` from `semver::VersionReq::parse` so the
4485        // parser's own wording flows through to the diagnostic.
4486        let s = SupervisorSpec {
4487            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
4488            ..SupervisorSpec::default()
4489        };
4490        let err = s.validate().unwrap_err();
4491        let SupervisorError::ChildVersaoInvalid {
4492            caixa,
4493            versao,
4494            reason,
4495        } = err
4496        else {
4497            panic!("expected ChildVersaoInvalid, got other variant");
4498        };
4499        assert_eq!(caixa, "worker");
4500        assert_eq!(versao, "not-a-req");
4501        assert!(
4502            !reason.is_empty(),
4503            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
4504        );
4505    }
4506
4507    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
4508
4509    #[test]
4510    fn validate_rejects_child_caixa_with_uppercase() {
4511        // The canonical "I copied the Servico's display name verbatim"
4512        // typo — child caixa names are lowercase per K8s DNS-1123 label
4513        // rule. The diagnostic names the offending name and suggests the
4514        // lower-cased fix in one edit, mirroring the
4515        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
4516        let s = SupervisorSpec {
4517            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
4518            ..SupervisorSpec::default()
4519        };
4520        let err = s.validate().unwrap_err();
4521        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4522            panic!("expected ChildCaixaInvalid, got other variant");
4523        };
4524        assert_eq!(caixa, "Worker");
4525        assert!(
4526            reason.contains("uppercase"),
4527            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
4528        );
4529        assert!(
4530            reason.contains("\"worker\""),
4531            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
4532        );
4533    }
4534
4535    #[test]
4536    fn validate_rejects_child_caixa_with_underscore() {
4537        // The canonical "I'm thinking of a Python module / Postgres
4538        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
4539        // label schema. K8s rejects `metadata.name: my_worker` at
4540        // admission time with an opaque `field is invalid` (no source-
4541        // citing diagnostic). The gate moves it to caixa-build time.
4542        let s = SupervisorSpec {
4543            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
4544            ..SupervisorSpec::default()
4545        };
4546        let err = s.validate().unwrap_err();
4547        assert!(
4548            matches!(
4549                err,
4550                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4551                    if caixa == "my_worker" && reason.contains('_')
4552            ),
4553            "got {err:?}"
4554        );
4555    }
4556
4557    #[test]
4558    fn validate_rejects_child_caixa_with_dot() {
4559        // A `:children :caixa` entry is a single DNS-1123 label, not a
4560        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
4561        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
4562        // (3f9d7a0) on the peer name axis.
4563        let s = SupervisorSpec {
4564            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
4565            ..SupervisorSpec::default()
4566        };
4567        let err = s.validate().unwrap_err();
4568        assert!(
4569            matches!(
4570                err,
4571                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4572                    if caixa == "team.worker" && reason.contains('.')
4573            ),
4574            "got {err:?}"
4575        );
4576    }
4577
4578    #[test]
4579    fn validate_rejects_child_caixa_with_leading_hyphen() {
4580        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
4581        // with an alphanumeric. The K8s apiserver rejects `-worker`
4582        // outright; the renderer would emit a `metadata.name: "-worker"`
4583        // that fails admission far from the source caixa.lisp.
4584        let s = SupervisorSpec {
4585            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
4586            ..SupervisorSpec::default()
4587        };
4588        let err = s.validate().unwrap_err();
4589        assert!(
4590            matches!(
4591                err,
4592                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4593                    if caixa == "-worker" && reason.contains("start and end")
4594            ),
4595            "got {err:?}"
4596        );
4597    }
4598
4599    #[test]
4600    fn validate_rejects_child_caixa_with_trailing_hyphen() {
4601        // The symmetric arm of the boundary rule. Pin separately so
4602        // both ends of the label are covered against a future relaxation
4603        // that only checks one boundary.
4604        let s = SupervisorSpec {
4605            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
4606            ..SupervisorSpec::default()
4607        };
4608        let err = s.validate().unwrap_err();
4609        assert!(
4610            matches!(
4611                err,
4612                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4613                    if caixa == "worker-"
4614            ),
4615            "got {err:?}"
4616        );
4617    }
4618
4619    #[test]
4620    fn validate_rejects_child_caixa_with_unicode() {
4621        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
4622        // (`xn--…`) by the author before it reaches K8s. The byte-by-
4623        // byte ASCII validity check rejects multi-byte UTF-8 sequences
4624        // by the first byte that fails the `[a-z0-9-]` predicate.
4625        let s = SupervisorSpec {
4626            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
4627            ..SupervisorSpec::default()
4628        };
4629        let err = s.validate().unwrap_err();
4630        assert!(
4631            matches!(
4632                err,
4633                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4634                    if caixa == "café"
4635            ),
4636            "got {err:?}"
4637        );
4638    }
4639
4640    #[test]
4641    fn validate_rejects_child_caixa_with_whitespace() {
4642        // Whitespace is the canonical "I pasted from a sketch / doc"
4643        // footgun. The apiserver rejects every `metadata.name` value
4644        // carrying whitespace; pin the gate fires at the right boundary.
4645        let s = SupervisorSpec {
4646            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
4647            ..SupervisorSpec::default()
4648        };
4649        let err = s.validate().unwrap_err();
4650        assert!(
4651            matches!(
4652                err,
4653                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4654                    if caixa == "my worker"
4655            ),
4656            "got {err:?}"
4657        );
4658    }
4659
4660    #[test]
4661    fn validate_rejects_child_caixa_too_long() {
4662        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
4663        // 63 bytes; the K8s apiserver rejects every `metadata.name`
4664        // axis over the limit at admission time. The diagnostic names
4665        // both the cap and the actual length so the author can shorten
4666        // in one edit, mirroring `rejects_membro_caixa_too_long`
4667        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
4668        let too_long = "a".repeat(64);
4669        let s = SupervisorSpec {
4670            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
4671            ..SupervisorSpec::default()
4672        };
4673        let err = s.validate().unwrap_err();
4674        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4675            panic!("expected ChildCaixaInvalid, got other variant");
4676        };
4677        assert_eq!(caixa, too_long);
4678        assert!(
4679            reason.contains("63"),
4680            "diagnostic must name the 63-byte cap (got: {reason:?})"
4681        );
4682        assert!(
4683            reason.contains("64"),
4684            "diagnostic must name the actual length (got: {reason:?})"
4685        );
4686    }
4687
4688    #[test]
4689    fn child_caixa_max_length_validates() {
4690        // The 63-byte boundary control pin — exactly-at-the-cap is
4691        // accepted, mirroring `membro_caixa_max_length_validates`
4692        // (3f9d7a0) and `placement_cluster_max_length_validates`
4693        // (6cbb900). Pinned separately so a future off-by-one tightening
4694        // surfaces here.
4695        let max_label = "a".repeat(63);
4696        let s = SupervisorSpec {
4697            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
4698            ..SupervisorSpec::default()
4699        };
4700        s.validate().unwrap();
4701    }
4702
4703    #[test]
4704    fn validate_accepts_canonical_child_caixa_forms() {
4705        // The realistic shapes a supervised child's `:caixa` carries —
4706        // single-word `worker`, version-suffixed `cache-v2`, single-char
4707        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
4708        // `payment-retry`, all-digit `0`. Pin every leg so a future
4709        // tightening (e.g. requiring a leading lowercase letter) surfaces
4710        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
4711        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
4712        // (6cbb900).
4713        for form in [
4714            "worker",
4715            "cache-v2",
4716            "a",
4717            "db",
4718            "2-pool",
4719            "payment-retry",
4720            "0",
4721        ] {
4722            let s = SupervisorSpec {
4723                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
4724                ..SupervisorSpec::default()
4725            };
4726            s.validate()
4727                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4728        }
4729    }
4730
4731    #[test]
4732    fn child_caixa_empty_takes_precedence_over_invalid() {
4733        // Order pin: the existing `EmptyChildName` diagnostic (which
4734        // doesn't try to parse the DNS-1123 shape) fires before the new
4735        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
4736        // its narrower error message — `is_dns_1123_label` would reject
4737        // the empty string too (boundary check on the first byte), but
4738        // the empty-string arm is the more self-locating diagnostic for
4739        // the author. Same ordering discipline as
4740        // `membro_caixa_empty_takes_precedence_over_invalid` in
4741        // aplicacao.rs.
4742        let s = SupervisorSpec {
4743            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4744            ..SupervisorSpec::default()
4745        };
4746        let err = s.validate().unwrap_err();
4747        assert_eq!(err, SupervisorError::EmptyChildName);
4748    }
4749
4750    #[test]
4751    fn child_caixa_invalid_fires_before_versao_check() {
4752        // Order pin: the per-axis shape gate runs inline before the
4753        // per-entry versao check, so a malformed `:caixa` on an entry
4754        // whose `:versao` would also fail surfaces the more self-
4755        // locating name-axis diagnostic first. Parallel to
4756        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
4757        // and `placement_cluster_invalid_fires_before_duplicate_check`
4758        // (6cbb900).
4759        let s = SupervisorSpec {
4760            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
4761            ..SupervisorSpec::default()
4762        };
4763        let err = s.validate().unwrap_err();
4764        assert!(
4765            matches!(
4766                err,
4767                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
4768            ),
4769            "got {err:?}"
4770        );
4771    }
4772
4773    #[test]
4774    fn child_caixa_invalid_fires_before_duplicate_check() {
4775        // Order pin: a malformed name on a non-duplicate entry surfaces
4776        // its own diagnostic, even when a later entry would otherwise
4777        // collapse onto an earlier name. The per-entry shape gate runs
4778        // inline before the duplicate-key HashSet insert, mirroring
4779        // `placement_cluster_invalid_fires_before_duplicate_check`
4780        // (6cbb900).
4781        let s = SupervisorSpec {
4782            children: vec![
4783                child("Worker", "^0.1", RestartPolicy::Permanent),
4784                child("cache", "^0.1", RestartPolicy::Transient),
4785                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4786            ],
4787            ..SupervisorSpec::default()
4788        };
4789        let err = s.validate().unwrap_err();
4790        assert!(
4791            matches!(
4792                err,
4793                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
4794            ),
4795            "got {err:?}"
4796        );
4797    }
4798
4799    #[test]
4800    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
4801        // The diagnostic-shape pin: the error names the offending
4802        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
4803        // the author can grep their caixa.lisp without re-running the
4804        // build. Mirrors the diagnostic-shape sweep on every prior
4805        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
4806        let s = SupervisorSpec {
4807            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
4808            ..SupervisorSpec::default()
4809        };
4810        let err = s.validate().unwrap_err();
4811        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4812            panic!("expected ChildCaixaInvalid, got other variant");
4813        };
4814        assert_eq!(caixa, "My_Worker");
4815        assert!(
4816            !reason.is_empty(),
4817            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
4818        );
4819    }
4820
4821    // ── value-shape: zero restart_window + duplicate child names ──────────
4822
4823    #[test]
4824    fn validate_accepts_none_restart_window() {
4825        // Omitted `:restart-window` is the "never reset" sentinel —
4826        // valid by design. Mirrors :limits axes where None = unbounded.
4827        let s = SupervisorSpec {
4828            restart_window: None,
4829            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4830            ..SupervisorSpec::default()
4831        };
4832        s.validate().unwrap();
4833    }
4834
4835    #[test]
4836    fn validate_rejects_zero_restart_window() {
4837        // Same "0 means the opposite of what you think" footgun closed
4838        // for :politicas :timeout (Envoy treats 0s as infinite) and
4839        // :limits :wall-clock (wasmtime traps before the call starts).
4840        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
4841        let s = SupervisorSpec {
4842            restart_window: Some(Duration::ZERO),
4843            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4844            ..SupervisorSpec::default()
4845        };
4846        assert_eq!(
4847            s.validate().unwrap_err(),
4848            SupervisorError::RestartWindowZero
4849        );
4850    }
4851
4852    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
4853    //
4854    // The fourth (and last) typed-`Duration` axis in caixa-core to get
4855    // the integer-millisecond canonical-form gate — peer with
4856    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
4857    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
4858    // path is already gated at the shared codec layer (see
4859    // `restart_window_serde_rejects_fractional_seconds`); this arm
4860    // closes the programmatic-struct-literal path the codec gate can't
4861    // see.
4862
4863    #[test]
4864    fn validate_rejects_sub_millisecond_restart_window() {
4865        // The fail-before-pass-after pin: a programmatic
4866        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
4867        // `validate` on every pre-gate codebase, then truncated to
4868        // `as_millis() == 1` on first serialize — the shared codec
4869        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
4870        // 1_000_000 ns, the typed `restart_window` no longer matches
4871        // its rendered form.
4872        let s = SupervisorSpec {
4873            restart_window: Some(Duration::from_micros(1500)),
4874            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4875            ..SupervisorSpec::default()
4876        };
4877        match s.validate().unwrap_err() {
4878            SupervisorError::RestartWindowNotCanonical { window } => {
4879                assert_eq!(window, Duration::from_micros(1500));
4880            }
4881            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4882        }
4883    }
4884
4885    #[test]
4886    fn validate_rejects_one_nanosecond_restart_window() {
4887        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
4888        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
4889        // so the shared codec emits the literal `"0s"` — the next
4890        // serde round-trip would parse back to `Duration::ZERO`, which
4891        // the `RestartWindowZero` arm then rejects on re-validate. The
4892        // canonical-form gate at this layer surfaces a self-locating
4893        // diagnostic naming the offending Duration verbatim rather
4894        // than a downstream `RestartWindowZero` whose remediation
4895        // points at omitting the slot.
4896        let s = SupervisorSpec {
4897            restart_window: Some(Duration::from_nanos(1)),
4898            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4899            ..SupervisorSpec::default()
4900        };
4901        match s.validate().unwrap_err() {
4902            SupervisorError::RestartWindowNotCanonical { window } => {
4903                assert_eq!(window, Duration::from_nanos(1));
4904            }
4905            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4906        }
4907    }
4908
4909    #[test]
4910    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
4911        // The 1-ns-past-1ms boundary case: a `Duration` carrying
4912        // 1_000_001 ns is structurally past the integer-ms granularity
4913        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
4914        // trip would truncate to `1ms` and the consumer would observe
4915        // a 1-ns drift on every emit. Same boundary the peer
4916        // `validate_rejects_nanosecond_past_canonical_boundary` test
4917        // in limits.rs pins for the `:limits :wall-clock` axis.
4918        let w = Duration::from_nanos(1_000_001);
4919        let s = SupervisorSpec {
4920            restart_window: Some(w),
4921            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4922            ..SupervisorSpec::default()
4923        };
4924        assert_eq!(
4925            s.validate().unwrap_err(),
4926            SupervisorError::RestartWindowNotCanonical { window: w }
4927        );
4928    }
4929
4930    #[test]
4931    fn validate_accepts_integer_millisecond_restart_window_values() {
4932        // The positive-control sweep: every `Duration` the shared
4933        // codec can round-trip losslessly — the canonical
4934        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
4935        // pair emits and accepts — passes `validate` without
4936        // surfacing the new canonical-form arm. Mirrors
4937        // `validate_accepts_integer_millisecond_wall_clock_values` on
4938        // the sibling `:limits :wall-clock` axis.
4939        for w in [
4940            Duration::from_millis(1),
4941            Duration::from_millis(500),
4942            Duration::from_millis(1500),
4943            Duration::from_secs(1),
4944            Duration::from_secs(30),
4945            Duration::from_secs(60),
4946            Duration::from_secs(120),
4947            Duration::from_secs(3600),
4948        ] {
4949            let s = SupervisorSpec {
4950                restart_window: Some(w),
4951                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4952                ..SupervisorSpec::default()
4953            };
4954            s.validate()
4955                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
4956        }
4957    }
4958
4959    #[test]
4960    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
4961        // Cross-arm ordering pin: `Duration::ZERO` has
4962        // `subsec_nanos() == 0` and would otherwise pass the
4963        // canonical-form arm — the zero-floor arm must fire first so
4964        // the more self-locating `RestartWindowZero` diagnostic (with
4965        // its omit-axis remediation directly named) leads. Same
4966        // posture every peer zero-then-shape gate uses
4967        // (`WallClockZero` → `WallClockNotCanonical`,
4968        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
4969        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
4970        let s = SupervisorSpec {
4971            restart_window: Some(Duration::ZERO),
4972            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4973            ..SupervisorSpec::default()
4974        };
4975        assert_eq!(
4976            s.validate().unwrap_err(),
4977            SupervisorError::RestartWindowZero
4978        );
4979    }
4980
4981    #[test]
4982    fn restart_window_canonical_diagnostic_carries_offending_duration() {
4983        // Diagnostic-shape pin: the canonical-form arm names the
4984        // offending `Duration` verbatim so the author's grep lands on
4985        // the field's value, not a generic "duration not canonical"
4986        // message. Same shape every other typed-canonical-form arm
4987        // on this surface carries (`WallClockNotCanonical` carries
4988        // the offending `Duration` verbatim,
4989        // `PolicyTimeoutNotCanonical` carries the offending
4990        // `Duration` verbatim).
4991        let w = Duration::from_micros(500);
4992        let s = SupervisorSpec {
4993            restart_window: Some(w),
4994            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4995            ..SupervisorSpec::default()
4996        };
4997        let err = s.validate().unwrap_err();
4998        let msg = err.to_string();
4999        assert!(
5000            msg.contains("500"),
5001            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
5002        );
5003        assert!(
5004            msg.contains("sub-millisecond"),
5005            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
5006        );
5007    }
5008
5009    #[test]
5010    fn restart_window_validated_value_round_trips_through_codec() {
5011        // The structural property the canonical-ms gate enforces:
5012        // every `SupervisorSpec::restart_window` past
5013        // `SupervisorSpec::validate` round-trips losslessly through
5014        // the shared duration codec (serialize → string →
5015        // deserialize → equal value). Pin this end-to-end so a future
5016        // change to either side (the validate gate's accepted
5017        // granularity, the codec's parse/render unit set) that breaks
5018        // the alignment surfaces here. Peer of
5019        // `wall_clock_validated_value_round_trips_through_codec` on
5020        // the sibling `:limits :wall-clock` axis.
5021        for w in [
5022            Duration::from_millis(1),
5023            Duration::from_millis(1500),
5024            Duration::from_secs(30),
5025            Duration::from_secs(3600),
5026        ] {
5027            let s = SupervisorSpec {
5028                restart_window: Some(w),
5029                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5030                ..SupervisorSpec::default()
5031            };
5032            s.validate().unwrap();
5033            let json = serde_json::to_string(&s).unwrap();
5034            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5035            assert_eq!(back.restart_window, Some(w));
5036        }
5037    }
5038
5039    // ── value-shape: upper cap on :restart-window ─────────────────────────
5040    //
5041    // The fourth (and last) typed-`Duration` axis in caixa-core to get
5042    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
5043    // `:politicas :timeout` (2e8ee7e), and `:politicas
5044    // :circuit-breaker :window` (379a814). Brackets the typed
5045    // `:restart-window` axis structurally: every validated value lies
5046    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
5047    // granularity, closing the
5048    // rolling-window-degenerates-to-lifetime-counter footgun the prior
5049    // zero-floor-and-canonical-form-only checks left open.
5050
5051    #[test]
5052    fn validate_rejects_restart_window_above_cap() {
5053        // The fail-before-pass-after pin: 3601s = 1h + 1s is
5054        // structurally one canonical-tick past the
5055        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
5056        // integer-millisecond magnitude the canonical-form arm above
5057        // accepts cleanly, that the shared duration codec round-trips
5058        // losslessly as `"3601s"`, and that silently passed validate on
5059        // every pre-gate codebase because the typed slot's only checks
5060        // were the zero-floor and canonical-form arms. The runtime
5061        // substrate consuming the value (Erlang/OTP's MaxIntensity/
5062        // Period reconciler, the future wasm-operator's per-supervisor
5063        // restart-intensity counter) reaches for a `Duration` so long
5064        // no realistic restart-recovery pattern resets the counter,
5065        // far from the source caixa.lisp.
5066        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5067        let s = SupervisorSpec {
5068            restart_window: Some(w),
5069            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5070            ..SupervisorSpec::default()
5071        };
5072        assert_eq!(
5073            s.validate().unwrap_err(),
5074            SupervisorError::RestartWindowExceedsCap { window: w }
5075        );
5076    }
5077
5078    #[test]
5079    fn validate_rejects_restart_window_one_millisecond_above_cap() {
5080        // Boundary case: exactly 1ms past the cap (the granularity the
5081        // canonical-form gate enforces). Catches a future "strictly
5082        // less than" half-measure and pins the diagnostic to name the
5083        // offending `Duration` verbatim. Peer of
5084        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
5085        // `rejects_policy_timeout_one_millisecond_above_cap` /
5086        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
5087        // on the sibling typed-`Duration` axes' top edges.
5088        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
5089        let s = SupervisorSpec {
5090            restart_window: Some(w),
5091            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5092            ..SupervisorSpec::default()
5093        };
5094        assert_eq!(
5095            s.validate().unwrap_err(),
5096            SupervisorError::RestartWindowExceedsCap { window: w }
5097        );
5098    }
5099
5100    #[test]
5101    fn validate_rejects_restart_window_far_above_cap() {
5102        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
5103        // `(:restart-window "7d")`, or any "I want a lifetime counter
5104        // but wrote a `<integer>h` magnitude anyway" typo — values the
5105        // canonical-form arm accepts as integer-millisecond magnitudes,
5106        // the codec round-trips losslessly through serde, but the
5107        // operator's `MaxIntensity / Period` reconciler cannot honor
5108        // as a meaningful rolling window. Until this gate landed
5109        // validate accepted them. Pin the common above-cap values (24h,
5110        // 7d, ~11.5d) so a future relaxation that drops the upper bound
5111        // surfaces here.
5112        for w in [
5113            Duration::from_secs(86_400),    // 24h
5114            Duration::from_secs(604_800),   // 7d
5115            Duration::from_secs(1_000_000), // ~11.5 days
5116        ] {
5117            let s = SupervisorSpec {
5118                restart_window: Some(w),
5119                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5120                ..SupervisorSpec::default()
5121            };
5122            assert_eq!(
5123                s.validate().unwrap_err(),
5124                SupervisorError::RestartWindowExceedsCap { window: w }
5125            );
5126        }
5127    }
5128
5129    #[test]
5130    fn validate_accepts_restart_window_at_cap() {
5131        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
5132        // (1h) — must validate. The cap is inclusive on the top edge,
5133        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
5134        // [`crate::POLICY_TIMEOUT_MAX`] /
5135        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
5136        // capped axes. Pin the boundary explicitly so a future
5137        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
5138        // instead of `>`) surfaces here as a test failure rather than a
5139        // silent contract narrowing.
5140        let s = SupervisorSpec {
5141            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5142            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5143            ..SupervisorSpec::default()
5144        };
5145        s.validate()
5146            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
5147    }
5148
5149    #[test]
5150    fn validate_accepts_restart_window_typical_values() {
5151        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
5152        // per-supervisor production-playbook band positive-control
5153        // sweep — every value Learn You Some Erlang's `{intensity, 5,
5154        // 60}` worker-supervisor `Period = 60s` default, Elixir's
5155        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
5156        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
5157        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
5158        // default recommend (5s..=300s) must pass, plus a sweep
5159        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
5160        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
5161        // on the sibling `:limits :wall-clock` axis.
5162        for w in [
5163            Duration::from_millis(1),
5164            Duration::from_millis(500),
5165            Duration::from_secs(1),
5166            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
5167            Duration::from_secs(10), // Riak Core lower
5168            Duration::from_secs(30),
5169            Duration::from_secs(60),  // Learn You Some Erlang default
5170            Duration::from_secs(120), // OTP supervisor MaxT typical
5171            Duration::from_secs(300), // Riak Core upper
5172            Duration::from_secs(900), // 15m
5173            Duration::from_secs(1800),
5174            Duration::from_secs(3600), // exactly 1h, the cap
5175        ] {
5176            let s = SupervisorSpec {
5177                restart_window: Some(w),
5178                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5179                ..SupervisorSpec::default()
5180            };
5181            s.validate()
5182                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
5183        }
5184    }
5185
5186    #[test]
5187    fn restart_window_zero_takes_precedence_over_cap() {
5188        // The cross-arm ordering pin: `Duration::ZERO` is structurally
5189        // outside both `>= 1ms` (zero-floor) and `<=
5190        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
5191        // diagnostic is the more self-locating one (it directly names
5192        // the omit-axis remediation), so the validate gate must fire
5193        // on zero first. Same shape every other zero-then-cap ordering
5194        // on this surface uses (`WallClockZero` then
5195        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
5196        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
5197        // `PolicyBreakerWindowExceedsCap`).
5198        let s = SupervisorSpec {
5199            restart_window: Some(Duration::ZERO),
5200            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5201            ..SupervisorSpec::default()
5202        };
5203        assert_eq!(
5204            s.validate().unwrap_err(),
5205            SupervisorError::RestartWindowZero,
5206            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
5207        );
5208    }
5209
5210    #[test]
5211    fn restart_window_canonical_takes_precedence_over_cap() {
5212        // The cross-arm ordering pin: a `Duration` that is *both*
5213        // sub-millisecond (non-canonical-form) and structurally above
5214        // the cap surfaces the canonical-form diagnostic first,
5215        // because the round-trip-shape break is the more fundamental
5216        // issue (the value can't even round-trip through the codec,
5217        // so the cap diagnostic naming `1ms..=1h` would be misleading
5218        // — there's no integer-ms form of the offending value). Pin
5219        // the order so a future refactor that reorders the arms
5220        // surfaces here as a test failure rather than a silent
5221        // diagnostic regression. Peer of
5222        // `wall_clock_canonical_takes_precedence_over_cap` /
5223        // `policy_timeout_canonical_takes_precedence_over_cap`.
5224        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
5225        let s = SupervisorSpec {
5226            restart_window: Some(w),
5227            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5228            ..SupervisorSpec::default()
5229        };
5230        assert_eq!(
5231            s.validate().unwrap_err(),
5232            SupervisorError::RestartWindowNotCanonical { window: w },
5233            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
5234        );
5235    }
5236
5237    #[test]
5238    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
5239        // The cross-arm ordering pin between the `:max-restarts` cap
5240        // and the sibling `:restart-window` cap. A supervisor carrying
5241        // both an over-cap `max_restarts` AND an over-cap window must
5242        // surface the `MaxRestartsExceedsCap` diagnostic first — the
5243        // cap arm is wired immediately after the zero-restart arm and
5244        // strictly before every window-axis arm (zero / canonical /
5245        // cap), so the offending value the diagnostic names matches
5246        // the order the author would discover the gates by reading
5247        // top-to-bottom through `SupervisorSpec::validate`. Pin the
5248        // order so a future refactor that reorders the arms surfaces
5249        // here as a test failure rather than a silent diagnostic
5250        // regression. Peer of
5251        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
5252        // on the sibling zero / canonical window arms.
5253        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5254        let s = SupervisorSpec {
5255            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5256            restart_window: Some(w),
5257            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5258            ..SupervisorSpec::default()
5259        };
5260        assert_eq!(
5261            s.validate().unwrap_err(),
5262            SupervisorError::MaxRestartsExceedsCap {
5263                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5264            },
5265            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5266        );
5267    }
5268
5269    #[test]
5270    fn restart_window_cap_diagnostic_carries_offending_value() {
5271        // The diagnostic-shape pin: the offending `Duration` is
5272        // carried verbatim into the
5273        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
5274        // surfaced error message names the value the author wrote,
5275        // not just the cap. Same self-locating diagnostic shape every
5276        // other typed-cap arm on this surface carries
5277        // (`WallClockExceedsCap` carries the offending `Duration`
5278        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
5279        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
5280        // the offending `Duration` verbatim).
5281        let w = Duration::from_secs(7200); // 2h
5282        let s = SupervisorSpec {
5283            restart_window: Some(w),
5284            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5285            ..SupervisorSpec::default()
5286        };
5287        let err = s.validate().unwrap_err();
5288        assert!(
5289            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
5290            "got {err:?}"
5291        );
5292        let msg = err.to_string();
5293        assert!(
5294            msg.contains("7200"),
5295            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
5296        );
5297    }
5298
5299    #[test]
5300    fn supervisor_restart_window_cap_pins_canonical_value() {
5301        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
5302        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
5303        // shared duration codec emits as a clean canonical string
5304        // (`"<n>h"`). Pinning the literal value here surfaces a future
5305        // drift (a relaxation to 24h, a tightening to 5m) as a
5306        // deliberate test edit, not a silent contract narrowing.
5307        //
5308        // The four typed-`Duration` caps on the validation surface
5309        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
5310        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
5311        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
5312        // single uniform top edge at the codec's largest emitted unit
5313        // — a structural-property invariant the equality assertions
5314        // here enshrine, so a future drift on any of the four
5315        // surfaces as a deliberate test edit. Same shape every other
5316        // typed-cap value pin uses
5317        // (`wall_clock_cap_pins_canonical_value`,
5318        // `policy_timeout_cap_pins_canonical_value`,
5319        // `circuit_breaker_window_cap_pins_canonical_value`).
5320        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
5321        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
5322        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
5323        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
5324        assert_eq!(
5325            SUPERVISOR_RESTART_WINDOW_MAX,
5326            crate::POLICY_BREAKER_WINDOW_MAX
5327        );
5328    }
5329
5330    #[test]
5331    fn restart_window_cap_value_round_trips_through_codec() {
5332        // The codec round-trip property the cap arm preserves: the
5333        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
5334        // through the shared duration codec — every value at the cap
5335        // serializes to the canonical `"1h"` form and parses back
5336        // identically. Pin the round-trip so a future change to the
5337        // codec's unit set or to the cap's magnitude that breaks the
5338        // round-trip property surfaces here. Peer of
5339        // `wall_clock_cap_value_round_trips_through_codec` on the
5340        // sibling `:limits :wall-clock` axis.
5341        let s = SupervisorSpec {
5342            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5343            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5344            ..SupervisorSpec::default()
5345        };
5346        s.validate().unwrap();
5347        let json = serde_json::to_string(&s).unwrap();
5348        assert!(
5349            json.contains("\"1h\""),
5350            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
5351        );
5352        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5353        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
5354    }
5355
5356    #[test]
5357    fn validate_rejects_duplicate_child_caixa() {
5358        // Two children with the same :caixa render to two ComputeUnits
5359        // with the same name in the cluster's HelmRelease values —
5360        // one silently overwrites the other. Erlang/OTP's child_spec.id
5361        // is required-unique per supervisor; same set-not-multiset
5362        // discipline applied here as for :membros / :placement
5363        // :clusters / :entrada :paths.
5364        let s = SupervisorSpec {
5365            children: vec![
5366                child("worker", "^0.1", RestartPolicy::Permanent),
5367                child("cache", "^0.1", RestartPolicy::Transient),
5368                child("worker", "^0.2", RestartPolicy::Permanent),
5369            ],
5370            ..SupervisorSpec::default()
5371        };
5372        let err = s.validate().unwrap_err();
5373        assert!(
5374            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
5375            "got {err:?}"
5376        );
5377    }
5378
5379    #[test]
5380    fn validate_duplicate_child_diagnostic_names_first_collision() {
5381        // Iteration walks the :children list in declaration order —
5382        // the diagnostic names the first repeat, deterministically,
5383        // even when multiple names duplicate.
5384        let s = SupervisorSpec {
5385            children: vec![
5386                child("a", "^0.1", RestartPolicy::Permanent),
5387                child("b", "^0.1", RestartPolicy::Permanent),
5388                child("a", "^0.1", RestartPolicy::Permanent),
5389                child("b", "^0.1", RestartPolicy::Permanent),
5390            ],
5391            ..SupervisorSpec::default()
5392        };
5393        let err = s.validate().unwrap_err();
5394        assert!(
5395            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
5396            "got {err:?}"
5397        );
5398    }
5399
5400    // ── self-supervision cross-slot gate ──────────────────────────
5401
5402    #[test]
5403    fn validate_no_self_supervision_rejects_self_referential_child() {
5404        // A supervisor whose `:children` lists its own `:nome` is a
5405        // one-node reconciliation cycle — rejected, naming the parent.
5406        let children = vec![
5407            child("worker", "^0.1", RestartPolicy::Permanent),
5408            child("orquestra", "^0.1", RestartPolicy::Permanent),
5409        ];
5410        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
5411        assert!(
5412            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
5413            "got {err:?}"
5414        );
5415    }
5416
5417    #[test]
5418    fn validate_no_self_supervision_accepts_distinct_children() {
5419        // Positive control: distinct child names (including a child that
5420        // is itself a supervisor — nested trees are valid OTP) pass.
5421        let children = vec![
5422            child("worker", "^0.1", RestartPolicy::Permanent),
5423            child("sub-tree", "^0.1", RestartPolicy::Permanent),
5424        ];
5425        validate_no_self_supervision(&children, "orquestra").unwrap();
5426    }
5427
5428    #[test]
5429    fn validate_no_self_supervision_empty_children_is_ok() {
5430        // SimpleOneForOne / no-static-children supervisors have nothing
5431        // to self-reference — the gate is vacuously satisfied.
5432        validate_no_self_supervision(&[], "orquestra").unwrap();
5433    }
5434
5435    #[test]
5436    fn validate_simple_one_for_one_skips_uniqueness_check() {
5437        // SimpleOneForOne supervisors carry no static children — the
5438        // duplicate-child loop never runs. A zero-window declaration
5439        // on a SimpleOneForOne supervisor still trips the window check
5440        // (window applies to dynamic children too).
5441        let s = SupervisorSpec {
5442            estrategia: RestartStrategy::SimpleOneForOne,
5443            restart_window: None,
5444            children: vec![],
5445            ..SupervisorSpec::default()
5446        };
5447        s.validate().unwrap();
5448        let s_zero = SupervisorSpec {
5449            estrategia: RestartStrategy::SimpleOneForOne,
5450            restart_window: Some(Duration::ZERO),
5451            children: vec![],
5452            ..SupervisorSpec::default()
5453        };
5454        assert_eq!(
5455            s_zero.validate().unwrap_err(),
5456            SupervisorError::RestartWindowZero
5457        );
5458    }
5459
5460    #[test]
5461    fn validate_zero_window_runs_after_max_restarts_check() {
5462        // Pin the order: max_restarts == 0 fires before
5463        // restart_window == 0s, so an author with both wrong sees the
5464        // counter-axis diagnostic first (matches the order in the
5465        // struct and in the doc comment).
5466        let s = SupervisorSpec {
5467            max_restarts: 0,
5468            restart_window: Some(Duration::ZERO),
5469            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5470            ..SupervisorSpec::default()
5471        };
5472        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5473    }
5474
5475    #[test]
5476    fn round_trip_all_strategies() {
5477        for &strat in RestartStrategy::ALL {
5478            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
5479            // shape partition through the [`gen_platform::IsVariant`]
5480            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
5481            // predicate rather than the raw
5482            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
5483            // open-coded pattern-match — same closed-set-typed-enum
5484            // arm-discriminator dispatch discipline the sibling
5485            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
5486            // (915a934) extended onto its two paired positive / negated
5487            // `matches!` filter sites, and the sibling
5488            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
5489            // predicate convergence (766ec63) extended onto the M3 mesh-
5490            // slot per-`:placement` distribution-strategy `matches!`
5491            // discriminator axis. See the sibling
5492            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
5493            // fixture and the peer `manifest::tests::
5494            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
5495            // fixture — all three sites (the last unlifted
5496            // `matches!`-based arm-discriminator axis on the OTP-shape
5497            // supervisor sibling-restart-strategy closed-set typed enum,
5498            // acknowledged in 915a934's Prior-commits footnote as the
5499            // outstanding follow-up) now consult one typed dispatch on
5500            // the substrate primitive.
5501            let s = SupervisorSpec {
5502                estrategia: strat,
5503                children: if strat.is_simple_one_for_one() {
5504                    vec![]
5505                } else {
5506                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
5507                },
5508                ..SupervisorSpec::default()
5509            };
5510            let json = serde_json::to_string(&s).unwrap();
5511            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5512            assert_eq!(s, back);
5513        }
5514    }
5515
5516    #[test]
5517    fn round_trip_all_restart_policies() {
5518        for policy in [
5519            RestartPolicy::Permanent,
5520            RestartPolicy::Temporary,
5521            RestartPolicy::Transient,
5522        ] {
5523            let c = child("w", "^0.1", policy);
5524            let json = serde_json::to_string(&c).unwrap();
5525            let back: ChildSpec = serde_json::from_str(&json).unwrap();
5526            assert_eq!(c, back);
5527        }
5528    }
5529
5530    #[test]
5531    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
5532        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
5533        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
5534        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
5535        // is the only variant that satisfies `.is_simple_one_for_one()`;
5536        // every static-children-bearing arm (`OneForOne` / `OneForAll`
5537        // / `RestForOne`) returns `false`. This pin makes the partition
5538        // invariant load-bearing at caixa-core test time so a future
5539        // derive regression (a hole that returns `false` for
5540        // `SimpleOneForOne` too, or a byte-collision that flips a second
5541        // variant to `true`) trips here rather than laundering the arm
5542        // at the three test-fixture builder sites (a hole flips the
5543        // `SimpleOneForOne` fixture to carry a non-empty children list
5544        // and the subsequent `SupervisorSpec::validate` would refuse the
5545        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
5546        // a collision flips a peer strategy's fixture to carry an empty
5547        // children list and the subsequent `validate` would refuse with
5548        // [`SupervisorError::NoChildren`] — either way, the pin fires
5549        // here, at the derive site, rather than at the fixture-refusal
5550        // site far away). Peer of the sibling
5551        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
5552        // (915a934) pin on the M2 OTP-appup axis and the sibling
5553        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
5554        // pin on the M0 `:kind` axis.
5555        let cases: &[(RestartStrategy, bool)] = &[
5556            (RestartStrategy::OneForOne, false),
5557            (RestartStrategy::OneForAll, false),
5558            (RestartStrategy::RestForOne, false),
5559            (RestartStrategy::SimpleOneForOne, true),
5560        ];
5561        for (variant, expected) in cases {
5562            assert_eq!(
5563                variant.is_simple_one_for_one(),
5564                *expected,
5565                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
5566                 return {expected} (partition invariant on the \
5567                 IsVariant-derived arm-discriminator predicate — every \
5568                 test-fixture site that partitions the `:children` slot \
5569                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
5570                 off this typed dispatch, so a derive regression must \
5571                 surface here rather than at the fixture-refusal site)"
5572            );
5573        }
5574    }
5575
5576    #[test]
5577    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
5578        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
5579        // fixture-shape partition against the pre-lift
5580        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
5581        // pattern-match every test-fixture builder site previously
5582        // coupled to inline. Asserts the two projections agree byte-for-
5583        // byte on every arm of the enum, so a future derive regression
5584        // that flipped either predicate's arm-set would surface here at
5585        // caixa-core test time rather than at the three fixture-builder
5586        // sites (`supervisor::tests::round_trip_all_strategies`,
5587        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
5588        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
5589        // far from the derive site. Same peer-shape byte-identity pin
5590        // every sibling `IsVariant`-derive-routed convergence carries on
5591        // the substrate's closed-set typed-enum surface (peer of
5592        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
5593        // on the M2 OTP-appup axis).
5594        for &strat in RestartStrategy::ALL {
5595            let via_predicate = strat.is_simple_one_for_one();
5596            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
5597            assert_eq!(
5598                via_predicate, via_matches,
5599                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
5600                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
5601                 the pre-lift open-coded pattern and the \
5602                 IsVariant-derived predicate are the same axis, \
5603                 one typed dispatch"
5604            );
5605        }
5606    }
5607
5608    #[test]
5609    fn duration_codec_round_trip_canonical_units() {
5610        // Note the canonical-form rule: durations serialize to the
5611        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
5612        // "60s" — but the round-trip preserves the underlying Duration.
5613        let cases = [
5614            ("30s", Duration::from_secs(30)),
5615            ("5m", Duration::from_secs(300)),
5616            ("1h", Duration::from_secs(3600)),
5617            ("500ms", Duration::from_millis(500)),
5618        ];
5619        for (lit, dur) in cases {
5620            let s = SupervisorSpec {
5621                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5622                restart_window: Some(dur),
5623                ..SupervisorSpec::default()
5624            };
5625            let json = serde_json::to_string(&s).unwrap();
5626            assert!(
5627                json.contains(&format!("\"{lit}\"")),
5628                "expected \"{lit}\" in {json}"
5629            );
5630            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5631            assert_eq!(back.restart_window, Some(dur));
5632        }
5633    }
5634
5635    #[test]
5636    fn duration_canonicalizes_to_largest_unit() {
5637        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
5638        // typed Duration still equals 60s on the way back.
5639        let s = SupervisorSpec {
5640            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5641            restart_window: Some(Duration::from_secs(60)),
5642            ..SupervisorSpec::default()
5643        };
5644        let json = serde_json::to_string(&s).unwrap();
5645        assert!(json.contains("\"1m\""), "{json}");
5646        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5647        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
5648    }
5649
5650    #[test]
5651    fn three_child_one_for_one_validates() {
5652        let s = SupervisorSpec {
5653            estrategia: RestartStrategy::OneForOne,
5654            max_restarts: 5,
5655            restart_window: Some(Duration::from_secs(60)),
5656            children: vec![
5657                child("worker", "^0.1", RestartPolicy::Permanent),
5658                child("cache", "^0.1", RestartPolicy::Transient),
5659                child("scratch", "^0.1", RestartPolicy::Temporary),
5660            ],
5661        };
5662        s.validate().unwrap();
5663    }
5664
5665    #[test]
5666    fn json_uses_pascal_case_for_strategy_and_policy() {
5667        // Variant names are PascalCase by default in serde, matching
5668        // tatara-lisp's enum convention (`:estrategia OneForOne`).
5669        let c = child("w", "^0.1", RestartPolicy::Permanent);
5670        let json = serde_json::to_string(&c).unwrap();
5671        assert!(json.contains("\"Permanent\""));
5672        assert!(!json.contains("\"permanent\""));
5673
5674        let s = SupervisorSpec {
5675            estrategia: RestartStrategy::OneForOne,
5676            children: vec![c],
5677            ..SupervisorSpec::default()
5678        };
5679        let json = serde_json::to_string(&s).unwrap();
5680        assert!(json.contains("\"estrategia\":\"OneForOne\""));
5681    }
5682
5683    // ── shared duration codec: integer-magnitude canonical-form gate ──
5684    //
5685    // The gate lifts the discipline `crate::limits::parse_duration`
5686    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
5687    // the shared codec backing the remaining three typed-duration
5688    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
5689    // `:politicas :circuit-breaker :window`. Every magnitude `render`
5690    // emits is a non-negative integer with no decimal point and no
5691    // leading sign, so the codec's accepted set must match for
5692    // serialize/deserialize to round-trip without canonical-form
5693    // drift.
5694
5695    #[test]
5696    fn parse_accepts_integer_canonical_units() {
5697        // Pin the happy-path: every canonical author shape `render`
5698        // ever emits parses to the same `Duration` value, so the
5699        // codec's accepted set is at least a superset of its emitted
5700        // set on the canonical-unit axis.
5701        for (lit, dur) in [
5702            ("30s", Duration::from_secs(30)),
5703            ("500ms", Duration::from_millis(500)),
5704            ("2m", Duration::from_secs(120)),
5705            ("1h", Duration::from_secs(3600)),
5706            ("0s", Duration::ZERO),
5707        ] {
5708            assert_eq!(
5709                duration_codec::parse(lit).unwrap(),
5710                dur,
5711                "parse({lit:?}) should be {dur:?}"
5712            );
5713        }
5714    }
5715
5716    #[test]
5717    fn parse_accepts_bare_integer_as_seconds() {
5718        // The `"s" | ""` arm: a bare integer with no unit is read as
5719        // seconds. Pin this so the unit-empty form keeps parsing (it
5720        // renders to `"<n>s"` on serialize — that's a unit-choice
5721        // drift the integer-magnitude gate does NOT close, matching
5722        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
5723        // the peer `:limits :memory` codec).
5724        assert_eq!(
5725            duration_codec::parse("30").unwrap(),
5726            Duration::from_secs(30)
5727        );
5728    }
5729
5730    #[test]
5731    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
5732        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
5733        // on first serialize — DRIFT. The integer-magnitude gate names
5734        // the offending `"1.5"` verbatim and points at the canonical
5735        // remediation `"1500ms"`.
5736        let err = duration_codec::parse("1.5s").unwrap_err();
5737        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
5738        assert!(
5739            err.contains("not a non-negative integer"),
5740            "missing canonical-form reason in {err:?}"
5741        );
5742        assert!(
5743            err.contains("\"1500ms\""),
5744            "missing canonical-form remediation in {err:?}"
5745        );
5746    }
5747
5748    #[test]
5749    fn parse_rejects_decimal_shaped_integer_seconds() {
5750        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
5751        // `1s` exactly, so the round-trip looks correct — but the
5752        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
5753        // decimal-shape-with-integer-value form so author intent is
5754        // never silently rewritten.
5755        let err = duration_codec::parse("1.0s").unwrap_err();
5756        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
5757        assert!(
5758            err.contains("not a non-negative integer"),
5759            "missing canonical-form reason in {err:?}"
5760        );
5761    }
5762
5763    #[test]
5764    fn parse_rejects_half_unit_minute() {
5765        // `"0.5m"` is the unit-fraction footgun — author writes a
5766        // human-readable half-minute, serde silently rewrites to
5767        // `"30s"` on next emit. The gate names the offending
5768        // magnitude `"0.5"` and points at the integer-in-smaller-unit
5769        // form.
5770        let err = duration_codec::parse("0.5m").unwrap_err();
5771        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
5772        assert!(
5773            err.contains("\"30s\""),
5774            "missing canonical-form remediation in {err:?}"
5775        );
5776    }
5777
5778    #[test]
5779    fn parse_rejects_leading_plus_sign() {
5780        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
5781        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
5782        // cleanly to 30s and round-tripped to `"30s"` on next emit
5783        // (DRIFT). The digit-only gate closes the leading-sign class
5784        // first; the diagnostic names `"+30"` verbatim.
5785        let err = duration_codec::parse("+30s").unwrap_err();
5786        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
5787        assert!(
5788            err.contains("not a non-negative integer"),
5789            "missing canonical-form reason in {err:?}"
5790        );
5791    }
5792
5793    #[test]
5794    fn parse_rejects_leading_minus_sign() {
5795        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
5796        // rejected with `"negative duration in \"-30s\""`. Under the
5797        // integer-magnitude gate the diagnostic is unified — `-30` is
5798        // non-digit-only, f64-numeric, and surfaces with the canonical-
5799        // form reason (no leading `+` / `-` sign) naming the offending
5800        // `"-30"` verbatim. Same diagnostic shape as every other
5801        // rejected non-integer magnitude.
5802        let err = duration_codec::parse("-30s").unwrap_err();
5803        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
5804        assert!(
5805            err.contains("not a non-negative integer"),
5806            "missing canonical-form reason in {err:?}"
5807        );
5808    }
5809
5810    #[test]
5811    fn parse_garbage_still_falls_through_to_bad_magnitude() {
5812        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
5813        // through to the narrower "bad duration magnitude" arm — the
5814        // canonical-form diagnostic is reserved for the parser-shape
5815        // footgun case, not the "not a number at all" case. Same
5816        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
5817        // the peer `:limits :memory` codec.
5818        let err = duration_codec::parse("--1s").unwrap_err();
5819        assert!(
5820            err.contains("bad duration magnitude"),
5821            "expected bad-magnitude wording in {err:?}"
5822        );
5823    }
5824
5825    #[test]
5826    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
5827        // The accepted set is now closed under `u64`-exact integer
5828        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
5829        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
5830        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
5831        // possible. Pin the integer-exact arms across the four unit
5832        // suffixes so a future refactor that reaches back for f64
5833        // (`from_secs_f64`, `mul_f64`) surfaces here.
5834        assert_eq!(
5835            duration_codec::parse("3600s").unwrap(),
5836            Duration::from_secs(3600)
5837        );
5838        assert_eq!(
5839            duration_codec::parse("60m").unwrap(),
5840            Duration::from_secs(3600)
5841        );
5842        assert_eq!(
5843            duration_codec::parse("1h").unwrap(),
5844            Duration::from_secs(3600)
5845        );
5846        assert_eq!(
5847            duration_codec::parse("999ms").unwrap(),
5848            Duration::from_millis(999)
5849        );
5850    }
5851
5852    #[test]
5853    fn restart_window_serde_rejects_fractional_seconds() {
5854        // The shared codec backs `SupervisorSpec::restart_window`
5855        // (`with = "duration_codec"`) — so the gate applies on serde
5856        // deserialize for the typed Supervisor slot. A
5857        // `{"restartWindow":"1.5s"}` payload that previously round-
5858        // tripped to a different canonical string on next serialize
5859        // is now refused at deserialize with the integer-magnitude
5860        // diagnostic.
5861        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5862            "restartWindow":"1.5s",
5863            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5864        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5865        let msg = err.to_string();
5866        assert!(
5867            msg.contains("not a non-negative integer"),
5868            "expected integer-magnitude diagnostic in {msg:?}"
5869        );
5870        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
5871    }
5872
5873    #[test]
5874    fn restart_window_serde_rejects_leading_plus() {
5875        // The `u64::from_str` leading-`+` permissiveness gap that
5876        // motivated the digit-only gate (the `f64`-side accepted
5877        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
5878        // is now closed on the shared codec — surfaces as a structured
5879        // diagnostic at the serde layer for every typed-duration slot.
5880        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5881            "restartWindow":"+30s",
5882            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5883        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5884        let msg = err.to_string();
5885        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
5886        assert!(
5887            msg.contains("not a non-negative integer"),
5888            "missing canonical-form reason in {msg:?}"
5889        );
5890    }
5891
5892    #[test]
5893    fn parse_rejects_leading_zero_magnitude() {
5894        // `"030s"` is digit-only, so the existing non-digit-only / sign
5895        // / fractional arm doesn't catch it — `u64::from_str("030")`
5896        // returns `Ok(30)`, so before this gate `"030s"` parsed to
5897        // `Duration::from_secs(30)` and round-tripped through `render`
5898        // to `"30s"` — a *different* canonical string on the next emit,
5899        // breaking the THEORY.md Part V render-determinism contract
5900        // exactly the way `"+30s"` did before the leading-`+` arm
5901        // landed. Peer with the `rate_limit_codec` leading-zero arm
5902        // (4f46830) on the same canonical-form-drift axis.
5903        let err = duration_codec::parse("030s").unwrap_err();
5904        assert!(
5905            err.contains("non-canonical leading zero"),
5906            "expected leading-zero diagnostic in {err:?}"
5907        );
5908        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5909        assert!(
5910            err.contains("\"30s\""),
5911            "missing canonical-form remediation in {err:?}"
5912        );
5913        assert!(
5914            err.contains("THEORY.md"),
5915            "missing render-determinism citation in {err:?}"
5916        );
5917    }
5918
5919    #[test]
5920    fn parse_rejects_multi_digit_zero_magnitude() {
5921        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
5922        // digit-only, parse losslessly to `Duration::ZERO`, but render
5923        // back to `"0s"` (the single-byte canonical form) on the next
5924        // emit. The leading-zero arm refuses the drift class at the
5925        // codec layer; the semantic-zero gate downstream
5926        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
5927        // the single-byte canonical form `"0s"` separately on the
5928        // typed-validate layer.
5929        let err = duration_codec::parse("00s").unwrap_err();
5930        assert!(
5931            err.contains("non-canonical leading zero"),
5932            "expected leading-zero diagnostic in {err:?}"
5933        );
5934        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
5935    }
5936
5937    #[test]
5938    fn parse_rejects_leading_zero_per_hour_window() {
5939        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
5940        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
5941        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
5942        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
5943        // `h` / bare-integer-as-seconds) inherits the same gate.
5944        let err = duration_codec::parse("01h").unwrap_err();
5945        assert!(
5946            err.contains("non-canonical leading zero"),
5947            "expected leading-zero diagnostic in {err:?}"
5948        );
5949        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
5950    }
5951
5952    #[test]
5953    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
5954        // The `parse_accepts_bare_integer_as_seconds` happy-path
5955        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
5956        // multi-byte starts-with-`0`, parses losslessly to
5957        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
5958        // bare-integer surface accepts permissive unit-empty
5959        // shorthand but still must reject leading-zero padding.
5960        let err = duration_codec::parse("030").unwrap_err();
5961        assert!(
5962            err.contains("non-canonical leading zero"),
5963            "expected leading-zero diagnostic in {err:?}"
5964        );
5965        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5966    }
5967
5968    #[test]
5969    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
5970        // The codec-layer / typed-validate-layer boundary: `"0s"` /
5971        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
5972        // each round-trips losslessly through `render`
5973        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
5974        // accepts them. The downstream semantic-zero gates
5975        // (`SupervisorError::ZeroRestartWindow`,
5976        // `AplicacaoError::PolicyTimeoutZero`,
5977        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
5978        // zero-magnitude authoring at the typed-validate layer above,
5979        // peer with the `rate_limit_codec` codec-layer / typed-
5980        // validate-layer partition for `"0/s"`.
5981        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
5982        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
5983        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
5984    }
5985
5986    #[test]
5987    fn parse_accepts_canonical_magnitude_with_leading_one() {
5988        // The complementary boundary: a future tightening cannot
5989        // drift into rejecting valid canonical magnitudes that
5990        // happen to start with `1` (or any digit `[1-9]`). Pin
5991        // every canonical-unit suffix so the leading-zero arm
5992        // remains strictly narrower than the digit-only arm.
5993        assert_eq!(
5994            duration_codec::parse("100ms").unwrap(),
5995            Duration::from_millis(100)
5996        );
5997        assert_eq!(
5998            duration_codec::parse("100s").unwrap(),
5999            Duration::from_secs(100)
6000        );
6001        assert_eq!(
6002            duration_codec::parse("10m").unwrap(),
6003            Duration::from_secs(600)
6004        );
6005        assert_eq!(
6006            duration_codec::parse("10h").unwrap(),
6007            Duration::from_secs(36_000)
6008        );
6009    }
6010
6011    #[test]
6012    fn restart_window_serde_rejects_leading_zero() {
6013        // The shared codec backs `SupervisorSpec::restart_window`
6014        // (`with = "duration_codec"`) — so the leading-zero arm
6015        // applies on serde deserialize for the typed Supervisor slot.
6016        // A `{"restartWindow":"030s"}` payload that previously round-
6017        // tripped to a different canonical string on next serialize
6018        // is now refused at deserialize with the leading-zero
6019        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
6020        // / `restart_window_serde_rejects_fractional_seconds` on the
6021        // same canonical-form-drift axis.
6022        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6023            "restartWindow":"030s",
6024            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6025        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6026        let msg = err.to_string();
6027        assert!(
6028            msg.contains("non-canonical leading zero"),
6029            "expected leading-zero diagnostic in {msg:?}"
6030        );
6031        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
6032    }
6033
6034    #[test]
6035    fn parse_rejects_leading_whitespace() {
6036        // `" 30s"` — the canonical paste-from-aligned-doc /
6037        // paste-from-YAML-quoted-plain-scalar footgun. Before this
6038        // gate the top-level `s.trim()` at parse entry silently ate
6039        // the leading space and parsed the value to
6040        // `Duration::from_secs(30)`, which then round-tripped through
6041        // `render` to `"30s"` (a *different* canonical string on the
6042        // next emit) — the exact canonical-form-drift class the
6043        // leading-`+` / leading-zero arms already close, extended
6044        // to the whitespace-byte class. Peer with the sibling
6045        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
6046        // the M3 `:politicas` axis.
6047        let err = duration_codec::parse(" 30s").unwrap_err();
6048        assert!(
6049            err.contains("contains whitespace byte"),
6050            "expected whitespace diagnostic in {err:?}"
6051        );
6052        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6053        assert!(
6054            err.contains("THEORY.md"),
6055            "missing render-determinism contract citation in {err:?}"
6056        );
6057    }
6058
6059    #[test]
6060    fn parse_rejects_trailing_whitespace() {
6061        // `"30s "` — the canonical shell-history / trailing-space
6062        // paste footgun. Before this gate the top-level `s.trim()`
6063        // silently ate the trailing space and parsed to
6064        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
6065        // next emit — same canonical-form drift as the leading-space
6066        // sibling, closed on the same whitespace-byte arm.
6067        let err = duration_codec::parse("30s ").unwrap_err();
6068        assert!(
6069            err.contains("contains whitespace byte"),
6070            "expected whitespace diagnostic in {err:?}"
6071        );
6072        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6073    }
6074
6075    #[test]
6076    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
6077        // `"30 s"` — the canonical typographically-spaced author
6078        // shape (the same idiom every prose reference to a duration
6079        // renders as, mistakenly retained when the value is pasted
6080        // into a codec-shaped slot). Before this gate the per-part
6081        // `num_part.trim()` / `unit.trim()` calls silently ate the
6082        // whitespace between the magnitude and the unit and parsed
6083        // the value to `Duration::from_secs(30)`, round-tripping to
6084        // `"30s"` — the codec's *internal* whitespace-tolerance
6085        // vector, orthogonal to the leading / trailing surface but
6086        // the same canonical-form-drift class. Pins the arm as
6087        // strictly stronger than the pre-existing top-level
6088        // `s.trim()` behavior: it fires on whitespace anywhere in
6089        // the value, not just at the string boundary.
6090        let err = duration_codec::parse("30 s").unwrap_err();
6091        assert!(
6092            err.contains("contains whitespace byte"),
6093            "expected whitespace diagnostic in {err:?}"
6094        );
6095        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6096    }
6097
6098    #[test]
6099    fn parse_rejects_tab_byte() {
6100        // `"\t30s"` — the canonical paste-from-indented-doc /
6101        // paste-from-YAML-block-scalar footgun where a tab byte leads
6102        // the magnitude. Pins that the gate covers tab (`0x09`) as
6103        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
6104        // members and both would be silently swallowed by `s.trim()`
6105        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
6106        // space alone to the full ASCII-whitespace set (space `0x20`,
6107        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
6108        // the tab arm as a representative of the non-space members.
6109        let err = duration_codec::parse("\t30s").unwrap_err();
6110        assert!(
6111            err.contains("contains whitespace byte"),
6112            "expected whitespace diagnostic in {err:?}"
6113        );
6114        assert!(
6115            err.contains("0x09"),
6116            "missing offending tab byte in {err:?}"
6117        );
6118    }
6119
6120    #[test]
6121    fn restart_window_serde_rejects_whitespace() {
6122        // The shared codec backs `SupervisorSpec::restart_window`
6123        // (`with = "duration_codec"`) — so the whitespace arm
6124        // applies on serde deserialize for the typed Supervisor slot.
6125        // A `{"restartWindow":" 30s"}` payload that previously round-
6126        // tripped to a different canonical string on next serialize
6127        // is now refused at deserialize with the whitespace-byte
6128        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
6129        // / `restart_window_serde_rejects_leading_plus` /
6130        // `restart_window_serde_rejects_fractional_seconds` on the
6131        // same canonical-form-drift axis.
6132        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6133            "restartWindow":" 30s",
6134            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6135        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6136        let msg = err.to_string();
6137        assert!(
6138            msg.contains("contains whitespace byte"),
6139            "expected whitespace diagnostic in {msg:?}"
6140        );
6141        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
6142    }
6143
6144    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
6145    //
6146    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
6147    // duration codec — closes the strictly-complementary class the
6148    // byte-scan cannot see, through the lifted
6149    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
6150    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
6151    // and `:politicas :circuit-breaker :window` simultaneously via
6152    // this shared codec.
6153
6154    #[test]
6155    fn duration_codec_parse_rejects_leading_nbsp() {
6156        // NBSP prefix — the strictly-complementary drift class the
6157        // ASCII byte-scan cannot see. `str::trim` strips it silently
6158        // and the value drifts to `"30s"` on next serialize.
6159        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
6160        assert!(
6161            err.contains("non-ASCII Unicode whitespace character"),
6162            "expected non-ASCII whitespace diagnostic in {err:?}"
6163        );
6164        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
6165    }
6166
6167    #[test]
6168    fn duration_codec_parse_rejects_trailing_line_separator() {
6169        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
6170        // footgun.
6171        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
6172        assert!(
6173            err.contains("non-ASCII Unicode whitespace character"),
6174            "expected non-ASCII whitespace diagnostic in {err:?}"
6175        );
6176        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
6177    }
6178
6179    #[test]
6180    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
6181        // Positive-control pin: every ASCII-only canonical form the
6182        // renderer emits stays accepted through the new arm.
6183        assert_eq!(
6184            duration_codec::parse("30s").unwrap(),
6185            Duration::from_secs(30)
6186        );
6187        assert_eq!(
6188            duration_codec::parse("500ms").unwrap(),
6189            Duration::from_millis(500)
6190        );
6191        assert_eq!(
6192            duration_codec::parse("1h").unwrap(),
6193            Duration::from_secs(3600)
6194        );
6195    }
6196
6197    #[test]
6198    fn restart_window_serde_rejects_non_ascii_whitespace() {
6199        // The shared codec backs `SupervisorSpec::restart_window` — so
6200        // the new non-ASCII Unicode whitespace arm applies on serde
6201        // deserialize for the typed Supervisor slot. A
6202        // `{"restartWindow":" 30s"}` payload that previously
6203        // survived the ASCII byte-scan (only ASCII whitespace was
6204        // refused) is now refused at deserialize with the
6205        // non-ASCII-whitespace-and-codepoint diagnostic.
6206        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
6207            \"restartWindow\":\"\u{00A0}30s\",\
6208            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
6209        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6210        let msg = err.to_string();
6211        assert!(
6212            msg.contains("non-ASCII Unicode whitespace character"),
6213            "expected non-ASCII whitespace diagnostic in {msg:?}"
6214        );
6215        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
6216    }
6217
6218    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
6219
6220    #[test]
6221    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
6222        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
6223        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
6224        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
6225        // name the exact camelCase JSON keys the
6226        // `#[serde(rename_all = "camelCase")]` attribute on
6227        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
6228        // field carries `Some(_)` / non-empty) and pin that each canonical
6229        // byte-sequence appears verbatim in the JSON — a future accidental
6230        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
6231        // name flip at the derive attribute (any of which would silently
6232        // break every downstream JSON consumer that reaches for one of the
6233        // four consts via `Value::get(...)`) surfaces here as a build-time
6234        // test failure at `supervisor.rs`, not as an apply-time
6235        // `.get(<stale-canonical-const>)` returning `None` far from the
6236        // derive-attr drift's commit. Peer with the sibling
6237        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
6238        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
6239        // M2 typed-slot family established, extended here to close the
6240        // top-level Supervisor axis.
6241        let spec = SupervisorSpec {
6242            estrategia: RestartStrategy::OneForOne,
6243            max_restarts: 5,
6244            restart_window: Some(Duration::from_secs(60)),
6245            children: vec![ChildSpec {
6246                caixa: "w".into(),
6247                versao: "^0.1".into(),
6248                restart: RestartPolicy::Permanent,
6249            }],
6250        };
6251        let json = serde_json::to_string(&spec).unwrap();
6252        for key in [
6253            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6254            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6255            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6256            crate::render::SUPERVISOR_KEY_CHILDREN,
6257        ] {
6258            let quoted = format!("\"{key}\"");
6259            assert!(
6260                json.contains(&quoted),
6261                "serialized SupervisorSpec must carry the lifted \
6262                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
6263                 the JSON emission (got: {json})",
6264            );
6265        }
6266    }
6267
6268    #[test]
6269    fn supervisor_key_consts_are_pairwise_distinct() {
6270        // Cross-axis drift-detection pin: a future collapse of two
6271        // canonical top-level byte-strings onto the same value (e.g. an
6272        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
6273        // also read `"estrategia"`) would silently reroute every
6274        // downstream probe on one axis onto the sibling axis's overlay
6275        // entry and pass every propagation-probe test that expected only
6276        // the stale axis's value. Peer of the sibling four-way distinct
6277        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
6278        let all = [
6279            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6280            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6281            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6282            crate::render::SUPERVISOR_KEY_CHILDREN,
6283        ];
6284        for (i, a) in all.iter().enumerate() {
6285            for b in all.iter().skip(i + 1) {
6286                assert_ne!(
6287                    a, b,
6288                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
6289                     canonical byte-sequences — got `{a}` == `{b}`",
6290                );
6291            }
6292        }
6293    }
6294
6295    #[test]
6296    fn supervisor_key_consts_are_lower_camel_case_shape() {
6297        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
6298        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6299        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6300        // capital, no whitespace / dots) — the canonical shape the
6301        // `#[serde(rename_all = "camelCase")]` derive produces on
6302        // `SupervisorSpec`. A future flip to a non-camelCase attribute
6303        // at the derive surfaces both here (this test fails on the
6304        // stale-constant shape) and at
6305        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6306        // (that test fails on the mismatch between const and derive).
6307        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
6308        // (d8b8b4f) on the sibling M2 `:limits` axis.
6309        for key in [
6310            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6311            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6312            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6313            crate::render::SUPERVISOR_KEY_CHILDREN,
6314        ] {
6315            assert!(
6316                !key.is_empty(),
6317                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
6318            );
6319            let first = key.chars().next().unwrap();
6320            assert!(
6321                first.is_ascii_lowercase(),
6322                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
6323                 (got {key:?}, leads with {first:?})",
6324            );
6325            assert!(
6326                key.chars().all(|c| c.is_ascii_alphanumeric()),
6327                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
6328                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6329            );
6330        }
6331    }
6332
6333    #[test]
6334    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
6335        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
6336        // (camelCase JSON keys, no leading colon) must never collide
6337        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
6338        // consts (kebab-case author-facing labels with leading colon)
6339        // that sit next to them at `caixa_core::render`. Both families
6340        // cover the same four typed Supervisor slots on two distinct
6341        // axes (author-side kebab vs renderer-side camelCase);
6342        // collapsing either family onto the other's byte-shape would
6343        // silently reroute the render-side probe onto the author-facing
6344        // surface, or vice versa. Peer of the byte-distinctness
6345        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
6346        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
6347        let pairs = [
6348            (
6349                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6350                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
6351            ),
6352            (
6353                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6354                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
6355            ),
6356            (
6357                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6358                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
6359            ),
6360            (
6361                crate::render::SUPERVISOR_KEY_CHILDREN,
6362                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
6363            ),
6364        ];
6365        for (json_key, author_key) in pairs {
6366            assert_ne!(
6367                json_key, author_key,
6368                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
6369                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
6370                 got JSON `{json_key}` == author `{author_key}`",
6371            );
6372        }
6373    }
6374
6375    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
6376
6377    #[test]
6378    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
6379        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
6380        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
6381        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
6382        // keys the `#[serde(rename_all = "camelCase")]` attribute on
6383        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
6384        // pin that each canonical byte-sequence appears verbatim in the
6385        // JSON — a future accidental `rename_all = "snake_case"` /
6386        // `"kebab-case"` / verbatim-field-name flip at the derive
6387        // attribute (any of which would silently break every downstream
6388        // JSON consumer that reaches for one of the three consts via
6389        // `Value::get(...)`) surfaces here as a build-time test failure at
6390        // `supervisor.rs`, not as an apply-time
6391        // `.get(<stale-canonical-const>)` returning `None` far from the
6392        // derive-attr drift's commit. Peer with the enclosing
6393        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6394        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
6395        // discipline the SupervisorSpec top-level lift established,
6396        // extended here to the sibling per-`:children` entry `ChildSpec`
6397        // derive so the last M2 typed-struct sub-block
6398        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
6399        // surface without a lifted serde-key peer joins the substrate's
6400        // "one canonical byte-string per typed serialized-key axis"
6401        // discipline.
6402        let c = ChildSpec {
6403            caixa: "worker".into(),
6404            versao: "^0.1".into(),
6405            restart: RestartPolicy::Permanent,
6406        };
6407        let json = serde_json::to_string(&c).unwrap();
6408        for key in [
6409            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6410            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6411            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6412        ] {
6413            let quoted = format!("\"{key}\"");
6414            assert!(
6415                json.contains(&quoted),
6416                "serialized ChildSpec must carry the lifted \
6417                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
6418                 in the JSON emission (got: {json})",
6419            );
6420        }
6421    }
6422
6423    #[test]
6424    fn supervisor_child_key_consts_are_pairwise_distinct() {
6425        // Cross-axis drift-detection pin: a future collapse of two
6426        // canonical `ChildSpec` per-entry byte-strings onto the same
6427        // value (e.g. an accidental copy-paste flip of
6428        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
6429        // silently reroute every downstream probe on one axis onto the
6430        // sibling axis's overlay entry and pass every propagation-probe
6431        // test that expected only the stale axis's value. Peer of the
6432        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
6433        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
6434        // pair (ce80ca0).
6435        let all = [
6436            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6437            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6438            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6439        ];
6440        for (i, a) in all.iter().enumerate() {
6441            for b in all.iter().skip(i + 1) {
6442                assert_ne!(
6443                    a, b,
6444                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
6445                     distinct canonical byte-sequences — got `{a}` == `{b}`",
6446                );
6447            }
6448        }
6449    }
6450
6451    #[test]
6452    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
6453        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
6454        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6455        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6456        // capital, no whitespace / dots) — the canonical shape the
6457        // `#[serde(rename_all = "camelCase")]` derive produces on
6458        // `ChildSpec`. A future flip to a non-camelCase attribute at the
6459        // derive surfaces both here (this test fails on the
6460        // stale-constant shape) and at
6461        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
6462        // (that test fails on the mismatch between const and derive).
6463        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
6464        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
6465        for key in [
6466            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6467            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6468            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6469        ] {
6470            assert!(
6471                !key.is_empty(),
6472                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
6473            );
6474            let first = key.chars().next().unwrap();
6475            assert!(
6476                first.is_ascii_lowercase(),
6477                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
6478                 byte (got {key:?}, leads with {first:?})",
6479            );
6480            assert!(
6481                key.chars().all(|c| c.is_ascii_alphanumeric()),
6482                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
6483                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6484            );
6485        }
6486    }
6487
6488    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
6489
6490    #[test]
6491    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
6492        // The fail-before-pass-after pin: pre-lift there was no
6493        // single-source binding between the [`RestartStrategy`] variant
6494        // name the un-`rename`d `Serialize` derive emits under
6495        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
6496        // every downstream cluster-side dispatcher (the future
6497        // wasm-operator's per-supervisor sibling-restart branch, the
6498        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
6499        // admission-time enum-arm bind, the `caixa-operator`'s
6500        // hierarchical reconciliation scheduler's per-strategy fan-out)
6501        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
6502        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
6503        // override, or a variant rename in the source — would silently
6504        // rebrand the emitted scalar under one spelling while every
6505        // downstream dispatcher still probed the other, with the failure
6506        // surfacing at the operator's reconcile posture (subtrees coming
6507        // up under the `default()` `OneForOne` arm rather than the typed
6508        // slot's declared strategy — a bad child would then only take
6509        // itself down instead of the sibling set the author intended, so
6510        // shared-state children fall out of sync) far from the source
6511        // rebrand commit and with no field naming the drift. Pinning the
6512        // two paths (the `Serialize` derive's serialized string AND the
6513        // [`RestartStrategy::as_str`] helper) to the same four lifted
6514        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
6515        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
6516        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
6517        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
6518        // byte-strings makes any future drift on either endpoint fail
6519        // here at caixa-core build time. Peer of the M3
6520        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
6521        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
6522        // three-path-convergence discipline, extended to close the
6523        // OTP-shaped per-supervisor sibling-restart axis.
6524        for (variant, expected) in [
6525            (
6526                RestartStrategy::OneForOne,
6527                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6528            ),
6529            (
6530                RestartStrategy::OneForAll,
6531                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6532            ),
6533            (
6534                RestartStrategy::RestForOne,
6535                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6536            ),
6537            (
6538                RestartStrategy::SimpleOneForOne,
6539                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6540            ),
6541        ] {
6542            let json = serde_json::to_string(&variant).unwrap();
6543            assert_eq!(
6544                json,
6545                format!("\"{expected}\""),
6546                "RestartStrategy::{variant:?} must serialize to {expected:?}"
6547            );
6548            assert_eq!(
6549                variant.as_str(),
6550                expected,
6551                "RestartStrategy::{variant:?}.as_str() must return the lifted \
6552                 SUPERVISOR_ESTRATEGIA_* constant"
6553            );
6554        }
6555    }
6556
6557    #[test]
6558    fn supervisor_estrategia_consts_are_pairwise_distinct() {
6559        // Cross-arm drift-detection pin: a future collapse of two
6560        // canonical variant byte-strings onto the same value (e.g. an
6561        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
6562        // to also read `"OneForOne"`) would silently reroute every
6563        // downstream operator's per-strategy dispatch onto the sibling
6564        // arm's reconcile branch and pass every propagation-probe test
6565        // that expected only the stale arm's value — the mis-strategied
6566        // subtree would come up with the wrong sibling-restart posture
6567        // on every subsequent failure. Peer of the sibling four-way
6568        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
6569        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
6570        let all = [
6571            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6572            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6573            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6574            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6575        ];
6576        for (i, a) in all.iter().enumerate() {
6577            for (j, b) in all.iter().enumerate() {
6578                if i != j {
6579                    assert_ne!(
6580                        a, b,
6581                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
6582                         — got duplicate {a:?} at indices {i} and {j}",
6583                    );
6584                }
6585            }
6586        }
6587    }
6588
6589    #[test]
6590    fn restart_strategy_display_routes_through_as_str_helper() {
6591        // The fail-before-pass-after pin on the first half of the
6592        // three-path convergence: pre-convergence the sibling
6593        // OTP-shape typed enum [`RestartStrategy`] carried a
6594        // [`std::fmt::Display`] surface via its
6595        // `#[discriminant(also_display)]` gen-platform derive route,
6596        // which arrived kebab-case as `"one-for-one"` /
6597        // `"one-for-all"` / `"rest-for-one"` /
6598        // `"simple-one-for-one"` while the wire format ran as
6599        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
6600        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
6601        // Every consumer reaching for a strategy byte-string past the
6602        // wire format had to pick between three paths
6603        // ([`RestartStrategy::as_str`], the `Serialize` derive's
6604        // serialized string, or `format!("{v}")` on the
6605        // discriminant-Display route), any two of which a future
6606        // variant rename or `#[serde(rename_all = "kebab-case")]`
6607        // attribute would silently desynchronize. Wiring
6608        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
6609        // closes the third path: every `format!("{v}")` call reaches
6610        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6611        // const the wire format and the [`RestartStrategy::as_str`]
6612        // helper already route through, so a future variant rename
6613        // lands at exactly one place. Pin the routing here so a future
6614        // `impl std::fmt::Display for RestartStrategy`
6615        // reimplementation that hand-rolls the arms instead of
6616        // delegating to [`RestartStrategy::as_str`] fails at
6617        // caixa-core build time. Peer of the M3
6618        // `placement_strategy_display_routes_through_as_str_helper`
6619        // (cc8f749) which the M3 axis converged first.
6620        for &variant in RestartStrategy::ALL {
6621            assert_eq!(
6622                variant.to_string(),
6623                variant.as_str(),
6624                "RestartStrategy::{variant:?} Display must route through \
6625                 RestartStrategy::as_str (single source of truth: the lifted \
6626                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
6627            );
6628        }
6629    }
6630
6631    #[test]
6632    fn restart_strategy_display_matches_serialized_wire_byte_string() {
6633        // The fail-before-pass-after pin on the second half of the
6634        // three-path convergence: `Display` (user-facing text) agrees
6635        // byte-for-byte with the `Serialize` derive's wire format
6636        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
6637        // scalar) on every variant. Pre-convergence the two paths
6638        // were structurally independent — a future
6639        // `#[serde(rename_all = "kebab-case")]` attribute on the
6640        // enum would silently rebrand the emitted wire scalar
6641        // (`one-for-one`, `one-for-all`, `rest-for-one`,
6642        // `simple-one-for-one`) while every consumer that
6643        // pretty-prints the strategy (the future wasm-operator's
6644        // per-supervisor sibling-restart-strategy diagnostic line,
6645        // the future `feira app graph` per-supervisor strategy line,
6646        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
6647        // materializer's admission-webhook rejection body) would
6648        // still emit the PascalCase form the `as_str` / `Display`
6649        // route returns, with the mismatch surfacing at consumer
6650        // parse time / operator dispatch time far from the source
6651        // rebrand commit. Pin the two paths byte-for-byte here so any
6652        // future serde-attribute or variant-rename drift is a
6653        // caixa-core-build-time test failure at this call, not a
6654        // silent per-consumer dispatch miss. Peer of the M3
6655        // `placement_strategy_display_matches_serialized_wire_byte_string`
6656        // (cc8f749) which the M3 axis converged first.
6657        for &variant in RestartStrategy::ALL {
6658            let wire = serde_json::to_string(&variant).unwrap();
6659            let unquoted = wire
6660                .strip_prefix('"')
6661                .and_then(|s| s.strip_suffix('"'))
6662                .expect("serialized RestartStrategy is a JSON string");
6663            assert_eq!(
6664                variant.to_string(),
6665                unquoted,
6666                "RestartStrategy::{variant:?} Display byte-string must match the \
6667                 Serialize derive's wire byte-string (three-path convergence: \
6668                 Display + as_str + Serialize all resolve to the same \
6669                 SUPERVISOR_ESTRATEGIA_* const)"
6670            );
6671        }
6672    }
6673
6674    #[test]
6675    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
6676        // Fail-before-pass-after byte-parity pin on the lifted
6677        // `impl AsRef<str> for RestartStrategy` — asserts the
6678        // standard-library trait impl and the substrate-primitive
6679        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
6680        // to the same `&str` per instance across the four-arm
6681        // closed set, so any future silent detour that routes the
6682        // impl through a divergent projection (a per-arm inline
6683        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
6684        // re-inlining that opens a compile-time link to the un-lifted
6685        // arm-literal, a swap onto the kebab-case
6686        // [`gen_platform::Discriminant`] catalog identity that would
6687        // collide the wire axis with the dispatcher-catalog axis) trips
6688        // at caixa-core test time under `PartialEq` rather than at a
6689        // downstream `impl AsRef<str>`-bound consumer's silent split.
6690        // Sweeps every one of the four arms
6691        // [`RestartStrategy::ALL`] carries so no arm's projection is
6692        // covered only by the sibling wire-format `Serialize` derive
6693        // path. Peer of the sibling
6694        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
6695        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
6696        // top-level `:versao` typed newtype — the two pins together
6697        // cover the substrate primitive's `AsRef<str>` projection axis
6698        // on the paired newtype + closed-set-typed-enum surface.
6699        for &variant in RestartStrategy::ALL {
6700            assert_eq!(
6701                <RestartStrategy as AsRef<str>>::as_ref(&variant),
6702                variant.as_str(),
6703                "AsRef<str> impl on RestartStrategy::{variant:?} must \
6704                 byte-equal RestartStrategy::as_str on the same instance \
6705                 — divergence signals a silent detour off the substrate-\
6706                 primitive accessor"
6707            );
6708        }
6709    }
6710
6711    #[test]
6712    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
6713        // Fail-before-pass-after byte-parity pin on the three-path
6714        // convergence discipline the M2 sibling-restart primitive now
6715        // carries on the `&str`-projection axis:
6716        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
6717        // lifted impl), `format!("{s}")` (the pre-existing
6718        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
6719        // primitive `pub const fn` accessor both trait impls delegate
6720        // through) must resolve to the same byte-string on every
6721        // instance across the four-arm closed set. Refuses any future
6722        // divergence between the two trait impls (a stray
6723        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
6724        // rather than delegating through the shared accessor; a
6725        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
6726        // literal cascade) that would silently split the two
6727        // projection paths of the same closed-set typed enum. Mirrors
6728        // the sibling three-path-convergence discipline the peer
6729        // [`crate::CaixaVersion`] typed newtype carries on its
6730        // `AsRef<str>` / `Display` / `as_str` triple
6731        // (version.rs pin
6732        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
6733        // 16d5c7e).
6734        for &variant in RestartStrategy::ALL {
6735            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
6736            let via_display: String = format!("{variant}");
6737            let via_accessor: &str = variant.as_str();
6738            assert_eq!(via_as_ref, via_accessor);
6739            assert_eq!(via_display, via_accessor);
6740            assert_eq!(via_as_ref, via_display.as_str());
6741        }
6742    }
6743
6744    #[test]
6745    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
6746        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
6747        // exhaustive-iteration surface: every variant appears exactly
6748        // once, and the slice length matches the arm count of the
6749        // closed set. Every consumer that walks the accepted-strategy
6750        // set (a future `feira supervisor --estrategia …` CLI-side
6751        // arg-parse's "did you mean" hint, a future M4 admission-
6752        // webhook's rejection body naming the accepted-`:estrategia`
6753        // list, the [`RestartStrategy::from_wire`] reverse-projection
6754        // consumers that iterate the accept-set for diagnostic
6755        // rendering) reads through this slice, so a future arm addition
6756        // that grows the enum but forgets to grow [`Self::ALL`]
6757        // silently truncates every downstream consumer's accept-set at
6758        // the same pre-addition boundary — this pin fails at caixa-core
6759        // build time on the pairwise-distinct + arm-count invariants.
6760        //
6761        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
6762        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
6763        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
6764        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6765        // pins on the peer closed-set typed-enum axes.
6766        let all: &[RestartStrategy] = RestartStrategy::ALL;
6767        assert_eq!(
6768            all.len(),
6769            4,
6770            "RestartStrategy::ALL must enumerate every variant of the \
6771             four-arm closed set (OneForOne, OneForAll, RestForOne, \
6772             SimpleOneForOne); got {all:?}"
6773        );
6774        for (i, a) in all.iter().enumerate() {
6775            for (j, b) in all.iter().enumerate() {
6776                if i != j {
6777                    assert_ne!(
6778                        a, b,
6779                        "RestartStrategy::ALL must carry every variant exactly \
6780                         once — got duplicate {a:?} at indices {i} and {j}"
6781                    );
6782                }
6783            }
6784        }
6785        for variant in [
6786            RestartStrategy::OneForOne,
6787            RestartStrategy::OneForAll,
6788            RestartStrategy::RestForOne,
6789            RestartStrategy::SimpleOneForOne,
6790        ] {
6791            assert!(
6792                all.contains(&variant),
6793                "RestartStrategy::ALL must contain {variant:?} — a future arm \
6794                 addition that grows the enum but forgets to grow the ALL slice \
6795                 silently truncates every downstream consumer's accept-set at \
6796                 the pre-addition boundary"
6797            );
6798        }
6799    }
6800
6801    #[test]
6802    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
6803        // Fail-before-pass-after pin on the forward accept-set of the
6804        // [`RestartStrategy::from_wire`] reverse projection: every
6805        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6806        // constant the [`RestartStrategy::as_str`] emitter walks parses
6807        // back to its paired variant. Any future arm addition that
6808        // grows the emitter's `as_str` match but forgets to grow the
6809        // parser's `from_wire` match silently splits the two halves of
6810        // the round-trip — the wire byte-string one non-serde consumer
6811        // parses from the one the emitter wrote — with the failure
6812        // surfacing at parse time far from the rebrand commit. Pinning
6813        // the four-arm accept-set here catches the drift at caixa-core
6814        // build time.
6815        //
6816        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
6817        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
6818        // accept-set pins on the peer closed-set typed-enum `str → Self`
6819        // axes.
6820        for (wire, expected) in [
6821            (
6822                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6823                RestartStrategy::OneForOne,
6824            ),
6825            (
6826                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6827                RestartStrategy::OneForAll,
6828            ),
6829            (
6830                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6831                RestartStrategy::RestForOne,
6832            ),
6833            (
6834                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6835                RestartStrategy::SimpleOneForOne,
6836            ),
6837        ] {
6838            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6839                panic!(
6840                    "RestartStrategy::from_wire({wire:?}) must accept every \
6841                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
6842                     lifted canonical byte-string that RestartStrategy::{expected:?} \
6843                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
6844                )
6845            });
6846            assert_eq!(
6847                parsed, expected,
6848                "RestartStrategy::from_wire({wire:?}) must return \
6849                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
6850            );
6851        }
6852    }
6853
6854    #[test]
6855    fn restart_strategy_from_wire_round_trips_through_as_str() {
6856        // Fail-before-pass-after pin on the closed round-trip between
6857        // the forward [`RestartStrategy::as_str`] emitter and the
6858        // reverse [`RestartStrategy::from_wire`] parser: for every
6859        // variant in [`RestartStrategy::ALL`], parsing the emitter's
6860        // output must return exactly the same variant. Any per-arm
6861        // divergence — a future arm added to `as_str` but not
6862        // `from_wire`, an accidental copy-paste flip in one but not
6863        // the other — silently splits the emit and parse halves and
6864        // the failure surfaces at consumer parse time far from the
6865        // drift site. The `ALL`-iterating shape means a future arm
6866        // addition picks up the coverage by construction.
6867        //
6868        // Peer of the sibling
6869        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
6870        // (18c7342) round-trip pin on
6871        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
6872        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
6873        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
6874        for &variant in RestartStrategy::ALL {
6875            let wire = variant.as_str();
6876            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6877                panic!(
6878                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6879                     must be Some({variant:?}) — the two halves of the round-trip \
6880                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
6881                     got None on wire byte-string {wire:?}"
6882                )
6883            });
6884            assert_eq!(
6885                parsed, variant,
6886                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6887                 must round-trip to the same variant; got {parsed:?}"
6888            );
6889        }
6890    }
6891
6892    #[test]
6893    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
6894        // Fail-before-pass-after pin on the closed-set refusal
6895        // discipline of [`RestartStrategy::from_wire`]: every
6896        // byte-string outside the four-arm accept-set returns `None`
6897        // rather than silently collapsing onto the [`Default`]
6898        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
6899        // exercised here sweeps the load-bearing drift shapes: the
6900        // empty string (a stripped serde-attribute drift), all-
6901        // whitespace strings (the canonical text-editor accidental
6902        // padding shape), the kebab-case dispatcher-catalog identities
6903        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
6904        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
6905        // derived [`std::str::FromStr`] accept-set, which parses the
6906        // *other* axis of this enum's two-axis split and must not leak
6907        // into the `from_wire` PascalCase-wire accept-set), the
6908        // lowercased single-word forms (`"oneforone"`), the padded
6909        // canonical scalar (`" OneForOne "`), the trailing-newline
6910        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
6911        // (`"AllForOne"` — the canonical typo direction).
6912        //
6913        // Peer of the sibling
6914        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
6915        // (2aa6d23) +
6916        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
6917        // (18c7342) refusal pins on the peer closed-set typed-enum
6918        // axes.
6919        for bad in [
6920            "",
6921            " ",
6922            "\n",
6923            "\t",
6924            "one-for-one",
6925            "one-for-all",
6926            "rest-for-one",
6927            "simple-one-for-one",
6928            "oneforone",
6929            "OneForOnes",
6930            "one_for_one",
6931            "one for one",
6932            "ONEFORONE",
6933            "OneForOne ",
6934            " OneForOne",
6935            " SimpleOneForOne ",
6936            "OneForOne\n",
6937            "restforone",
6938            "REST_FOR_ONE",
6939            "AllForOne",
6940            "Simple",
6941            "?",
6942        ] {
6943            assert!(
6944                RestartStrategy::from_wire(bad).is_none(),
6945                "RestartStrategy::from_wire({bad:?}) must return None — the \
6946                 parser's accept-set is exactly the four RestartStrategy::as_str \
6947                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
6948                 and this byte-string is outside that closed set"
6949            );
6950        }
6951    }
6952
6953    #[test]
6954    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
6955        // Fail-before-pass-after pin on the fourth path of the four-path
6956        // convergence: `from_wire` (the reverse projection) inverts the
6957        // `Serialize` derive's wire byte-string on every variant.
6958        // Together with the pre-existing three-path convergence
6959        // (`Display` + `as_str` + `Serialize` all resolve to the same
6960        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
6961        // pinned by
6962        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
6963        // this closes the round-trip: the wire byte-string the
6964        // `Serialize` derive emits parses back to the same variant
6965        // through `from_wire`, so any future serde-attribute or variant-
6966        // rename drift on the emit half now surfaces as a matched drift
6967        // on the parse half at caixa-core build time — the two halves
6968        // migrate as a unit through the lifted consts on any future
6969        // rename, and the round-trip cannot silently split.
6970        //
6971        // Peer of the sibling
6972        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6973        // (18c7342) wire-format pin on
6974        // [`crate::aplicacao::PlacementStrategy::from_wire`].
6975        for &variant in RestartStrategy::ALL {
6976            let wire = serde_json::to_string(&variant).unwrap();
6977            let unquoted = wire
6978                .strip_prefix('"')
6979                .and_then(|s| s.strip_suffix('"'))
6980                .expect("serialized RestartStrategy is a JSON string");
6981            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
6982                panic!(
6983                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
6984                     Serialize derive's wire byte-string for \
6985                     RestartStrategy::{variant:?} — the four-path convergence \
6986                     (Display + as_str + Serialize + from_wire) resolves through \
6987                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
6988                )
6989            });
6990            assert_eq!(
6991                parsed, variant,
6992                "RestartStrategy::from_wire of the Serialize derive's wire \
6993                 byte-string for RestartStrategy::{variant:?} must round-trip \
6994                 to the same variant; got {parsed:?}"
6995            );
6996        }
6997    }
6998
6999    #[test]
7000    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
7001        // Fail-before-pass-after byte-parity pin on the newly lifted
7002        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
7003        // library trait impl and the substrate-primitive
7004        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
7005        // the same four-arm accept-set across every arm the exhaustive
7006        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7007        // detour that routes the trait impl through a divergent projection
7008        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
7009        // … }` re-inlining that opens a compile-time link to the un-
7010        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
7011        // attribute drift that silently splits the wire byte-string from
7012        // every consumer that reaches for this typed dispatch, an
7013        // accidental swap onto the kebab-case dispatcher-catalog axis the
7014        // pre-existing [`std::str::FromStr`] impl parses through and which
7015        // would collide the two-axis wire/catalog split the sibling
7016        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
7017        // trips at caixa-core test time under `assert_eq!` rather than at
7018        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
7019        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
7020        // carries so no arm's projection is covered only by the sibling
7021        // method-named `from_wire` path. Peer of the sibling
7022        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
7023        // (3c83606),
7024        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
7025        // (bf33136), and the M3
7026        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
7027        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
7028        // onto the first M2-OTP-shape closed-set typed enum on the caixa
7029        // surface.
7030        for &variant in RestartStrategy::ALL {
7031            let wire = variant.as_str();
7032            assert_eq!(
7033                <RestartStrategy as TryFrom<&str>>::try_from(wire),
7034                Ok(variant),
7035                "TryFrom<&str> impl on RestartStrategy must round-trip \
7036                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
7037                 Ok(RestartStrategy::{variant:?}) — divergence from \
7038                 RestartStrategy::from_wire signals a silent detour off \
7039                 the substrate-primitive accessor"
7040            );
7041            assert_eq!(
7042                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
7043                RestartStrategy::from_wire(wire),
7044                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
7045                 RestartStrategy::from_wire on the same input"
7046            );
7047        }
7048    }
7049
7050    #[test]
7051    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
7052        // Rejection witness on the `impl TryFrom<&str> for
7053        // RestartStrategy` — sweeps a candidate set of byte-strings
7054        // outside the four-arm PascalCase wire accept-set the sibling
7055        // [`RestartStrategy::as_str`] emits and asserts every one lands on
7056        // `Err(())`, so a future accidental widening of the trait impl's
7057        // accept-set (a stray additional
7058        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
7059        // path, a silent inclusion of the kebab-case dispatcher-catalog
7060        // byte-string the pre-existing [`std::str::FromStr`] impl the
7061        // [`gen_platform::FromStrKind`] derive installs parses onto the
7062        // wire axis — which would collide the two-axis
7063        // wire/dispatcher-catalog split the sibling
7064        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
7065        // an English-rebrand or plural-arm silent alias that would
7066        // widen the wire accept-set past the OTP-canonical four) trips at
7067        // caixa-core test time. The candidate set includes the empty
7068        // string, whitespace-only padding, the kebab-case dispatcher-
7069        // catalog byte-strings on the sibling axis (a caller who confuses
7070        // the two axes trips here rather than at a downstream consumer's
7071        // silent reject), a lowercase / uppercase / mixed-case fold of
7072        // each PascalCase arm (a caller who assumes case-fold acceptance
7073        // trips here), leading/trailing whitespace padding, the trailing-
7074        // newline shape, quote-wrapped candidates, and a residual set of
7075        // plausible-but-wrong English rebrand candidates. Peer of the
7076        // sibling
7077        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
7078        // (3c83606) and
7079        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
7080        // (6fd00cd) rejection witnesses.
7081        let rejected: &[&str] = &[
7082            "",
7083            " ",
7084            "\n",
7085            "\t",
7086            "one-for-one",
7087            "one-for-all",
7088            "rest-for-one",
7089            "simple-one-for-one",
7090            "oneforone",
7091            "one_for_one",
7092            "OneForOnes",
7093            "ONEFORONE",
7094            "oneforall",
7095            "restforone",
7096            "simpleoneforone",
7097            "OneForOne ",
7098            " OneForOne",
7099            " OneForAll ",
7100            "OneForOne\n",
7101            "RestForOne\t",
7102            "OneForEach",
7103            "AllForOne",
7104            "one for one",
7105            "\"OneForOne\"",
7106            "?",
7107        ];
7108        for &input in rejected {
7109            assert_eq!(
7110                <RestartStrategy as TryFrom<&str>>::try_from(input),
7111                Err(()),
7112                "TryFrom<&str> impl on RestartStrategy must reject the \
7113                 non-wire byte-string {input:?} — silent acceptance signals \
7114                 an accept-set widening off the paired \
7115                 RestartStrategy::from_wire resolver"
7116            );
7117        }
7118    }
7119
7120    #[test]
7121    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
7122        // Cross-axis partition pin: the paired `TryFrom<&str>` and
7123        // `from_wire` reverse projections must resolve identically on
7124        // *every* input, not just the ones [`RestartStrategy::ALL`]
7125        // enumerates. Sweeps a mixed candidate set spanning accepted
7126        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
7127        // dispatcher-catalog byte-strings, empty, whitespace-padded,
7128        // quoted, English-rebrand candidates) inputs and asserts the
7129        // trait's `Result::ok()` projection byte-equals the method-named
7130        // resolver's `Option<Self>` return-shape on each, locking the two
7131        // paths together by construction so any future detour (a stray
7132        // `try_from` special-case that widens or narrows the accept-set
7133        // outside the paired `from_wire` resolver, an accidental swap
7134        // onto the kebab-case [`std::str::FromStr`] impl the
7135        // [`gen_platform::FromStrKind`] derive installs on the sibling
7136        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
7137        // the sibling
7138        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
7139        // pin — extends the round-trip discipline onto the M2-OTP-shape
7140        // sibling-restart axis.
7141        let candidates: &[&str] = &[
7142            "OneForOne",
7143            "OneForAll",
7144            "RestForOne",
7145            "SimpleOneForOne",
7146            "",
7147            "one-for-one",
7148            "one-for-all",
7149            "rest-for-one",
7150            "simple-one-for-one",
7151            "oneforone",
7152            "unknown",
7153            "OneForOne ",
7154            " OneForOne",
7155            "\"OneForOne\"",
7156            "OneForEach",
7157            "?",
7158        ];
7159        for &input in candidates {
7160            let via_trait: Option<RestartStrategy> =
7161                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
7162            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
7163            assert_eq!(
7164                via_trait, via_method,
7165                "TryFrom<&str> and from_wire must resolve identically on \
7166                 input {input:?} — divergence signals the two reverse-\
7167                 projection paths have drifted onto different accept-sets"
7168            );
7169        }
7170    }
7171
7172    #[test]
7173    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
7174        // Fail-before-pass-after byte-parity pin on the newly lifted
7175        // `impl From<RestartStrategy> for &'static str` — asserts the
7176        // standard-library trait impl and the substrate-primitive
7177        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
7178        // the same four-arm emit-set across every arm the exhaustive
7179        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7180        // detour that routes the trait impl through a divergent
7181        // projection (a per-arm inline `match strategy { OneForOne =>
7182        // "OneForOne", … }` re-inlining that opens a compile-time link to
7183        // the un-lifted arm-literal, an accidental swap onto the sibling
7184        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
7185        // would collide the two-axis wire/catalog split the sibling
7186        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
7187        // at caixa-core test time under `assert_eq!` rather than at a
7188        // downstream `impl Into<&'static str>`-bound consumer's silent
7189        // split. Sweeps every one of the four arms
7190        // [`RestartStrategy::ALL`] carries so no arm's projection is
7191        // covered only by the sibling method-named `as_str` /
7192        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
7193        // `<&'static str as From<RestartStrategy>>::from` output in a
7194        // `const`-shape binding to make the `'static` lifetime promise a
7195        // build-time invariant — a future accidental downgrade of any of
7196        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7197        // constants to a non-`&'static str` (a `String::leak()`-produced
7198        // return, a `Box::leak`-cast) trips at caixa-core build time
7199        // rather than at a downstream `'static`-bound consumer.
7200        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7201        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7202        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7203        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7204        for &variant in RestartStrategy::ALL {
7205            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7206            let via_method: &'static str = variant.as_str();
7207            assert_eq!(
7208                via_trait, via_method,
7209                "From<RestartStrategy> for &'static str impl must round-trip \
7210                 RestartStrategy::{variant:?} to the same lifted \
7211                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
7212                 divergence signals a silent detour off the substrate-primitive \
7213                 accessor"
7214            );
7215            let via_into: &'static str = variant.into();
7216            assert_eq!(
7217                via_into, via_method,
7218                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
7219                 byte-equal RestartStrategy::as_str on the same input — the \
7220                 blanket-derived Into shape must resolve to the same as_str \
7221                 dispatch as the explicit From impl"
7222            );
7223        }
7224        assert_eq!(
7225            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7226            [
7227                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7228                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7229                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7230                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7231            ],
7232            "const-context RestartStrategy::as_str must resolve to the four \
7233             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
7234             downgrade of any arm to a non-const or non-static byte-string \
7235             breaks the `&'static str`-lifetime promise the paired \
7236             From<RestartStrategy> for &'static str impl carries by \
7237             construction"
7238        );
7239    }
7240
7241    #[test]
7242    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
7243        // Cross-axis partition pin: the paired trait-idiomatic
7244        // `From<RestartStrategy> for &'static str` forward projection and
7245        // the method-named [`RestartStrategy::as_str`] forward projection
7246        // must resolve identically on *every* arm, not just the ones
7247        // named in the primary byte-parity pin above. Sweeps every
7248        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
7249        // output byte-equals the method-named accessor's return-value on
7250        // each, locking the two forward-projection paths together by
7251        // construction so any future detour (a stray `From` special-case
7252        // that lands on a divergent per-arm literal outside the paired
7253        // `as_str` dispatch, a hypothetical rebrand touching one axis
7254        // without the other) trips at caixa-core test time. Peer of the
7255        // sibling reverse-projection partition pin
7256        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7257        // — extends the round-trip discipline onto the trait-idiomatic
7258        // *forward* axis, closing the two-way `Self ↔ &'static str`
7259        // round-trip on the trait-idiomatic pair
7260        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
7261        // well as the pre-existing method-named pair
7262        // (`as_str` + `from_wire`).
7263        for &variant in RestartStrategy::ALL {
7264            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7265            let via_method: &'static str = variant.as_str();
7266            assert_eq!(
7267                via_trait, via_method,
7268                "From<RestartStrategy> for &'static str and \
7269                 RestartStrategy::as_str must resolve identically on \
7270                 RestartStrategy::{variant:?} — divergence signals the \
7271                 two forward-projection paths have drifted onto different \
7272                 emit-sets"
7273            );
7274        }
7275        // Round-trip witness: every arm's forward `From` output re-parses
7276        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
7277        // to the original variant. Closes the two-way `RestartStrategy ↔
7278        // &'static str` round-trip on the trait-idiomatic axis pair,
7279        // mirroring the pre-existing method-named `as_str` + `from_wire`
7280        // round-trip on the substrate-primitive axis pair.
7281        for &variant in RestartStrategy::ALL {
7282            let emitted: &'static str = variant.into();
7283            let re_parsed: Result<RestartStrategy, ()> =
7284                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7285            assert_eq!(
7286                re_parsed,
7287                Ok(variant),
7288                "trait-idiomatic axis pair must round-trip \
7289                 RestartStrategy::{variant:?} through `.into::<&'static \
7290                 str>()` and back through `TryFrom<&str>` — a break signals \
7291                 the forward-emit and reverse-parse axes have drifted onto \
7292                 different vocabularies"
7293            );
7294        }
7295    }
7296
7297    #[test]
7298    fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
7299        // Fail-before-pass-after byte-parity pin on the newly lifted
7300        // `impl From<&RestartStrategy> for &'static str` — asserts the
7301        // borrowed-input standard-library trait impl and the substrate-
7302        // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
7303        // resolve to the same four-arm emit-set across every arm the
7304        // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
7305        // `From` trait does not auto-derive the borrowed-input sibling
7306        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
7307        // where T: Copy, U: From<T>` blanket in `core`), so the
7308        // borrowed-input axis is a distinct trait-idiomatic surface
7309        // that a `.iter().map(Into::into)` shape over
7310        // [`RestartStrategy::ALL`] (whose iterator yields
7311        // `&RestartStrategy`, not `RestartStrategy`) reaches through
7312        // this impl and no other — the paired owned-input
7313        // [`From<RestartStrategy>`] impl requires an explicit
7314        // `.copied()` / dereference before the trait fires.
7315        // Materializes the `<&'static str as
7316        // From<&RestartStrategy>>::from` output in a `const`-shape
7317        // binding to make the `'static` lifetime promise a build-time
7318        // invariant.
7319        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7320        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7321        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7322        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7323        for variant in RestartStrategy::ALL {
7324            let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
7325            let via_method: &'static str = variant.as_str();
7326            assert_eq!(
7327                via_trait, via_method,
7328                "From<&RestartStrategy> for &'static str impl must \
7329                 round-trip &RestartStrategy::{variant:?} to the same \
7330                 lifted SUPERVISOR_ESTRATEGIA_* const \
7331                 RestartStrategy::as_str returns — divergence signals a \
7332                 silent detour off the substrate-primitive accessor"
7333            );
7334            let via_into: &'static str = variant.into();
7335            assert_eq!(
7336                via_into, via_method,
7337                "Into<&'static str>::into on &RestartStrategy::{variant:?} \
7338                 must byte-equal RestartStrategy::as_str on the same input — \
7339                 the blanket-derived Into shape must resolve to the same \
7340                 as_str dispatch as the explicit From impl"
7341            );
7342        }
7343        assert_eq!(
7344            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7345            [
7346                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7347                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7348                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7349                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7350            ],
7351            "const-context RestartStrategy::as_str must resolve to the \
7352             four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
7353             input From<&RestartStrategy> for &'static str impl inherits \
7354             its `'static` lifetime promise from the same accessor the \
7355             owned-input sibling routes through"
7356        );
7357    }
7358
7359    #[test]
7360    fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
7361        // Cross-axis partition pin: the paired trait-idiomatic
7362        // owned-input `From<RestartStrategy> for &'static str` (523157d
7363        // campaign-shape) and borrowed-input `From<&RestartStrategy> for
7364        // &'static str` (this lift) forward projections must resolve
7365        // identically on every arm, locking the two input-shape paths
7366        // together so any future detour trips at caixa-core test time.
7367        // Then a witness that a `.iter().map(Into::into)` pipe over
7368        // [`RestartStrategy::ALL`] (whose iterator yields
7369        // `&RestartStrategy`) materializes the four-arm accept-set
7370        // through the borrowed-input axis alone — the exact shape a
7371        // future wasm-operator per-supervisor sibling-restart-strategy
7372        // diagnostic line, a future substrate-wide per-arm diagnostic
7373        // column, or a
7374        // `HashMap::<&'static str, RestartStrategy>::from_iter(
7375        //     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
7376        // per-strategy lookup reaches through — closing the two-way
7377        // owned/borrowed input-shape symmetry on the forward-projection
7378        // trait-idiomatic axis. Peer of the sibling
7379        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7380        // (64aa742) /
7381        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7382        // (5ab993a) /
7383        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7384        // (807b0b5) partition pins on the sibling closed-set typed-enum
7385        // discriminator axes — extends the borrowed-input axis
7386        // discipline onto the first M2 OTP-shape sibling-restart
7387        // closed-set typed enum on the caixa surface. Also closes the
7388        // direct two-way `&Self → &'static str → Self` round-trip via
7389        // the paired [`TryFrom<&str>`] axis — unlike the peer
7390        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
7391        // lowercase Portuguese diagnostic bytes while the reverse
7392        // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
7393        // trip through an intermediate wire-vocab hop), the
7394        // [`RestartStrategy::as_str`] emit and
7395        // [`RestartStrategy::from_wire`] parse share the same
7396        // `PascalCase` vocabulary by construction, so the borrowed-
7397        // input forward axis and the reverse axis compose directly.
7398        for &variant in RestartStrategy::ALL {
7399            let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7400            let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
7401            assert_eq!(
7402                owned, borrowed,
7403                "From<RestartStrategy> and From<&RestartStrategy> for \
7404                 &'static str must resolve identically on \
7405                 RestartStrategy::{variant:?} — divergence signals the \
7406                 owned-input and borrowed-input forward-projection paths \
7407                 have drifted onto different emit-sets"
7408            );
7409        }
7410        let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
7411        let via_method: Vec<&'static str> =
7412            RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
7413        assert_eq!(
7414            via_iter, via_method,
7415            "`.iter().map(Into::into)` over RestartStrategy::ALL must \
7416             byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
7417             borrowed-input `From<&RestartStrategy> for &'static str` \
7418             axis is what makes the `.iter().map(Into::into)` shape route \
7419             through the substrate-primitive `RestartStrategy::as_str` \
7420             accessor rather than through a per-call-site `.copied()` / \
7421             dereference detour"
7422        );
7423        for variant in RestartStrategy::ALL {
7424            let emitted: &'static str = variant.into();
7425            let re_parsed: Result<RestartStrategy, ()> =
7426                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7427            assert_eq!(
7428                re_parsed,
7429                Ok(*variant),
7430                "trait-idiomatic borrowed-input forward-projection + \
7431                 reverse-projection axis pair must round-trip \
7432                 &RestartStrategy::{variant:?} through `.into::<&'static \
7433                 str>()` (via the borrowed-input axis) and back through \
7434                 `TryFrom<&str>` — a break signals the borrowed-input \
7435                 forward-emit and reverse-parse axes have drifted onto \
7436                 different vocabularies"
7437            );
7438        }
7439    }
7440
7441    #[test]
7442    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
7443        // Fail-before-pass-after byte-parity pin on the newly lifted
7444        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
7445        // library trait impl and the substrate-primitive
7446        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
7447        // the same three-arm accept-set across every arm the exhaustive
7448        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
7449        // detour that routes the trait impl through a divergent
7450        // projection (a per-arm inline `match s { "Permanent" =>
7451        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
7452        // link to the un-lifted arm-literal, a hypothetical
7453        // `#[serde(rename_all = "…")]` attribute drift that silently
7454        // splits the wire byte-string from every consumer that reaches
7455        // for this typed dispatch, an accidental swap onto the kebab-case
7456        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
7457        // impl parses through and which would collide the two-axis
7458        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
7459        // doc block makes load-bearing) trips at caixa-core test time
7460        // under `assert_eq!` rather than at a downstream
7461        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
7462        // every one of the three arms [`RestartPolicy::ALL`] carries so
7463        // no arm's projection is covered only by the sibling method-
7464        // named `from_wire` path. Peer of the sibling
7465        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
7466        // (5b828ed) — extends the trait-idiomatic reverse-projection
7467        // axis onto the third and final M2-OTP-shape closed-set typed
7468        // enum on the caixa surface (the paired per-child restart-
7469        // decision-policy sibling on the same M2 `:supervisor` slot).
7470        for &variant in RestartPolicy::ALL {
7471            let wire = variant.as_str();
7472            assert_eq!(
7473                <RestartPolicy as TryFrom<&str>>::try_from(wire),
7474                Ok(variant),
7475                "TryFrom<&str> impl on RestartPolicy must round-trip \
7476                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
7477                 Ok(RestartPolicy::{variant:?}) — divergence from \
7478                 RestartPolicy::from_wire signals a silent detour off \
7479                 the substrate-primitive accessor"
7480            );
7481            assert_eq!(
7482                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
7483                RestartPolicy::from_wire(wire),
7484                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
7485                 equal RestartPolicy::from_wire on the same input"
7486            );
7487        }
7488    }
7489
7490    #[test]
7491    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
7492        // Rejection witness on the `impl TryFrom<&str> for
7493        // RestartPolicy` — sweeps a candidate set of byte-strings
7494        // outside the three-arm PascalCase wire accept-set the sibling
7495        // [`RestartPolicy::as_str`] emits and asserts every one lands on
7496        // `Err(())`, so a future accidental widening of the trait impl's
7497        // accept-set (a stray additional
7498        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
7499        // path, a silent inclusion of the kebab-case dispatcher-catalog
7500        // byte-string the pre-existing [`std::str::FromStr`] impl the
7501        // [`gen_platform::FromStrKind`] derive installs parses onto the
7502        // wire axis — which would collide the two-axis
7503        // wire/dispatcher-catalog split the sibling
7504        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
7505        // an English-rebrand or plural-arm silent alias that would widen
7506        // the wire accept-set past the OTP-canonical three) trips at
7507        // caixa-core test time. The candidate set includes the empty
7508        // string, whitespace-only padding, the kebab-case dispatcher-
7509        // catalog byte-strings on the sibling axis (a caller who
7510        // confuses the two axes trips here rather than at a downstream
7511        // consumer's silent reject), a lowercase / uppercase / mixed-case
7512        // fold of each PascalCase arm (a caller who assumes case-fold
7513        // acceptance trips here), leading/trailing whitespace padding,
7514        // the trailing-newline shape, quote-wrapped candidates, and a
7515        // residual set of plausible-but-wrong English rebrand
7516        // candidates. Peer of the sibling
7517        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
7518        // (5b828ed) rejection witness.
7519        let rejected: &[&str] = &[
7520            "",
7521            " ",
7522            "\n",
7523            "\t",
7524            "permanent",
7525            "temporary",
7526            "transient",
7527            "PERMANENT",
7528            "TEMPORARY",
7529            "TRANSIENT",
7530            "Permanents",
7531            "Permanent ",
7532            " Permanent",
7533            " Temporary ",
7534            "Permanent\n",
7535            "Transient\t",
7536            "\"Permanent\"",
7537            "Ephemeral",
7538            "Always",
7539            "Never",
7540            "OnAbnormalExit",
7541            "intrinsic",
7542            "?",
7543        ];
7544        for &input in rejected {
7545            assert_eq!(
7546                <RestartPolicy as TryFrom<&str>>::try_from(input),
7547                Err(()),
7548                "TryFrom<&str> impl on RestartPolicy must reject the \
7549                 non-wire byte-string {input:?} — silent acceptance \
7550                 signals an accept-set widening off the paired \
7551                 RestartPolicy::from_wire resolver"
7552            );
7553        }
7554    }
7555
7556    #[test]
7557    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
7558        // Cross-axis partition pin: the paired `TryFrom<&str>` and
7559        // `from_wire` reverse projections must resolve identically on
7560        // *every* input, not just the ones [`RestartPolicy::ALL`]
7561        // enumerates. Sweeps a mixed candidate set spanning accepted
7562        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
7563        // case dispatcher-catalog byte-strings, empty, whitespace-
7564        // padded, quoted, English-rebrand candidates) inputs and asserts
7565        // the trait's `Result::ok()` projection byte-equals the method-
7566        // named resolver's `Option<Self>` return-shape on each, locking
7567        // the two paths together by construction so any future detour
7568        // (a stray `try_from` special-case that widens or narrows the
7569        // accept-set outside the paired `from_wire` resolver, an
7570        // accidental swap onto the kebab-case [`std::str::FromStr`]
7571        // impl the [`gen_platform::FromStrKind`] derive installs on the
7572        // sibling dispatcher-catalog axis) trips at caixa-core test
7573        // time. Peer of the sibling
7574        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7575        // pin — extends the round-trip discipline onto the M2-OTP-shape
7576        // per-child restart-policy axis.
7577        let candidates: &[&str] = &[
7578            "Permanent",
7579            "Temporary",
7580            "Transient",
7581            "",
7582            "permanent",
7583            "temporary",
7584            "transient",
7585            "PERMANENT",
7586            "unknown",
7587            "Permanent ",
7588            " Permanent",
7589            "\"Permanent\"",
7590            "Ephemeral",
7591            "OnAbnormalExit",
7592            "?",
7593        ];
7594        for &input in candidates {
7595            let via_trait: Option<RestartPolicy> =
7596                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
7597            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
7598            assert_eq!(
7599                via_trait, via_method,
7600                "TryFrom<&str> and from_wire must resolve identically on \
7601                 input {input:?} — divergence signals the two reverse-\
7602                 projection paths have drifted onto different accept-sets"
7603            );
7604        }
7605    }
7606
7607    #[test]
7608    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
7609        // Fail-before-pass-after byte-parity pin on the newly lifted
7610        // `impl From<RestartPolicy> for &'static str` — asserts the
7611        // standard-library trait impl and the substrate-primitive
7612        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
7613        // the same three-arm emit-set across every arm the exhaustive
7614        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
7615        // detour that routes the trait impl through a divergent
7616        // projection (a per-arm inline `match policy { Permanent =>
7617        // "Permanent", … }` re-inlining that opens a compile-time link
7618        // to the un-lifted arm-literal, an accidental swap onto the
7619        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
7620        // axis that would collide the two-axis wire/catalog split the
7621        // sibling [`RestartPolicy::from_wire`] doc block makes
7622        // load-bearing) trips at caixa-core test time under
7623        // `assert_eq!` rather than at a downstream
7624        // `impl Into<&'static str>`-bound consumer's silent split.
7625        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
7626        // carries so no arm's projection is covered only by the sibling
7627        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
7628        // paths. Materializes the `<&'static str as
7629        // From<RestartPolicy>>::from` output in a `const`-shape binding
7630        // to make the `'static` lifetime promise a build-time invariant
7631        // — a future accidental downgrade of any of the three arms'
7632        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
7633        // non-`&'static str` (a `String::leak()`-produced return, a
7634        // `Box::leak`-cast) trips at caixa-core build time rather than
7635        // at a downstream `'static`-bound consumer. Peer of the sibling
7636        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
7637        // (523157d) — extends the trait-idiomatic forward-projection
7638        // axis onto the second (and second-of-two-in-M2) closed-set
7639        // typed enum on the caixa surface (the paired per-child
7640        // restart-decision-policy sibling on the same M2 `:supervisor`
7641        // slot).
7642        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
7643        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
7644        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
7645        for &variant in RestartPolicy::ALL {
7646            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
7647            let via_method: &'static str = variant.as_str();
7648            assert_eq!(
7649                via_trait, via_method,
7650                "From<RestartPolicy> for &'static str impl must round-trip \
7651                 RestartPolicy::{variant:?} to the same lifted \
7652                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
7653                 divergence signals a silent detour off the substrate-primitive \
7654                 accessor"
7655            );
7656            let via_into: &'static str = variant.into();
7657            assert_eq!(
7658                via_into, via_method,
7659                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
7660                 byte-equal RestartPolicy::as_str on the same input — the \
7661                 blanket-derived Into shape must resolve to the same as_str \
7662                 dispatch as the explicit From impl"
7663            );
7664        }
7665        assert_eq!(
7666            [PERMANENT, TEMPORARY, TRANSIENT],
7667            [
7668                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7669                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7670                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7671            ],
7672            "const-context RestartPolicy::as_str must resolve to the three \
7673             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
7674             downgrade of any arm to a non-const or non-static byte-string \
7675             breaks the `&'static str`-lifetime promise the paired \
7676             From<RestartPolicy> for &'static str impl carries by \
7677             construction"
7678        );
7679    }
7680
7681    #[test]
7682    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
7683        // Cross-axis partition pin: the paired trait-idiomatic
7684        // `From<RestartPolicy> for &'static str` forward projection and
7685        // the method-named [`RestartPolicy::as_str`] forward projection
7686        // must resolve identically on *every* arm, not just the ones
7687        // named in the primary byte-parity pin above. Sweeps every
7688        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
7689        // output byte-equals the method-named accessor's return-value on
7690        // each, locking the two forward-projection paths together by
7691        // construction so any future detour (a stray `From` special-case
7692        // that lands on a divergent per-arm literal outside the paired
7693        // `as_str` dispatch, a hypothetical rebrand touching one axis
7694        // without the other) trips at caixa-core test time. Peer of the
7695        // sibling forward-projection partition pin
7696        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
7697        // (523157d) — extends the round-trip discipline onto the
7698        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
7699        // surface, closing the two-way `Self ↔ &'static str` round-trip
7700        // on the trait-idiomatic pair (`From<Self> for &'static str` +
7701        // `TryFrom<&str> for Self`) as well as the pre-existing method-
7702        // named pair (`as_str` + `from_wire`).
7703        for &variant in RestartPolicy::ALL {
7704            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
7705            let via_method: &'static str = variant.as_str();
7706            assert_eq!(
7707                via_trait, via_method,
7708                "From<RestartPolicy> for &'static str and \
7709                 RestartPolicy::as_str must resolve identically on \
7710                 RestartPolicy::{variant:?} — divergence signals the \
7711                 two forward-projection paths have drifted onto different \
7712                 emit-sets"
7713            );
7714        }
7715        // Round-trip witness: every arm's forward `From` output re-parses
7716        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
7717        // to the original variant. Closes the two-way `RestartPolicy ↔
7718        // &'static str` round-trip on the trait-idiomatic axis pair,
7719        // mirroring the pre-existing method-named `as_str` + `from_wire`
7720        // round-trip on the substrate-primitive axis pair.
7721        for &variant in RestartPolicy::ALL {
7722            let emitted: &'static str = variant.into();
7723            let re_parsed: Result<RestartPolicy, ()> =
7724                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
7725            assert_eq!(
7726                re_parsed,
7727                Ok(variant),
7728                "trait-idiomatic axis pair must round-trip \
7729                 RestartPolicy::{variant:?} through `.into::<&'static \
7730                 str>()` and back through `TryFrom<&str>` — a break signals \
7731                 the forward-emit and reverse-parse axes have drifted onto \
7732                 different vocabularies"
7733            );
7734        }
7735    }
7736
7737    #[test]
7738    fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
7739        // Fail-before-pass-after byte-parity pin on the newly lifted
7740        // `impl From<&RestartPolicy> for &'static str` — asserts the
7741        // borrowed-input standard-library trait impl and the substrate-
7742        // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
7743        // resolve to the same three-arm emit-set across every arm the
7744        // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
7745        // `From` trait does not auto-derive the borrowed-input sibling
7746        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
7747        // where T: Copy, U: From<T>` blanket in `core`), so the
7748        // borrowed-input axis is a distinct trait-idiomatic surface
7749        // that a `.iter().map(Into::into)` shape over
7750        // [`RestartPolicy::ALL`] (whose iterator yields
7751        // `&RestartPolicy`, not `RestartPolicy`) reaches through this
7752        // impl and no other — the paired owned-input
7753        // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
7754        // / dereference before the trait fires. Materializes the
7755        // `<&'static str as From<&RestartPolicy>>::from` output in a
7756        // `const`-shape binding to make the `'static` lifetime promise
7757        // a build-time invariant.
7758        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
7759        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
7760        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
7761        for variant in RestartPolicy::ALL {
7762            let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
7763            let via_method: &'static str = variant.as_str();
7764            assert_eq!(
7765                via_trait, via_method,
7766                "From<&RestartPolicy> for &'static str impl must round-trip \
7767                 &RestartPolicy::{variant:?} to the same lifted \
7768                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
7769                 returns — divergence signals a silent detour off the \
7770                 substrate-primitive accessor"
7771            );
7772            let via_into: &'static str = variant.into();
7773            assert_eq!(
7774                via_into, via_method,
7775                "Into<&'static str>::into on &RestartPolicy::{variant:?} \
7776                 must byte-equal RestartPolicy::as_str on the same input — \
7777                 the blanket-derived Into shape must resolve to the same \
7778                 as_str dispatch as the explicit From impl"
7779            );
7780        }
7781        assert_eq!(
7782            [PERMANENT, TEMPORARY, TRANSIENT],
7783            [
7784                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7785                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7786                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7787            ],
7788            "const-context RestartPolicy::as_str must resolve to the three \
7789             lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
7790             From<&RestartPolicy> for &'static str impl inherits its \
7791             `'static` lifetime promise from the same accessor the \
7792             owned-input sibling routes through"
7793        );
7794    }
7795
7796    #[test]
7797    fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
7798        // Cross-axis partition pin: the paired trait-idiomatic
7799        // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
7800        // campaign-shape) and borrowed-input `From<&RestartPolicy> for
7801        // &'static str` (this lift) forward projections must resolve
7802        // identically on every arm, locking the two input-shape paths
7803        // together so any future detour trips at caixa-core test time.
7804        // Then a witness that a `.iter().map(Into::into)` pipe over
7805        // [`RestartPolicy::ALL`] (whose iterator yields
7806        // `&RestartPolicy`) materializes the three-arm accept-set
7807        // through the borrowed-input axis alone — the exact shape a
7808        // future wasm-operator per-child post-exit restart-decision
7809        // diagnostic line, a future substrate-wide per-arm diagnostic
7810        // column, or a
7811        // `HashMap::<&'static str, RestartPolicy>::from_iter(
7812        //     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
7813        // per-policy lookup reaches through — closing the two-way
7814        // owned/borrowed input-shape symmetry on the forward-projection
7815        // trait-idiomatic axis. Peer of the sibling
7816        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7817        // (64aa742) /
7818        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7819        // (5ab993a) /
7820        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7821        // (807b0b5) /
7822        // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7823        // (e941836) partition pins on the sibling closed-set typed-enum
7824        // discriminator axes — extends the borrowed-input axis
7825        // discipline onto the second-of-two M2 OTP-shape closed-set
7826        // typed enum on the caixa surface (per-child restart-decision
7827        // policy). Also closes the direct two-way `&Self → &'static
7828        // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
7829        // — unlike the peer [`crate::CaixaKind`] axis pair (whose
7830        // forward `From` emits lowercase Portuguese diagnostic bytes
7831        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
7832        // forcing the round-trip through an intermediate wire-vocab
7833        // hop), the [`RestartPolicy::as_str`] emit and
7834        // [`RestartPolicy::from_wire`] parse share the same
7835        // `PascalCase` vocabulary by construction, so the borrowed-
7836        // input forward axis and the reverse axis compose directly.
7837        for &variant in RestartPolicy::ALL {
7838            let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
7839            let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
7840            assert_eq!(
7841                owned, borrowed,
7842                "From<RestartPolicy> and From<&RestartPolicy> for \
7843                 &'static str must resolve identically on \
7844                 RestartPolicy::{variant:?} — divergence signals the \
7845                 owned-input and borrowed-input forward-projection paths \
7846                 have drifted onto different emit-sets"
7847            );
7848        }
7849        let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
7850        let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
7851        assert_eq!(
7852            via_iter, via_method,
7853            "`.iter().map(Into::into)` over RestartPolicy::ALL must \
7854             byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
7855             borrowed-input `From<&RestartPolicy> for &'static str` axis \
7856             is what makes the `.iter().map(Into::into)` shape route \
7857             through the substrate-primitive `RestartPolicy::as_str` \
7858             accessor rather than through a per-call-site `.copied()` / \
7859             dereference detour"
7860        );
7861        for variant in RestartPolicy::ALL {
7862            let emitted: &'static str = variant.into();
7863            let re_parsed: Result<RestartPolicy, ()> =
7864                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
7865            assert_eq!(
7866                re_parsed,
7867                Ok(*variant),
7868                "trait-idiomatic borrowed-input forward-projection + \
7869                 reverse-projection axis pair must round-trip \
7870                 &RestartPolicy::{variant:?} through `.into::<&'static \
7871                 str>()` (via the borrowed-input axis) and back through \
7872                 `TryFrom<&str>` — a break signals the borrowed-input \
7873                 forward-emit and reverse-parse axes have drifted onto \
7874                 different vocabularies"
7875            );
7876        }
7877    }
7878
7879    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
7880
7881    #[test]
7882    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
7883        // The fail-before-pass-after pin: pre-lift there was no
7884        // single-source binding between the [`RestartPolicy`] variant
7885        // name the un-`rename`d `Serialize` derive emits under
7886        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
7887        // byte-string every downstream cluster-side dispatcher (the
7888        // future wasm-operator's per-child post-exit restart-decision
7889        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7890        // materializer's admission-time enum-arm bind, the
7891        // `caixa-operator`'s hierarchical reconciliation scheduler's
7892        // per-child-policy fan-out) probes verbatim. A future
7893        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
7894        // or a per-variant `#[serde(rename = "…")]` override, or a
7895        // variant rename in the source — would silently rebrand the
7896        // emitted scalar under one spelling while every downstream
7897        // dispatcher still probed the other, with the failure surfacing
7898        // at the operator's reconcile posture (children coming up under
7899        // the `default()` `Permanent` arm rather than the typed slot's
7900        // declared policy — a `:temporary` `oneShot` child would be
7901        // restarted on clean exit, treating the successful-completion
7902        // signal as failure and re-running the completion-terminal
7903        // one-shot indefinitely; a `:transient` child that clean-exited
7904        // would be restarted, masking the clean-completion contract)
7905        // far from the source rebrand commit and with no field naming
7906        // the drift. Pinning the two paths (the `Serialize` derive's
7907        // serialized string AND the [`RestartPolicy::as_str`] helper)
7908        // to the same three lifted
7909        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
7910        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
7911        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
7912        // byte-strings makes any future drift on either endpoint fail
7913        // here at caixa-core build time. Peer of the sibling
7914        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
7915        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
7916        // and the M3
7917        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7918        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
7919        // same three-path-convergence discipline, extended to close the
7920        // third OTP-shaped closed-enum discriminator axis on the caixa
7921        // typed surface (per-child restart-decision policy).
7922        for (variant, expected) in [
7923            (
7924                RestartPolicy::Permanent,
7925                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7926            ),
7927            (
7928                RestartPolicy::Temporary,
7929                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7930            ),
7931            (
7932                RestartPolicy::Transient,
7933                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7934            ),
7935        ] {
7936            let json = serde_json::to_string(&variant).unwrap();
7937            assert_eq!(
7938                json,
7939                format!("\"{expected}\""),
7940                "RestartPolicy::{variant:?} must serialize to {expected:?}"
7941            );
7942            assert_eq!(
7943                variant.as_str(),
7944                expected,
7945                "RestartPolicy::{variant:?}.as_str() must return the lifted \
7946                 SUPERVISOR_CHILD_RESTART_* constant"
7947            );
7948        }
7949    }
7950
7951    #[test]
7952    fn supervisor_child_restart_consts_are_pairwise_distinct() {
7953        // Cross-arm drift-detection pin: a future collapse of two
7954        // canonical variant byte-strings onto the same value (e.g. an
7955        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
7956        // to also read `"Permanent"`) would silently reroute every
7957        // downstream operator's per-child-policy dispatch onto the
7958        // sibling arm's reconcile branch and pass every propagation-probe
7959        // test that expected only the stale arm's value — a `:transient`
7960        // child would come up under the `:permanent` restart-decision
7961        // posture on every subsequent clean exit, so a completion-terminal
7962        // child would be restarted indefinitely against its declared
7963        // policy. Peer of the sibling
7964        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
7965        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
7966        // and the four-way distinct pin
7967        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
7968        // top-level `SUPERVISOR_KEY_*` axis.
7969        let all = [
7970            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7971            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7972            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7973        ];
7974        for (i, a) in all.iter().enumerate() {
7975            for (j, b) in all.iter().enumerate() {
7976                if i != j {
7977                    assert_ne!(
7978                        a, b,
7979                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
7980                         — got duplicate {a:?} at indices {i} and {j}",
7981                    );
7982                }
7983            }
7984        }
7985    }
7986
7987    #[test]
7988    fn restart_policy_display_routes_through_as_str_helper() {
7989        // The fail-before-pass-after pin on the first half of the
7990        // three-path convergence: pre-convergence [`RestartPolicy`]
7991        // carried a [`std::fmt::Display`] surface via its
7992        // `#[discriminant(also_display)]` gen-platform derive route,
7993        // which arrived kebab-case as `"permanent"` / `"temporary"`
7994        // / `"transient"` on this three-arm enum (whose variant
7995        // names each collapse to their own lowercase form under the
7996        // kebab-case transform) while the wire format ran as
7997        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
7998        // through the un-`rename`d serde derive. Every consumer
7999        // reaching for a policy byte-string past the wire format had
8000        // to pick between three paths ([`RestartPolicy::as_str`],
8001        // the `Serialize` derive's serialized string, or
8002        // `format!("{v}")` on the discriminant-Display route), any
8003        // two of which a future variant rename or
8004        // `#[serde(rename_all = "kebab-case")]` attribute would
8005        // silently desynchronize. Wiring [`std::fmt::Display`]
8006        // through [`RestartPolicy::as_str`] closes the third path:
8007        // every `format!("{v}")` call reaches the same lifted
8008        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
8009        // wire format and the [`RestartPolicy::as_str`] helper
8010        // already route through, so a future variant rename lands at
8011        // exactly one place. Pin the routing here so a future
8012        // `impl std::fmt::Display for RestartPolicy`
8013        // reimplementation that hand-rolls the arms instead of
8014        // delegating to [`RestartPolicy::as_str`] fails at
8015        // caixa-core build time. Peer of the sibling
8016        // [`restart_strategy_display_routes_through_as_str_helper`]
8017        // on the per-supervisor sibling-restart-strategy axis and
8018        // the M3
8019        // `placement_strategy_display_routes_through_as_str_helper`
8020        // (cc8f749) — the third of three OTP-shape closed-enum
8021        // discriminator axes on the caixa typed surface now
8022        // converged onto the same three-path
8023        // (Display → as_str → lifted const) discipline.
8024        for variant in [
8025            RestartPolicy::Permanent,
8026            RestartPolicy::Temporary,
8027            RestartPolicy::Transient,
8028        ] {
8029            assert_eq!(
8030                variant.to_string(),
8031                variant.as_str(),
8032                "RestartPolicy::{variant:?} Display must route through \
8033                 RestartPolicy::as_str (single source of truth: the lifted \
8034                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
8035            );
8036        }
8037    }
8038
8039    #[test]
8040    fn restart_policy_display_matches_serialized_wire_byte_string() {
8041        // The fail-before-pass-after pin on the second half of the
8042        // three-path convergence: `Display` (user-facing text) agrees
8043        // byte-for-byte with the `Serialize` derive's wire format
8044        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
8045        // scalar) on every variant. Pre-convergence the two paths
8046        // were structurally independent — a future
8047        // `#[serde(rename_all = "kebab-case")]` attribute on the
8048        // enum would silently rebrand the emitted wire scalar
8049        // (`permanent`, `temporary`, `transient`) while every
8050        // consumer that pretty-prints the policy (the future
8051        // wasm-operator's per-child post-exit restart-decision
8052        // diagnostic line, the future `feira app graph` per-child
8053        // restart column, the future M4
8054        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
8055        // per-child admission-webhook rejection body) would still
8056        // emit the PascalCase form the `as_str` / `Display` route
8057        // returns, with the mismatch surfacing at consumer parse
8058        // time / operator dispatch time far from the source rebrand
8059        // commit. Pin the two paths byte-for-byte here so any future
8060        // serde-attribute or variant-rename drift is a
8061        // caixa-core-build-time test failure at this call, not a
8062        // silent per-consumer dispatch miss. Peer of the sibling
8063        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
8064        // on the per-supervisor sibling-restart-strategy axis and
8065        // the M3
8066        // `placement_strategy_display_matches_serialized_wire_byte_string`
8067        // (cc8f749).
8068        for variant in [
8069            RestartPolicy::Permanent,
8070            RestartPolicy::Temporary,
8071            RestartPolicy::Transient,
8072        ] {
8073            let wire = serde_json::to_string(&variant).unwrap();
8074            let unquoted = wire
8075                .strip_prefix('"')
8076                .and_then(|s| s.strip_suffix('"'))
8077                .expect("serialized RestartPolicy is a JSON string");
8078            assert_eq!(
8079                variant.to_string(),
8080                unquoted,
8081                "RestartPolicy::{variant:?} Display byte-string must match the \
8082                 Serialize derive's wire byte-string (three-path convergence: \
8083                 Display + as_str + Serialize all resolve to the same \
8084                 SUPERVISOR_CHILD_RESTART_* const)"
8085            );
8086        }
8087    }
8088
8089    #[test]
8090    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
8091        // Fail-before-pass-after byte-parity pin on the lifted
8092        // `impl AsRef<str> for RestartPolicy` — asserts the
8093        // standard-library trait impl and the substrate-primitive
8094        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
8095        // to the same `&str` per instance across the three-arm
8096        // closed set, so any future silent detour that routes the
8097        // impl through a divergent projection (a per-arm inline
8098        // `match self { RestartPolicy::Permanent => "Permanent", … }`
8099        // re-inlining that opens a compile-time link to the un-lifted
8100        // arm-literal, a swap onto the kebab-case
8101        // [`gen_platform::Discriminant`] catalog identity that would
8102        // collide the wire axis with the dispatcher-catalog axis) trips
8103        // at caixa-core test time under `PartialEq` rather than at a
8104        // downstream `impl AsRef<str>`-bound consumer's silent split.
8105        // Sweeps every one of the three arms
8106        // [`RestartPolicy::ALL`] carries so no arm's projection is
8107        // covered only by the sibling wire-format `Serialize` derive
8108        // path. Peer of the sibling
8109        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
8110        // (63eb1a4) on the paired per-supervisor sibling-restart-
8111        // strategy axis and the [`crate::CaixaVersion`]
8112        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
8113        // top-level `:versao` typed newtype — the three pins together
8114        // cover the substrate primitive's `AsRef<str>` projection axis
8115        // on the paired newtype + M2 closed-set-typed-enum surface.
8116        for &variant in RestartPolicy::ALL {
8117            assert_eq!(
8118                <RestartPolicy as AsRef<str>>::as_ref(&variant),
8119                variant.as_str(),
8120                "AsRef<str> impl on RestartPolicy::{variant:?} must \
8121                 byte-equal RestartPolicy::as_str on the same instance \
8122                 — divergence signals a silent detour off the substrate-\
8123                 primitive accessor"
8124            );
8125        }
8126    }
8127
8128    #[test]
8129    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
8130        // Fail-before-pass-after byte-parity pin on the three-path
8131        // convergence discipline the M2 per-child-restart-policy
8132        // primitive now carries on the `&str`-projection axis:
8133        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
8134        // lifted impl), `format!("{v}")` (the pre-existing
8135        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
8136        // primitive `pub const fn` accessor both trait impls delegate
8137        // through) must resolve to the same byte-string on every
8138        // instance across the three-arm closed set. Refuses any future
8139        // divergence between the two trait impls (a stray
8140        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
8141        // rather than delegating through the shared accessor; a
8142        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
8143        // literal cascade) that would silently split the two
8144        // projection paths of the same closed-set typed enum. Mirrors
8145        // the sibling three-path-convergence discipline the peer
8146        // [`RestartStrategy`] typed enum carries on its
8147        // `AsRef<str>` / `Display` / `as_str` triple
8148        // (supervisor.rs pin
8149        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
8150        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
8151        // carries on the same triple (version.rs pin
8152        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
8153        // 16d5c7e).
8154        for &variant in RestartPolicy::ALL {
8155            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
8156            let via_display: String = format!("{variant}");
8157            let via_accessor: &str = variant.as_str();
8158            assert_eq!(via_as_ref, via_accessor);
8159            assert_eq!(via_display, via_accessor);
8160            assert_eq!(via_as_ref, via_display.as_str());
8161        }
8162    }
8163
8164    #[test]
8165    fn restart_policy_all_enumerates_every_variant_exactly_once() {
8166        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
8167        // exhaustive-iteration surface: every variant appears exactly
8168        // once, and the slice length matches the arm count of the
8169        // closed set. Every consumer that walks the accepted-policy
8170        // set (a future `feira supervisor --restart …` CLI-side
8171        // arg-parse's "did you mean" hint, a future M4 admission-
8172        // webhook's per-child rejection body naming the accepted-
8173        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
8174        // projection consumers that iterate the accept-set for
8175        // diagnostic rendering) reads through this slice, so a future
8176        // arm addition that grows the enum but forgets to grow
8177        // [`Self::ALL`] silently truncates every downstream consumer's
8178        // accept-set at the same pre-addition boundary — this pin
8179        // fails at caixa-core build time on the pairwise-distinct +
8180        // arm-count invariants.
8181        //
8182        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
8183        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
8184        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
8185        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
8186        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
8187        // pins on the peer closed-set typed-enum axes.
8188        let all: &[RestartPolicy] = RestartPolicy::ALL;
8189        assert_eq!(
8190            all.len(),
8191            3,
8192            "RestartPolicy::ALL must enumerate every variant of the \
8193             three-arm closed set (Permanent, Temporary, Transient); \
8194             got {all:?}"
8195        );
8196        for (i, a) in all.iter().enumerate() {
8197            for (j, b) in all.iter().enumerate() {
8198                if i != j {
8199                    assert_ne!(
8200                        a, b,
8201                        "RestartPolicy::ALL must carry every variant exactly \
8202                         once — got duplicate {a:?} at indices {i} and {j}"
8203                    );
8204                }
8205            }
8206        }
8207        for variant in [
8208            RestartPolicy::Permanent,
8209            RestartPolicy::Temporary,
8210            RestartPolicy::Transient,
8211        ] {
8212            assert!(
8213                all.contains(&variant),
8214                "RestartPolicy::ALL must contain {variant:?} — a future arm \
8215                 addition that grows the enum but forgets to grow the ALL slice \
8216                 silently truncates every downstream consumer's accept-set at \
8217                 the pre-addition boundary"
8218            );
8219        }
8220    }
8221
8222    #[test]
8223    fn restart_policy_from_wire_accepts_every_lifted_constant() {
8224        // Fail-before-pass-after pin on the forward accept-set of the
8225        // [`RestartPolicy::from_wire`] reverse projection: every
8226        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
8227        // constant the [`RestartPolicy::as_str`] emitter walks parses
8228        // back to its paired variant. Any future arm addition that
8229        // grows the emitter's `as_str` match but forgets to grow the
8230        // parser's `from_wire` match silently splits the two halves of
8231        // the round-trip — the wire byte-string one non-serde consumer
8232        // parses from the one the emitter wrote — with the failure
8233        // surfacing at the operator's reconcile posture (a `:temporary`
8234        // `oneShot` child restarted on clean exit, a `:transient` child
8235        // restarted after clean completion) far from the rebrand
8236        // commit. Pinning the three-arm accept-set here catches the
8237        // drift at caixa-core build time.
8238        //
8239        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
8240        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
8241        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
8242        // accept-set pins on the peer closed-set typed-enum `str → Self`
8243        // axes.
8244        for (wire, expected) in [
8245            (
8246                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8247                RestartPolicy::Permanent,
8248            ),
8249            (
8250                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8251                RestartPolicy::Temporary,
8252            ),
8253            (
8254                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8255                RestartPolicy::Transient,
8256            ),
8257        ] {
8258            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
8259                panic!(
8260                    "RestartPolicy::from_wire({wire:?}) must accept every \
8261                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
8262                     lifted canonical byte-string that RestartPolicy::{expected:?} \
8263                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
8264                )
8265            });
8266            assert_eq!(
8267                parsed, expected,
8268                "RestartPolicy::from_wire({wire:?}) must return \
8269                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
8270            );
8271        }
8272    }
8273
8274    #[test]
8275    fn restart_policy_from_wire_round_trips_through_as_str() {
8276        // Fail-before-pass-after pin on the closed round-trip between
8277        // the forward [`RestartPolicy::as_str`] emitter and the
8278        // reverse [`RestartPolicy::from_wire`] parser: for every
8279        // variant in [`RestartPolicy::ALL`], parsing the emitter's
8280        // output must return exactly the same variant. Any per-arm
8281        // divergence — a future arm added to `as_str` but not
8282        // `from_wire`, an accidental copy-paste flip in one but not
8283        // the other — silently splits the emit and parse halves and
8284        // the failure surfaces at consumer parse time far from the
8285        // drift site. The `ALL`-iterating shape means a future arm
8286        // addition picks up the coverage by construction.
8287        //
8288        // Peer of the sibling
8289        // [`restart_strategy_from_wire_round_trips_through_as_str`]
8290        // (4eec29c) round-trip pin on
8291        // [`RestartStrategy::from_wire`] and the M3
8292        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
8293        // (18c7342) round-trip pin on
8294        // [`crate::aplicacao::PlacementStrategy::from_wire`].
8295        for &variant in RestartPolicy::ALL {
8296            let wire = variant.as_str();
8297            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
8298                panic!(
8299                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
8300                     must be Some({variant:?}) — the two halves of the round-trip \
8301                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
8302                     got None on wire byte-string {wire:?}"
8303                )
8304            });
8305            assert_eq!(
8306                parsed, variant,
8307                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
8308                 must round-trip to the same variant; got {parsed:?}"
8309            );
8310        }
8311    }
8312
8313    #[test]
8314    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
8315        // Fail-before-pass-after pin on the closed-set refusal
8316        // discipline of [`RestartPolicy::from_wire`]: every
8317        // byte-string outside the three-arm accept-set returns `None`
8318        // rather than silently collapsing onto the [`Default`]
8319        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
8320        // exercised here sweeps the load-bearing drift shapes: the
8321        // empty string (a stripped serde-attribute drift), all-
8322        // whitespace strings (the canonical text-editor accidental
8323        // padding shape), the kebab-case dispatcher-catalog identities
8324        // (`"permanent"` / `"temporary"` / `"transient"` — the
8325        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
8326        // accept-set, which parses the *other* axis of this enum's
8327        // two-axis split and must not leak into the `from_wire`
8328        // PascalCase-wire accept-set — a lowercase leak here would
8329        // silently accept the operator's kebab-case
8330        // dispatcher-catalog probe under the wire-axis parser and mis-
8331        // route a `:permanent` intent), the padded canonical scalar
8332        // (`" Permanent "`), the trailing-newline shapes
8333        // (`"Permanent\n"`), the uppercase-single-word forms
8334        // (`"PERMANENT"`), and neighboring-but-unknown arms
8335        // (`"Restart"` — the canonical typo direction toward the
8336        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
8337        //
8338        // Peer of the sibling
8339        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
8340        // (4eec29c) +
8341        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
8342        // (2aa6d23) +
8343        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
8344        // (18c7342) refusal pins on the peer closed-set typed-enum
8345        // axes.
8346        for bad in [
8347            "",
8348            " ",
8349            "\n",
8350            "\t",
8351            "permanent",
8352            "temporary",
8353            "transient",
8354            "PERMANENT",
8355            "TEMPORARY",
8356            "TRANSIENT",
8357            "Permanents",
8358            "Permanent ",
8359            " Permanent",
8360            " Transient ",
8361            "Permanent\n",
8362            "perma",
8363            "Trans",
8364            "OneForOne",
8365            "Restart",
8366            "?",
8367        ] {
8368            assert!(
8369                RestartPolicy::from_wire(bad).is_none(),
8370                "RestartPolicy::from_wire({bad:?}) must return None — the \
8371                 parser's accept-set is exactly the three RestartPolicy::as_str \
8372                 outputs (Permanent, Temporary, Transient), and this \
8373                 byte-string is outside that closed set"
8374            );
8375        }
8376    }
8377
8378    #[test]
8379    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
8380        // Fail-before-pass-after pin on the fourth path of the four-path
8381        // convergence: `from_wire` (the reverse projection) inverts the
8382        // `Serialize` derive's wire byte-string on every variant.
8383        // Together with the pre-existing three-path convergence
8384        // (`Display` + `as_str` + `Serialize` all resolve to the same
8385        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
8386        // pinned by
8387        // [`restart_policy_display_matches_serialized_wire_byte_string`])
8388        // this closes the round-trip: the wire byte-string the
8389        // `Serialize` derive emits parses back to the same variant
8390        // through `from_wire`, so any future serde-attribute or variant-
8391        // rename drift on the emit half now surfaces as a matched drift
8392        // on the parse half at caixa-core build time — the two halves
8393        // migrate as a unit through the lifted consts on any future
8394        // rename, and the round-trip cannot silently split.
8395        //
8396        // Peer of the sibling
8397        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8398        // (4eec29c) wire-format pin on
8399        // [`RestartStrategy::from_wire`] and the M3
8400        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8401        // (18c7342) wire-format pin on
8402        // [`crate::aplicacao::PlacementStrategy::from_wire`].
8403        for &variant in RestartPolicy::ALL {
8404            let wire = serde_json::to_string(&variant).unwrap();
8405            let unquoted = wire
8406                .strip_prefix('"')
8407                .and_then(|s| s.strip_suffix('"'))
8408                .expect("serialized RestartPolicy is a JSON string");
8409            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
8410                panic!(
8411                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
8412                     Serialize derive's wire byte-string for \
8413                     RestartPolicy::{variant:?} — the four-path convergence \
8414                     (Display + as_str + Serialize + from_wire) resolves through \
8415                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
8416                )
8417            });
8418            assert_eq!(
8419                parsed, variant,
8420                "RestartPolicy::from_wire of the Serialize derive's wire \
8421                 byte-string for RestartPolicy::{variant:?} must round-trip \
8422                 to the same variant; got {parsed:?}"
8423            );
8424        }
8425    }
8426
8427    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
8428    //
8429    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
8430    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
8431    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
8432    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
8433    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
8434    // the peer per-`:upgrade-from :from` axis. The three pins jointly
8435    // brace the accessor against every future silent detour that would
8436    // desynchronize it from the raw `.caixa` field access every consumer
8437    // previously open-coded.
8438
8439    #[test]
8440    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
8441        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
8442        // [`ChildSpec::nome`] must return the `:children :caixa` field
8443        // byte-for-byte across every DNS-1123-label value the upstream
8444        // [`crate::render::require_valid_dns_1123_label`] gate at
8445        // `SupervisorSpec::validate` admits. Peer of the sibling
8446        // `membro_nome_returns_caixa_byte_equal_across_permutations`
8447        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
8448        // substrate-primitive accessor must byte-equal the raw field
8449        // access verbatim across every author-declared value" discipline
8450        // extended to the M2 supervisor-tree per-`:children` arm. Pins
8451        // against a future silent detour that re-normalized the child
8452        // identity (an accidental `.to_lowercase()` — every `:children
8453        // :caixa` is validated as a DNS-1123 label upstream, so any
8454        // re-normalization is redundant + a drift surface between the
8455        // validator and the accessor), a namespace-prefix rewrite (an
8456        // accidental `format!("{namespace}/{caixa}")` per-CR
8457        // fully-qualified rewrite that didn't land on the peer axes), or
8458        // a per-cluster alias stamp the future wasm-operator's
8459        // hierarchical reconciliation scheduler authors on one consumer
8460        // without the others. Five values sweep the accept-set the
8461        // DNS-1123 gate upstream admits (short single-word / dashed /
8462        // v-suffixed / mixed-digit child names).
8463        for name in [
8464            "worker",
8465            "cache-server",
8466            "scratch-job",
8467            "orders-v2",
8468            "session-8080",
8469        ] {
8470            let c = ChildSpec {
8471                caixa: name.into(),
8472                versao: "^0.1".into(),
8473                restart: RestartPolicy::Permanent,
8474            };
8475            assert_eq!(
8476                c.nome(),
8477                name,
8478                "ChildSpec::nome must return :children :caixa verbatim \
8479                 (got {:?}, expected {name:?})",
8480                c.nome(),
8481            );
8482            assert_eq!(
8483                c.nome(),
8484                c.caixa.as_str(),
8485                "ChildSpec::nome must byte-equal the .caixa field access",
8486            );
8487        }
8488    }
8489
8490    #[test]
8491    fn child_spec_nome_borrows_from_caixa_storage() {
8492        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
8493        // `&str` slice that borrows from the typed slot's own [`String`]
8494        // storage — same-address invariant with `c.caixa.as_str()`. Pins
8495        // against a future silent detour that allocated a fresh `String`
8496        // (`self.caixa.clone()` in the body would type-check but silently
8497        // drop the borrow, and every downstream consumer that assumed
8498        // the returned slice outlives `&self` would break on a stale-
8499        // reference use-after-free — the [`crate::render::insert_first_seen`]
8500        // dedup key at [`SupervisorSpec::validate`], the
8501        // [`validate_no_self_supervision`] equality check against the
8502        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
8503        // borrow — each would silently misbehave if this accessor
8504        // produced a detached copy). Peer of the sibling
8505        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
8506        // M3 per-`:membros` axis and the
8507        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
8508        // first M2 slot scalar accessor.
8509        let c = ChildSpec {
8510            caixa: "worker".into(),
8511            versao: "^0.1".into(),
8512            restart: RestartPolicy::Permanent,
8513        };
8514        let name = c.nome();
8515        let caixa_slice = c.caixa.as_str();
8516        assert_eq!(
8517            name.as_ptr(),
8518            caixa_slice.as_ptr(),
8519            "ChildSpec::nome must borrow from the .caixa String's backing \
8520             storage — a fresh allocation here means the accessor no \
8521             longer names the substrate-primitive typed dispatch and \
8522             every downstream consumer would silently carry a detached \
8523             copy",
8524        );
8525        assert_eq!(
8526            name.len(),
8527            caixa_slice.len(),
8528            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
8529             as well as in address",
8530        );
8531    }
8532
8533    #[test]
8534    fn validate_gates_child_nome_through_lifted_accessor() {
8535        // Bilateral coherence pin: every `:children :caixa` that
8536        // [`SupervisorSpec::validate`] accepts is one
8537        // [`crate::render::require_valid_dns_1123_label`] accepts on the
8538        // accessor-projected value, and vice versa on the reject side.
8539        // This closes the "the validator reads through the accessor"
8540        // contract structurally — a future silent detour that made the
8541        // accessor return a different byte-string than the validator
8542        // gates against would surface here as a coverage mismatch, not
8543        // as an apply-time DNS-1123 rejection at
8544        // `metadata.name: Invalid value` far from the caixa.lisp source.
8545        // Peer of the M2 sibling
8546        // `validate_parses_prior_versao_through_lifted_accessor`
8547        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
8548        // `validate_membros` peer discipline.
8549        //
8550        // Accept-set sweep: five DNS-1123-label values the upstream gate
8551        // admits.
8552        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
8553            let s = SupervisorSpec {
8554                children: vec![ChildSpec {
8555                    caixa: ok_name.into(),
8556                    versao: "^0.1".into(),
8557                    restart: RestartPolicy::Permanent,
8558                }],
8559                ..SupervisorSpec::default()
8560            };
8561            s.validate().unwrap_or_else(|e| {
8562                panic!(
8563                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
8564                     (upstream DNS-1123 gate accepts it): got {e:?}",
8565                );
8566            });
8567            let c = ChildSpec {
8568                caixa: ok_name.into(),
8569                versao: "^0.1".into(),
8570                restart: RestartPolicy::Permanent,
8571            };
8572            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
8573                .unwrap_or_else(|()| {
8574                    panic!(
8575                        "require_valid_dns_1123_label must accept the accessor-projected \
8576                     :children :caixa {ok_name:?}",
8577                    );
8578                });
8579        }
8580        // Reject-set sweep: five DNS-1123-label-violating shapes the
8581        // upstream gate refuses (empty / uppercase / underscore / dot /
8582        // leading-hyphen). Every rejection at the validator must
8583        // correspond to a rejection when the accessor's projected value
8584        // is fed back through the shared gate.
8585        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
8586            let s = SupervisorSpec {
8587                children: vec![ChildSpec {
8588                    caixa: bad_name.into(),
8589                    versao: "^0.1".into(),
8590                    restart: RestartPolicy::Permanent,
8591                }],
8592                ..SupervisorSpec::default()
8593            };
8594            let err = s.validate().unwrap_err();
8595            assert!(
8596                matches!(
8597                    err,
8598                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
8599                ),
8600                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
8601                 via the DNS-1123 gate: got {err:?}",
8602            );
8603            let c = ChildSpec {
8604                caixa: bad_name.into(),
8605                versao: "^0.1".into(),
8606                restart: RestartPolicy::Permanent,
8607            };
8608            assert!(
8609                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
8610                    .is_err(),
8611                "require_valid_dns_1123_label must reject the accessor-projected \
8612                 :children :caixa {bad_name:?}",
8613            );
8614        }
8615    }
8616
8617    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
8618    //
8619    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
8620    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
8621    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
8622    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
8623    // trio on the peer per-`:children` `String`-carry axis. The three pins
8624    // jointly brace the accessor against every future silent detour that
8625    // would desynchronize it from the raw `.versao` field access the
8626    // requirement gate + error carrier previously open-coded.
8627    //
8628    // Closes the last unlifted per-`:children` `String`-carry axis: the
8629    // pair (`nome`, `versao_requirement`) now jointly projects the
8630    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
8631    // consumer that fans on per-child identity + version pin reads,
8632    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
8633    // pair discipline verbatim.
8634    #[test]
8635    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
8636        // The canonical per-`:children` child-`:versao`-scalar pin:
8637        // [`ChildSpec::versao_requirement`] must return the `:children
8638        // :versao` field byte-for-byte across every Cargo-shaped semver
8639        // requirement value the upstream
8640        // [`crate::render::require_valid_versao_requirement`] gate admits.
8641        // Peer of the sibling
8642        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
8643        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
8644        // substrate-primitive accessor must byte-equal the raw field
8645        // access verbatim across every author-declared value" discipline
8646        // extended to the M2 supervisor-tree per-`:children` arm. Pins
8647        // against a future silent detour that re-canonicalized the
8648        // requirement (an accidental `.to_string()` via
8649        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
8650        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
8651        // silently drifted the error carrier's quoted requirement away
8652        // from the source `caixa.lisp`, an accidental whitespace trim on
8653        // `"^ 0.1"` that no consumer ever produced from the field-access
8654        // side, an accidental per-cluster lacre-projected concrete-version
8655        // rewrite that didn't land on the peer requirement-gate call).
8656        // Five values sweep the accept-set the shared
8657        // [`crate::render::require_valid_versao_requirement`] gate admits
8658        // (caret / tilde / exact / wildcard / bare-major).
8659        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
8660            let c = ChildSpec {
8661                caixa: "worker".into(),
8662                versao: req.into(),
8663                restart: RestartPolicy::Permanent,
8664            };
8665            assert_eq!(
8666                c.versao_requirement(),
8667                req,
8668                "ChildSpec::versao_requirement must return :children :versao \
8669                 verbatim (got {:?}, expected {req:?})",
8670                c.versao_requirement(),
8671            );
8672            assert_eq!(
8673                c.versao_requirement(),
8674                c.versao.as_str(),
8675                "ChildSpec::versao_requirement must byte-equal the .versao \
8676                 field access",
8677            );
8678        }
8679    }
8680
8681    #[test]
8682    fn child_spec_versao_requirement_borrows_from_versao_storage() {
8683        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
8684        // return a `&str` slice that borrows from the typed slot's own
8685        // [`String`] storage — same-address invariant with
8686        // `c.versao.as_str()`. Pins against a future silent detour that
8687        // allocated a fresh `String` (`self.versao.clone()` in the body
8688        // would type-check but silently drop the borrow, and every
8689        // downstream consumer that assumed the returned slice outlives
8690        // `&self` — the [`crate::render::require_valid_versao_requirement`]
8691        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
8692        // `.to_string()` carrier's byte-length assumption — would silently
8693        // misbehave if this accessor produced a detached copy). Peer of
8694        // the sibling `child_spec_nome_borrows_from_caixa_storage`
8695        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
8696        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
8697        // pin on the peer per-`:membros` `:versao` axis.
8698        let c = ChildSpec {
8699            caixa: "worker".into(),
8700            versao: "^0.1".into(),
8701            restart: RestartPolicy::Permanent,
8702        };
8703        let req = c.versao_requirement();
8704        let versao_slice = c.versao.as_str();
8705        assert_eq!(
8706            req.as_ptr(),
8707            versao_slice.as_ptr(),
8708            "ChildSpec::versao_requirement must borrow from the .versao \
8709             String's backing storage — a fresh allocation here means the \
8710             accessor no longer names the substrate-primitive typed \
8711             dispatch and every downstream consumer would silently carry \
8712             a detached copy",
8713        );
8714        assert_eq!(
8715            req.len(),
8716            versao_slice.len(),
8717            "ChildSpec::versao_requirement and .versao.as_str() must \
8718             byte-equal in length as well as in address",
8719        );
8720    }
8721
8722    #[test]
8723    fn validate_gates_child_versao_through_lifted_accessor() {
8724        // Bilateral coherence pin: every `:children :versao` that
8725        // [`SupervisorSpec::validate`] accepts is one
8726        // [`crate::render::require_valid_versao_requirement`] accepts on
8727        // the accessor-projected value, and vice versa on the reject side.
8728        // This closes the "the validator reads through the accessor"
8729        // contract structurally — a future silent detour that made the
8730        // accessor return a different byte-string than the validator gates
8731        // against would surface here as a coverage mismatch, not as a
8732        // resolver-time semver-parse rejection at lacre-closure time far
8733        // from the caixa.lisp source. Peer of the sibling
8734        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
8735        // the per-`:children :caixa` axis and the M2
8736        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
8737        // on the peer per-`:upgrade-from :from` axis.
8738        //
8739        // Accept-set sweep: five Cargo-shaped semver requirement values
8740        // the upstream gate admits (caret / tilde / exact / wildcard /
8741        // bare-major).
8742        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
8743            let s = SupervisorSpec {
8744                children: vec![ChildSpec {
8745                    caixa: "worker".into(),
8746                    versao: ok_req.into(),
8747                    restart: RestartPolicy::Permanent,
8748                }],
8749                ..SupervisorSpec::default()
8750            };
8751            s.validate().unwrap_or_else(|e| {
8752                panic!(
8753                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
8754                     (upstream versao-requirement gate accepts it): got {e:?}",
8755                );
8756            });
8757            let c = ChildSpec {
8758                caixa: "worker".into(),
8759                versao: ok_req.into(),
8760                restart: RestartPolicy::Permanent,
8761            };
8762            crate::render::require_valid_versao_requirement(
8763                c.versao_requirement(),
8764                || (),
8765                |_reason| (),
8766            )
8767            .unwrap_or_else(|()| {
8768                panic!(
8769                    "require_valid_versao_requirement must accept the accessor-projected \
8770                     :children :versao {ok_req:?}",
8771                );
8772            });
8773        }
8774        // Reject-set sweep: five requirement-violating shapes the upstream
8775        // gate refuses. The empty string closes the empty-first arm of the
8776        // shared [`crate::render::require_valid_versao_requirement`]
8777        // cascade; the four non-empty arms exercise distinct semver-parse
8778        // failure modes the M3 peer per-`:membros` reject-set already pins
8779        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
8780        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
8781        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
8782        // shared parser routing means the same reject-set must fail
8783        // identically at the M2 supervisor-tree per-`:children` accessor
8784        // arm here. Every rejection at the validator must correspond to a
8785        // rejection when the accessor's projected value is fed back
8786        // through the shared gate.
8787        //
8788        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
8789        // `"not-a-semver"` are intentionally *not* in the reject-set: the
8790        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
8791        // and the identifier-tail arm's grammar admits some non-canonical
8792        // shapes — matching what the M3 peer test suite already documents
8793        // as the shared parser's accept-set edges.)
8794        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
8795            let s = SupervisorSpec {
8796                children: vec![ChildSpec {
8797                    caixa: "worker".into(),
8798                    versao: bad_req.into(),
8799                    restart: RestartPolicy::Permanent,
8800                }],
8801                ..SupervisorSpec::default()
8802            };
8803            let err = s.validate().unwrap_err();
8804            assert!(
8805                matches!(
8806                    err,
8807                    SupervisorError::EmptyChildVersion { .. }
8808                        | SupervisorError::ChildVersaoInvalid { .. }
8809                ),
8810                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
8811                 via the versao-requirement gate: got {err:?}",
8812            );
8813            let c = ChildSpec {
8814                caixa: "worker".into(),
8815                versao: bad_req.into(),
8816                restart: RestartPolicy::Permanent,
8817            };
8818            assert!(
8819                crate::render::require_valid_versao_requirement(
8820                    c.versao_requirement(),
8821                    || (),
8822                    |_reason| (),
8823                )
8824                .is_err(),
8825                "require_valid_versao_requirement must reject the accessor-projected \
8826                 :children :versao {bad_req:?}",
8827            );
8828        }
8829    }
8830
8831    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
8832    //
8833    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
8834    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
8835    // already project the `String`-carry `(caixa, versao)` fields; the
8836    // `Copy`-composite-enum `restart` field is the third and final axis).
8837    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
8838    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
8839    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
8840    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
8841    // strategy scalar accessor — same "one typed dispatch on the substrate
8842    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
8843    // extended onto the M2 supervisor-slot per-`:children` restart-decision
8844    // axis. The pin below covers the accessor's byte-equal projection
8845    // against the raw field access across every variant in the closed
8846    // accept-set (`Permanent`, `Transient`, `Temporary`).
8847
8848    #[test]
8849    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
8850        // The canonical per-`:children` restart-decision-policy-scalar
8851        // pin: [`ChildSpec::restart`] must return the `:children :restart`
8852        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
8853        // typed slot's own [`RestartPolicy`] storage across every variant
8854        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
8855        // Pins against a future silent detour that re-derived the policy
8856        // from a peer axis (an accidental fallback to
8857        // `if is_supervisor_child { Permanent } else { Temporary }` that
8858        // collapsed the child's kind axis into the restart discriminator),
8859        // a variant remap the operator authors on one consumer without the
8860        // other, or a stale-derive detour that substituted
8861        // [`RestartPolicy::default`] when the field held any explicit
8862        // variant (which would silently collapse the distinction between
8863        // "author explicitly declared `:restart Permanent`" and "author
8864        // omitted the slot and inherited the default" the future
8865        // per-cluster restart-decision override slot depends on).
8866        //
8867        // Peer of the sibling per-`:supervisor`
8868        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
8869        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
8870        // axis and the M3
8871        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
8872        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
8873        // — same "the substrate-primitive accessor must byte-equal the raw
8874        // field access verbatim across every author-declared value"
8875        // discipline extended onto the M2 supervisor-slot per-`:children`
8876        // restart-decision-policy axis, closing the last unlifted axis on
8877        // the per-`:children` [`ChildSpec`] type.
8878        for restart in [
8879            RestartPolicy::Permanent,
8880            RestartPolicy::Transient,
8881            RestartPolicy::Temporary,
8882        ] {
8883            let c = ChildSpec {
8884                caixa: "worker".into(),
8885                versao: "^0.1".into(),
8886                restart,
8887            };
8888            assert_eq!(
8889                c.restart(),
8890                restart,
8891                "ChildSpec::restart must return :children :restart \
8892                 verbatim (got {:?}, expected {restart:?})",
8893                c.restart(),
8894            );
8895            assert_eq!(
8896                c.restart(),
8897                c.restart,
8898                "ChildSpec::restart accessor and .restart field access \
8899                 must byte-equal — the accessor is the substrate-primitive \
8900                 typed dispatch every downstream per-child restart-\
8901                 decision consumer must route through",
8902            );
8903        }
8904    }
8905
8906    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
8907    //
8908    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
8909    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
8910    // distribution-strategy accessor discipline onto the M2 supervisor-slot
8911    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
8912    // scalar axis. The two pins below cover (1) the accessor's byte-equal
8913    // projection against the raw field access across every variant in the
8914    // closed accept-set, and (2) the two-consumer coherence between the
8915    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
8916    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
8917    // carrier's `estrategia:` field — peer of the sibling M3
8918    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
8919    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
8920    // pair on the per-`:placement` distribution-strategy axis.
8921
8922    #[test]
8923    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
8924        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
8925        // pin: [`SupervisorSpec::estrategia`] must return the
8926        // `:supervisor :estrategia` field verbatim as a
8927        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
8928        // [`RestartStrategy`] storage across every variant in the closed
8929        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
8930        // `SimpleOneForOne`). Pins against a future silent detour that
8931        // re-derived the strategy from a peer axis (an accidental
8932        // fallback to `if children.is_empty() { SimpleOneForOne } else {
8933        // OneForOne }` collapse that read the children-count axis into
8934        // the strategy discriminator), a variant remap the operator
8935        // authors on one consumer without the other, or a stale-derive
8936        // detour that substituted [`RestartStrategy::default`] when the
8937        // field held any explicit variant (which would silently collapse
8938        // the distinction between "author explicitly declared
8939        // `:estrategia OneForOne`" and "author omitted the slot and
8940        // inherited the default" the future per-cluster strategy override
8941        // slot depends on). Peer of the sibling M3
8942        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
8943        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
8944        // axis — same "the substrate-primitive accessor must byte-equal
8945        // the raw field access verbatim across every author-declared
8946        // value" discipline extended onto the M2 supervisor-slot
8947        // per-`:supervisor` sibling-restart-strategy axis.
8948        for &estrategia in RestartStrategy::ALL {
8949            // `SimpleOneForOne` requires `children.is_empty()`; the peer
8950            // three strategies require a non-empty static children list.
8951            // Build each shape coherently so the pin's fixture would
8952            // itself pass [`SupervisorSpec::validate`] once fed through
8953            // the sibling coherence pin below — the byte-equal projection
8954            // asserted here is a strictly weaker property (a `Copy` field
8955            // read) that does not depend on `validate` running, but
8956            // keeping the fixture validate-clean means a future extension
8957            // of the pin to exercise `validate` end-to-end does not have
8958            // to re-author the children shape.
8959            //
8960            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
8961            // shape partition through the [`gen_platform::IsVariant`]
8962            // derive-generated
8963            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
8964            // than the raw `matches!(estrategia, RestartStrategy::
8965            // SimpleOneForOne)` open-coded pattern-match — same closed-
8966            // set-typed-enum arm-discriminator dispatch discipline the
8967            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
8968            // convergence (915a934) extended onto its two paired positive
8969            // / negated `matches!` sites and the peer
8970            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
8971            // predicate convergence (766ec63) extended onto the M3 mesh-
8972            // slot per-`:placement` distribution-strategy discriminator
8973            // axis. See the sibling `round_trip_all_strategies` and the
8974            // peer `manifest::tests::
8975            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
8976            // fixture for the two peer sites the same lift closes on.
8977            let children = if estrategia.is_simple_one_for_one() {
8978                Vec::new()
8979            } else {
8980                vec![ChildSpec {
8981                    caixa: "worker".into(),
8982                    versao: "^0.1".into(),
8983                    restart: RestartPolicy::Permanent,
8984                }]
8985            };
8986            let s = SupervisorSpec {
8987                estrategia,
8988                children,
8989                ..SupervisorSpec::default()
8990            };
8991            assert_eq!(
8992                s.estrategia(),
8993                estrategia,
8994                "SupervisorSpec::estrategia must return :supervisor :estrategia \
8995                 verbatim (got {:?}, expected {estrategia:?})",
8996                s.estrategia(),
8997            );
8998            assert_eq!(
8999                s.estrategia(),
9000                s.estrategia,
9001                "SupervisorSpec::estrategia accessor and .estrategia field \
9002                 access must byte-equal — the accessor is the substrate-\
9003                 primitive typed dispatch every downstream sibling-restart-\
9004                 strategy consumer must route through",
9005            );
9006        }
9007    }
9008
9009    #[test]
9010    fn validate_reads_through_lifted_estrategia_accessor() {
9011        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
9012        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
9013        // dispatch (which reads through [`SupervisorSpec::estrategia`]
9014        // to fan across the strategy-arm shape-gate cascades) and the
9015        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
9016        // error carrier's `estrategia:` field (which reads through
9017        // [`SupervisorSpec::estrategia`] to name the strategy the empty
9018        // `:children` list was declared against) must both key off the
9019        // lifted accessor, so any future rebrand on the typed slot's
9020        // reader shape lands at exactly one place. Pins the two-site
9021        // coherence by exercising the `NoChildren` error surface end-to-
9022        // end across every non-`SimpleOneForOne` variant and asserting
9023        // the surfaced `estrategia:` field byte-equals the accessor's
9024        // return. Peer of the sibling M3
9025        // `validate_placement_reads_through_lifted_estrategia_accessor`
9026        // (921fe1b) three-consumer coherence pin on the per-`:placement`
9027        // distribution-strategy axis.
9028        for estrategia in [
9029            RestartStrategy::OneForOne,
9030            RestartStrategy::OneForAll,
9031            RestartStrategy::RestForOne,
9032        ] {
9033            let s = SupervisorSpec {
9034                estrategia,
9035                children: Vec::new(),
9036                ..SupervisorSpec::default()
9037            };
9038            let err = s.validate().unwrap_err();
9039            match err {
9040                SupervisorError::NoChildren { estrategia: e } => {
9041                    assert_eq!(
9042                        e,
9043                        s.estrategia(),
9044                        "NoChildren.estrategia must byte-equal \
9045                         SupervisorSpec::estrategia() — the empty-`:children` \
9046                         refusal reads through the lifted accessor",
9047                    );
9048                    assert_eq!(
9049                        e, estrategia,
9050                        "NoChildren.estrategia must carry the author-declared \
9051                         :supervisor :estrategia variant verbatim (got {e:?}, \
9052                         expected {estrategia:?})",
9053                    );
9054                }
9055                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
9056            }
9057        }
9058    }
9059
9060    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
9061    //
9062    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
9063    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
9064    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
9065    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
9066    // The two pins below cover (1) the accessor's byte-equal projection
9067    // against the raw field access across every representative value in
9068    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
9069    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
9070    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
9071    // zero-floor / cap composition — the validate gate and the accessor
9072    // must route through the same substrate-primitive typed dispatch, so
9073    // any future silent detour that had the accessor perform a
9074    // bounds-collapsing clamp would fail here at caixa-core build time.
9075    // Peer of the sibling M3
9076    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
9077    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
9078
9079    #[test]
9080    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
9081        // The canonical per-`:supervisor` restart-budget-count scalar pin:
9082        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
9083        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
9084        // typed slot's own `u32` storage, byte-equal to the raw field
9085        // access across every representative value in the accept-set —
9086        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
9087        // accept-set the surrounding [`SupervisorSpec::validate`] gate
9088        // carves out on the sibling `ZeroMaxRestarts` refusal),
9089        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
9090        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
9091        // (a past-the-guard sentinel that pins the accessor doesn't
9092        // perform a silent bounds-collapse into `1` on the zero arm —
9093        // validate rejects zero but the accessor must ship the raw slot
9094        // verbatim so a validate-time gate regression surfaces at the
9095        // emit boundary rather than being silently absorbed), `u32::MAX`
9096        // (a past-the-guard sentinel that pins the accessor doesn't
9097        // perform a silent bounds-collapse through
9098        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
9099        //
9100        // Peer of the sibling M3
9101        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
9102        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
9103        // required-scalar axis — same "the substrate-primitive accessor
9104        // must byte-equal the raw field access verbatim across every
9105        // value in the `u32` accept-set" discipline extended onto the M2
9106        // supervisor-slot per-`:supervisor` restart-budget-count axis.
9107        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
9108            let s = SupervisorSpec {
9109                max_restarts,
9110                ..SupervisorSpec::default()
9111            };
9112            assert_eq!(
9113                s.max_restarts(),
9114                max_restarts,
9115                "SupervisorSpec::max_restarts must return :supervisor \
9116                 :max-restarts verbatim (got {}, expected {max_restarts})",
9117                s.max_restarts(),
9118            );
9119            assert_eq!(
9120                s.max_restarts(),
9121                s.max_restarts,
9122                "SupervisorSpec::max_restarts accessor and .max_restarts \
9123                 field access must byte-equal — the accessor is the \
9124                 substrate-primitive typed dispatch every downstream \
9125                 restart-budget-count consumer must route through",
9126            );
9127        }
9128    }
9129
9130    #[test]
9131    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
9132        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
9133        // zero-floor + upper-cap bracket must key off
9134        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
9135        // field access. Structurally: a `SupervisorSpec { max_restarts:
9136        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
9137        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
9138        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
9139        // (with the offending count carried verbatim from the accessor
9140        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
9141        // lower boundary of the accept-set) plus a `SupervisorSpec {
9142        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
9143        // boundary) must pass validate. The four together jointly pin the
9144        // accessor + validate-gate composition: any future silent detour
9145        // that had the accessor return a fresh `1` on the zero arm (a
9146        // `.max_restarts().max(1)` collapse) would silently absorb the
9147        // `ZeroMaxRestarts` refusal at the accessor boundary and the
9148        // validate gate would accept a struct-literal `SupervisorSpec {
9149        // max_restarts: 0, .. }` — the composition pin catches that at
9150        // caixa-core build time.
9151        //
9152        // Peer of the sibling M3
9153        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
9154        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
9155        // composition axis — same "the validate / shape-gate predicate
9156        // must route through the substrate-primitive typed dispatch"
9157        // discipline extended onto the peer M2 supervisor-slot
9158        // required-`u32` composition axis.
9159        let child = ChildSpec {
9160            caixa: "worker".into(),
9161            versao: "^0.1".into(),
9162            restart: RestartPolicy::Permanent,
9163        };
9164        // Zero-floor arm.
9165        let s = SupervisorSpec {
9166            max_restarts: 0,
9167            children: vec![child.clone()],
9168            ..SupervisorSpec::default()
9169        };
9170        assert_eq!(
9171            s.validate().unwrap_err(),
9172            SupervisorError::ZeroMaxRestarts,
9173            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
9174             — the accessor and the validate gate must route through the \
9175             same substrate-primitive typed dispatch on the zero-floor arm",
9176        );
9177        // Cap arm — the surfaced `max_restarts:` field must byte-equal
9178        // the accessor's return so a future rebrand on the accessor
9179        // lands in the diagnostic without a coordinated rewrite.
9180        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
9181        let s = SupervisorSpec {
9182            max_restarts: over_cap,
9183            children: vec![child.clone()],
9184            ..SupervisorSpec::default()
9185        };
9186        match s.validate().unwrap_err() {
9187            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
9188                assert_eq!(
9189                    max_restarts,
9190                    s.max_restarts(),
9191                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
9192                     SupervisorSpec::max_restarts() — the cap-arm refusal \
9193                     reads through the lifted accessor",
9194                );
9195                assert_eq!(
9196                    max_restarts, over_cap,
9197                    "MaxRestartsExceedsCap.max_restarts must carry the \
9198                     author-declared :supervisor :max-restarts value \
9199                     verbatim (got {max_restarts}, expected {over_cap})",
9200                );
9201            }
9202            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
9203        }
9204        // Lower + upper accept-set boundaries.
9205        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
9206            let s = SupervisorSpec {
9207                max_restarts,
9208                children: vec![child.clone()],
9209                ..SupervisorSpec::default()
9210            };
9211            assert!(
9212                s.validate().is_ok(),
9213                "validate must accept max_restarts == {max_restarts} \
9214                 (an accept-set boundary of \
9215                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
9216            );
9217        }
9218    }
9219
9220    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
9221    //
9222    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
9223    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
9224    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
9225    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
9226    // supervisor-slot per-`:supervisor` restart-intensity-denominator
9227    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
9228    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
9229    // per-`:supervisor` scalar-value axis. The three pins below cover
9230    // (1) the accessor's byte-equal projection against the raw field
9231    // access across every representative value in the `Option<Duration>`
9232    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
9233    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
9234    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
9235    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
9236    // `if let Some(w) = self.restart_window() { … }` bracket-arm
9237    // composition — the validate gate and the accessor must route through
9238    // the same substrate-primitive typed dispatch, so any future silent
9239    // detour that had the accessor perform a bounds-collapsing clamp
9240    // would fail here at caixa-core build time, and (3) the accessor's
9241    // by-copy idempotence pin — the returned `Option<Duration>` must
9242    // outlive `&self` and two successive calls must return byte-equal
9243    // values. Peer of the sibling M2
9244    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
9245    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
9246    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
9247    // (7073d0f) pin on the per-`:politicas :timeout` axis.
9248
9249    #[test]
9250    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
9251        // The canonical per-`:supervisor` restart-intensity-denominator
9252        // scalar pin: [`SupervisorSpec::restart_window`] must return the
9253        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
9254        // `Option<Duration>`, `Copy`-projected from the typed slot's own
9255        // `Option<Duration>` storage, byte-equal to the raw field access
9256        // across every representative value in the accept-set — `None`
9257        // (the "never reset — every restart across the supervisor's
9258        // lifetime counts against the sibling `:max-restarts` budget"
9259        // sentinel the field's own docstring names and the peer
9260        // `validate_accepts_none_restart_window` pin locks in on the
9261        // [`SupervisorSpec::validate`] entry-side),
9262        // `Some(Duration::from_millis(1))` (the structural minimum a
9263        // validated `:restart-window` may carry, the integer-millisecond
9264        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
9265        // everything sub-ms; `Duration::ZERO` is separately rejected by
9266        // [`SupervisorError::RestartWindowZero`]),
9267        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
9268        // surrounding [`SupervisorSpec::validate`] gate carves out on the
9269        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
9270        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
9271        // accessor doesn't perform a silent bounds-collapse into `None` on
9272        // the zero-Duration arm — validate rejects zero but the accessor
9273        // must ship the raw slot verbatim so a validate-time gate
9274        // regression surfaces at the emit boundary rather than being
9275        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
9276        // sentinel that pins the accessor doesn't perform a silent
9277        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
9278        // return path).
9279        //
9280        // Peer of the sibling M2
9281        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
9282        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
9283        // sibling M3
9284        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
9285        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
9286        // substrate-primitive accessor must byte-equal the raw field
9287        // access verbatim across every value in the `Option<Duration>`
9288        // accept-set" discipline extended onto the M2 supervisor-slot
9289        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
9290        // silent detour that re-derived the restart-window from a peer
9291        // axis (an accidental `.max_restarts.into()` collapse that read
9292        // the restart-budget-count as a duration — the two axes serve
9293        // different halves of the `MaxIntensity / Period` restart-
9294        // intensity ratio, and confusing them silently inverts the
9295        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
9296        // "zero means never reset" collapse (the canonical
9297        // `Option<Duration>` → `Duration` collapse footgun the
9298        // [`SupervisorError::RestartWindowZero`] validate arm guards on
9299        // the peer zero-floor axis; a zero period either trips on the
9300        // first failure or never trips depending on operator
9301        // interpretation, neither of which is the author's "never reset"
9302        // intent that `None` expresses structurally), or a per-arm
9303        // variant swap that landed on one consumer without the other.
9304        for restart_window in [
9305            None,
9306            Some(Duration::from_millis(1)),
9307            Some(SUPERVISOR_RESTART_WINDOW_MAX),
9308            Some(Duration::ZERO),
9309            Some(Duration::MAX),
9310        ] {
9311            let s = SupervisorSpec {
9312                restart_window,
9313                ..SupervisorSpec::default()
9314            };
9315            assert_eq!(
9316                s.restart_window(),
9317                restart_window,
9318                "SupervisorSpec::restart_window must return :supervisor \
9319                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
9320                s.restart_window(),
9321            );
9322            assert_eq!(
9323                s.restart_window(),
9324                s.restart_window,
9325                "SupervisorSpec::restart_window accessor and \
9326                 .restart_window field access must byte-equal — the \
9327                 accessor is the substrate-primitive typed dispatch every \
9328                 downstream restart-intensity-denominator consumer must \
9329                 route through",
9330            );
9331        }
9332    }
9333
9334    #[test]
9335    fn validate_restart_window_bracket_arm_routes_through_accessor() {
9336        // Composition pin: [`SupervisorSpec::validate`]'s
9337        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
9338        // zero-floor + integer-millisecond canonical-form + upper-cap
9339        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
9340        // the raw `.restart_window` field access. Structurally: a
9341        // `SupervisorSpec { restart_window: None, .. }` must pass the
9342        // arm gate structurally (the `if let Some(_)` shape returns
9343        // early on the `None` arm — the accessor and the validate gate
9344        // must agree on `None → skip the bracket cascade` so an authored
9345        // `:restart-window ()` structurally routes through the "never
9346        // reset" sentinel path), a `SupervisorSpec { restart_window:
9347        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
9348        // refusal exactly, a `SupervisorSpec { restart_window:
9349        // Some(Duration::from_micros(1500)), .. }` must surface the
9350        // `RestartWindowNotCanonical` refusal exactly (with the offending
9351        // duration carried verbatim from the accessor return), a
9352        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
9353        // + Duration::from_millis(1)), .. }` must surface the
9354        // `RestartWindowExceedsCap` refusal exactly (with the offending
9355        // duration carried verbatim from the accessor return), and a
9356        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
9357        // .. }` (the lower boundary of the accept-set) plus a
9358        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
9359        // .. }` (the upper boundary) must pass validate. The six together
9360        // jointly pin the accessor + validate-gate composition: any future
9361        // silent detour that had the accessor return a fresh `None` on any
9362        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
9363        // collapse) would silently absorb the `RestartWindowZero` refusal
9364        // at the accessor boundary and the validate gate would accept a
9365        // struct-literal `SupervisorSpec { restart_window:
9366        // Some(Duration::ZERO), .. }` — the composition pin catches that
9367        // at caixa-core build time.
9368        //
9369        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
9370        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
9371        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
9372        // accessor-composition pin on the per-`:politicas :timeout` axis —
9373        // same "the validate / shape-gate predicate must route through
9374        // the substrate-primitive typed dispatch" discipline extended
9375        // onto the peer M2 supervisor-slot optional-`Duration` axis.
9376        let child = ChildSpec {
9377            caixa: "worker".into(),
9378            versao: "^0.1".into(),
9379            restart: RestartPolicy::Permanent,
9380        };
9381        // None arm — must not surface any :restart-window-shaped refusal;
9382        // the `if let Some(_)` bracket returns early on `None` structurally.
9383        let s = SupervisorSpec {
9384            restart_window: None,
9385            children: vec![child.clone()],
9386            ..SupervisorSpec::default()
9387        };
9388        assert!(
9389            s.validate().is_ok(),
9390            "validate must accept restart_window: None (the never-reset \
9391             sentinel) — the `if let Some(_)` bracket returns early on \
9392             the None arm and the accessor must agree",
9393        );
9394        // Zero-floor arm.
9395        let s = SupervisorSpec {
9396            restart_window: Some(Duration::ZERO),
9397            children: vec![child.clone()],
9398            ..SupervisorSpec::default()
9399        };
9400        assert_eq!(
9401            s.validate().unwrap_err(),
9402            SupervisorError::RestartWindowZero,
9403            "validate must reject restart_window == Some(Duration::ZERO) \
9404             with RestartWindowZero — the accessor and the validate gate \
9405             must route through the same substrate-primitive typed \
9406             dispatch on the zero-floor arm",
9407        );
9408        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
9409        // byte-equal the accessor's return so a future rebrand on the
9410        // accessor lands in the diagnostic without a coordinated rewrite.
9411        let sub_ms = Duration::from_micros(1500);
9412        let s = SupervisorSpec {
9413            restart_window: Some(sub_ms),
9414            children: vec![child.clone()],
9415            ..SupervisorSpec::default()
9416        };
9417        match s.validate().unwrap_err() {
9418            SupervisorError::RestartWindowNotCanonical { window } => {
9419                assert_eq!(
9420                    Some(window),
9421                    s.restart_window(),
9422                    "RestartWindowNotCanonical.window must byte-equal \
9423                     SupervisorSpec::restart_window().unwrap() — the \
9424                     non-canonical-arm refusal reads through the lifted \
9425                     accessor",
9426                );
9427                assert_eq!(
9428                    window, sub_ms,
9429                    "RestartWindowNotCanonical.window must carry the \
9430                     author-declared :supervisor :restart-window value \
9431                     verbatim (got {window:?}, expected {sub_ms:?})",
9432                );
9433            }
9434            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
9435        }
9436        // Cap arm — the surfaced `window:` field must byte-equal the
9437        // accessor's return.
9438        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
9439        let s = SupervisorSpec {
9440            restart_window: Some(over_cap),
9441            children: vec![child.clone()],
9442            ..SupervisorSpec::default()
9443        };
9444        match s.validate().unwrap_err() {
9445            SupervisorError::RestartWindowExceedsCap { window } => {
9446                assert_eq!(
9447                    Some(window),
9448                    s.restart_window(),
9449                    "RestartWindowExceedsCap.window must byte-equal \
9450                     SupervisorSpec::restart_window().unwrap() — the \
9451                     cap-arm refusal reads through the lifted accessor",
9452                );
9453                assert_eq!(
9454                    window, over_cap,
9455                    "RestartWindowExceedsCap.window must carry the \
9456                     author-declared :supervisor :restart-window value \
9457                     verbatim (got {window:?}, expected {over_cap:?})",
9458                );
9459            }
9460            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
9461        }
9462        // Lower + upper accept-set boundaries.
9463        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
9464            let s = SupervisorSpec {
9465                restart_window: Some(restart_window),
9466                children: vec![child.clone()],
9467                ..SupervisorSpec::default()
9468            };
9469            assert!(
9470                s.validate().is_ok(),
9471                "validate must accept restart_window == Some({restart_window:?}) \
9472                 (an accept-set boundary of \
9473                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
9474            );
9475        }
9476    }
9477
9478    #[test]
9479    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
9480        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
9481        // `Option<Duration>` by copy — `Duration` is `Copy` (so
9482        // `Option<Duration>` is `Copy`) and the accessor must return by
9483        // value, not by reference. Peer of the sibling M2
9484        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
9485        // per-`:limits :wall-clock` axis and the sibling M3
9486        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
9487        // per-`:politicas :timeout` axis, extended onto the peer M2
9488        // supervisor-slot `Option<Duration>` copy-invariant shape — the
9489        // accessor's returned `Option<Duration>` must outlive `&self`
9490        // (multiple calls must return equal values from a dropped-`&self`
9491        // copy, since the returned Option carries no borrow), and calling
9492        // the accessor twice on the same SupervisorSpec must yield the
9493        // same `Option<Duration>` verbatim (idempotent, no side effects
9494        // on `&self`).
9495        //
9496        // Pins against a future silent detour that returned
9497        // `Option<&Duration>` (which would type-check but silently break
9498        // every downstream caller — the future wasm-operator's
9499        // per-supervisor restart-intensity counter consumes `Duration` by
9500        // value and `&Duration` would fold to a detached copy at the call
9501        // site), an accidental `Option::as_ref()` projection
9502        // (`self.restart_window.as_ref()` would also type-check but
9503        // return `Option<&Duration>`), or a one-arm-only accessor that
9504        // reads `Some(*w)` in the Some arm but reads a fresh
9505        // `Default::default()` (which would collapse to `Duration::ZERO`,
9506        // not `None`) in the None arm — a footgun the
9507        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
9508        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
9509        // requires `Period > 0` and `None` structurally expresses "never
9510        // reset" instead.
9511        for restart_window in [
9512            None,
9513            Some(Duration::from_millis(1)),
9514            Some(Duration::from_secs(60)),
9515            Some(SUPERVISOR_RESTART_WINDOW_MAX),
9516        ] {
9517            let s = SupervisorSpec {
9518                restart_window,
9519                ..SupervisorSpec::default()
9520            };
9521            let first = s.restart_window();
9522            let second = s.restart_window();
9523            assert_eq!(
9524                first, second,
9525                "SupervisorSpec::restart_window must be idempotent — two \
9526                 successive calls on the same &self must return the \
9527                 same Option<Duration>",
9528            );
9529            assert_eq!(
9530                first, restart_window,
9531                "SupervisorSpec::restart_window must return :supervisor \
9532                 :restart-window verbatim by copy — got {first:?}, \
9533                 expected {restart_window:?}",
9534            );
9535        }
9536    }
9537
9538    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
9539    //
9540    // The [`SupervisorSpec::children`] accessor lift is the seed of the
9541    // slice-return (`&[T]`) accessor discipline on the substrate — the four
9542    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
9543    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
9544    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
9545    // access at the time of this seed, and inherit this pin family's
9546    // discipline as future compounding runs migrate their consumers. The
9547    // three pins below cover (1) the accessor's byte-equal projection
9548    // against the raw field access across the empty / singleton / cohort
9549    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
9550    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
9551    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
9552    // consumer routing through the accessor on both arms, and (3) the
9553    // per-child validate loop's traversal reading the same slice-view the
9554    // accessor projects. Peer of the sibling M2
9555    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
9556    // two-consumer coherence pin on the per-`:supervisor`
9557    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
9558    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
9559
9560    #[test]
9561    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
9562        // The canonical per-`:supervisor` static-child-list scalar-shape
9563        // pin: [`SupervisorSpec::children`] must return the `:supervisor
9564        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
9565        // slice-view over the same backing buffer the raw
9566        // `self.children.as_slice()` field access borrows from, byte-
9567        // equal across every representative fixture in the accept-set —
9568        // the empty slice (the `SimpleOneForOne`-arm sentinel),
9569        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
9570        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
9571        // with the peer three restart-policy variants in play).
9572        //
9573        // Pins against a future silent detour that returned
9574        // `&Vec<ChildSpec>` (which would type-check but leak the
9575        // storage-side `Vec`'s grow/push/reserve surface no consumer of
9576        // the typed view reaches for), a fresh-allocated
9577        // `Vec<ChildSpec>` copy (which would type-check via a coercion
9578        // but silently break every downstream caller that relied on the
9579        // slice sharing the backing buffer's identity), or an
9580        // out-of-order or length-drifted projection (which would silently
9581        // split the per-child validate loop's traversal input from the
9582        // paired partition-dispatch `.is_empty()` probe's input).
9583        //
9584        // Peer of the sibling
9585        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
9586        // (eafb619) `Copy`-composite-enum byte-equal pin on the
9587        // per-`:supervisor` sibling-restart-strategy axis, extended onto
9588        // the per-`:supervisor` static-child-list `Vec`-carry axis.
9589        let fixtures: Vec<Vec<ChildSpec>> = vec![
9590            Vec::new(),
9591            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
9592            vec![
9593                child("worker", "^0.1", RestartPolicy::Permanent),
9594                child("cache-server", "^0.1", RestartPolicy::Transient),
9595            ],
9596            vec![
9597                child("worker", "^0.1", RestartPolicy::Permanent),
9598                child("cache-server", "^0.1", RestartPolicy::Transient),
9599                child("scratch-job", "^0.1", RestartPolicy::Temporary),
9600            ],
9601        ];
9602        for children in fixtures {
9603            let s = SupervisorSpec {
9604                children: children.clone(),
9605                ..SupervisorSpec::default()
9606            };
9607            assert_eq!(
9608                s.children(),
9609                children.as_slice(),
9610                "SupervisorSpec::children must return :supervisor \
9611                 :children verbatim (got {:?}, expected {:?})",
9612                s.children(),
9613                children.as_slice(),
9614            );
9615            assert_eq!(
9616                s.children(),
9617                s.children.as_slice(),
9618                "SupervisorSpec::children accessor and \
9619                 .children.as_slice() field access must byte-equal — \
9620                 the accessor is the substrate-primitive typed \
9621                 dispatch every downstream static-child-list consumer \
9622                 must route through",
9623            );
9624            assert_eq!(
9625                s.children().len(),
9626                s.children.len(),
9627                "SupervisorSpec::children().len() must byte-equal \
9628                 self.children.len() — a length-drift would silently \
9629                 split the paired partition-dispatch `.is_empty()` \
9630                 probe input from the per-child validate loop's \
9631                 traversal input",
9632            );
9633        }
9634    }
9635
9636    #[test]
9637    fn validate_reads_through_lifted_children_accessor() {
9638        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
9639        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
9640        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
9641        // when the accessor projects a non-empty slice under a
9642        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
9643        // `self.children().is_empty()` refusal probe (which must trip
9644        // [`SupervisorError::NoChildren`] when the accessor projects the
9645        // empty slice under any peer estrategia), and the per-child
9646        // validate loop's `for child in self.children()` traversal
9647        // (which must reach every entry in the same order the accessor
9648        // projects) must all key off the lifted accessor, so any future
9649        // rebrand on the typed slot's reader shape lands at exactly one
9650        // place. Pins the three-site coherence by exercising each
9651        // production consumer end-to-end: (1) the
9652        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
9653        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
9654        // refusal under the empty slice + non-`SimpleOneForOne`
9655        // estrategia across every peer variant, and (3) the per-child
9656        // duplicate-detection surface fires on the second entry of a
9657        // two-child cohort that shares a `:caixa` name (which requires
9658        // the loop to reach both entries — a first-entry-only projection
9659        // would silently pass since the dedup HashSet has room for the
9660        // first insert).
9661        //
9662        // Peer of the sibling M2
9663        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
9664        // two-consumer coherence pin on the per-`:supervisor`
9665        // sibling-restart-strategy axis, extended onto the
9666        // per-`:supervisor` static-child-list `Vec`-carry axis.
9667
9668        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
9669        // `SimpleOneForOne` estrategia must trip
9670        // `SimpleOneForOneWithStaticChildren`.
9671        let s = SupervisorSpec {
9672            estrategia: RestartStrategy::SimpleOneForOne,
9673            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
9674            ..SupervisorSpec::default()
9675        };
9676        assert_eq!(
9677            s.validate().unwrap_err(),
9678            SupervisorError::SimpleOneForOneWithStaticChildren,
9679            "SimpleOneForOne + non-empty children must trip \
9680             SimpleOneForOneWithStaticChildren — the accessor projects \
9681             a non-empty slice, and the SimpleOneForOne-arm refusal \
9682             probe reads through the lifted accessor",
9683        );
9684        assert!(
9685            !s.children().is_empty(),
9686            "the SimpleOneForOne-arm refusal input must be a non-empty \
9687             slice per the accessor's projection",
9688        );
9689
9690        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
9691        // under any peer estrategia must trip `NoChildren`.
9692        for estrategia in [
9693            RestartStrategy::OneForOne,
9694            RestartStrategy::OneForAll,
9695            RestartStrategy::RestForOne,
9696        ] {
9697            let s = SupervisorSpec {
9698                estrategia,
9699                children: Vec::new(),
9700                ..SupervisorSpec::default()
9701            };
9702            match s.validate().unwrap_err() {
9703                SupervisorError::NoChildren { estrategia: e } => {
9704                    assert_eq!(
9705                        e, estrategia,
9706                        "NoChildren.estrategia must carry the author-\
9707                         declared :supervisor :estrategia variant \
9708                         verbatim (got {e:?}, expected {estrategia:?})",
9709                    );
9710                }
9711                other => panic!(
9712                    "expected NoChildren, got {other:?} for \
9713                     estrategia={estrategia:?}"
9714                ),
9715            }
9716            assert!(
9717                s.children().is_empty(),
9718                "the non-SimpleOneForOne-arm refusal input must be the \
9719                 empty slice per the accessor's projection",
9720            );
9721        }
9722
9723        // (3) Per-child validate loop: a two-child cohort that shares a
9724        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
9725        // reach both entries through the accessor.
9726        let s = SupervisorSpec {
9727            estrategia: RestartStrategy::OneForOne,
9728            children: vec![
9729                child("worker", "^0.1", RestartPolicy::Permanent),
9730                child("worker", "^0.2", RestartPolicy::Transient),
9731            ],
9732            ..SupervisorSpec::default()
9733        };
9734        match s.validate().unwrap_err() {
9735            SupervisorError::DuplicateChildCaixa { caixa } => {
9736                assert_eq!(
9737                    caixa, "worker",
9738                    "DuplicateChildCaixa.caixa must carry the shared \
9739                     child `:caixa` name verbatim",
9740                );
9741            }
9742            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
9743        }
9744        assert_eq!(
9745            s.children().len(),
9746            2,
9747            "the per-child validate loop's traversal input must be a \
9748             two-element slice per the accessor's projection",
9749        );
9750    }
9751
9752    // Shared helper for the M2 per-`:children` per-slot-gate ≡
9753    // `validate` equivalence pins: builds an `OneForOne`-estrategia
9754    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
9755    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
9756    // bracket all pass cleanly so the sole failing surface is the
9757    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
9758    // pins the two-altitude equivalence on the paired probe.
9759    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
9760        let s = SupervisorSpec {
9761            estrategia: RestartStrategy::OneForOne,
9762            children,
9763            ..SupervisorSpec::default()
9764        };
9765        let via_gate = s.validate_children().unwrap_err();
9766        let via_validate = s.validate().unwrap_err();
9767        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
9768        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
9769        assert_eq!(
9770            via_gate, via_validate,
9771            "per-slot gate ≡ validate() must discriminate the same \
9772             refusal shape",
9773        );
9774    }
9775
9776    #[test]
9777    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
9778        // Fail-before-pass-after equivalence pin on the M2
9779        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
9780        // convergence — sibling of the M3 mesh-slot
9781        // `validate_membros_*` / `validate_contratos_*` /
9782        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
9783        // peer per-entry axes. Sweeps four of the five refusal shapes
9784        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
9785        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
9786        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
9787        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
9788        // duplicate-`:caixa` fan-out. Companion pin
9789        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
9790        // covers `ChildVersaoInvalid` (whose parser-owned reason string
9791        // needs pattern-matching, not equality) and the clean-pass
9792        // canonical fixture; together the two pins guarantee the
9793        // per-slot gate and `validate` discriminate the same set on
9794        // every per-child-covered input.
9795        assert_validate_children_matches_gate(
9796            vec![child("", "^0.1", RestartPolicy::Permanent)],
9797            &SupervisorError::EmptyChildName,
9798        );
9799        assert_validate_children_matches_gate(
9800            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
9801            &SupervisorError::ChildCaixaInvalid {
9802                caixa: "Worker".into(),
9803                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
9804            },
9805        );
9806        assert_validate_children_matches_gate(
9807            vec![child("worker", "", RestartPolicy::Permanent)],
9808            &SupervisorError::EmptyChildVersion {
9809                caixa: "worker".into(),
9810            },
9811        );
9812        assert_validate_children_matches_gate(
9813            vec![
9814                child("worker", "^0.1", RestartPolicy::Permanent),
9815                child("worker", "^0.2", RestartPolicy::Transient),
9816            ],
9817            &SupervisorError::DuplicateChildCaixa {
9818                caixa: "worker".into(),
9819            },
9820        );
9821    }
9822
9823    #[test]
9824    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
9825        // Second half of the two-altitude equivalence pin — covers the
9826        // one refusal shape whose reason string is parser-owned
9827        // (`ChildVersaoInvalid`, whose reason comes from the shared
9828        // [`crate::version::parse_requirement`] impl and may drift) and
9829        // the clean-pass canonical fixture. Sibling pin
9830        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
9831        // covers the four equality-comparable refusal shapes.
9832        let s_bad_versao = SupervisorSpec {
9833            estrategia: RestartStrategy::OneForOne,
9834            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
9835            ..SupervisorSpec::default()
9836        };
9837        let via_gate = s_bad_versao.validate_children().unwrap_err();
9838        let via_validate = s_bad_versao.validate().unwrap_err();
9839        match (&via_gate, &via_validate) {
9840            (
9841                SupervisorError::ChildVersaoInvalid {
9842                    caixa: cg,
9843                    versao: vg,
9844                    ..
9845                },
9846                SupervisorError::ChildVersaoInvalid {
9847                    caixa: cv,
9848                    versao: vv,
9849                    ..
9850                },
9851            ) => {
9852                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
9853                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
9854                assert_eq!(cv, "worker", "validate() :caixa carrier");
9855                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
9856            }
9857            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
9858        }
9859        assert_eq!(
9860            via_gate, via_validate,
9861            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
9862        );
9863
9864        let s_ok = SupervisorSpec {
9865            estrategia: RestartStrategy::OneForOne,
9866            children: vec![
9867                child("worker-a", "^0.1", RestartPolicy::Permanent),
9868                child("worker-b", "~0.2.3", RestartPolicy::Transient),
9869                child("collector", "*", RestartPolicy::Temporary),
9870            ],
9871            ..SupervisorSpec::default()
9872        };
9873        s_ok.validate_children()
9874            .expect("per-slot gate must accept the clean-pass fixture");
9875        s_ok.validate()
9876            .expect("validate() must accept the clean-pass fixture");
9877    }
9878
9879    #[test]
9880    fn validate_children_is_self_contained_on_children_slot() {
9881        // Self-containment pin: [`SupervisorSpec::validate_children`]
9882        // resolves the per-child cascade against `&self` alone, without
9883        // depending on the peer `:estrategia`/`:max-restarts`/
9884        // `:restart-window` gates having run first — same posture the M3
9885        // peer per-slot gates carry (`validate_membros`,
9886        // `validate_contratos`, `validate_entrada`, `validate_placement`,
9887        // routing through their own oracles rather than borrowing state
9888        // threaded down from `validate`). A future consumer that reaches
9889        // the per-slot gate directly on a spec whose peer slots would
9890        // fail `validate` still surfaces the per-child refusal, not the
9891        // peer refusal.
9892        //
9893        // Construct a spec whose `:max-restarts` is `0` (which would
9894        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
9895        // the partition-dispatch) and whose `:children` carries a
9896        // `DuplicateChildCaixa` shape: the per-slot gate called directly
9897        // must surface `DuplicateChildCaixa`, proving it does not depend
9898        // on the peer `:max-restarts` gate running first.
9899        let s = SupervisorSpec {
9900            estrategia: RestartStrategy::OneForOne,
9901            max_restarts: 0,
9902            restart_window: Some(Duration::from_secs(60)),
9903            children: vec![
9904                child("worker", "^0.1", RestartPolicy::Permanent),
9905                child("worker", "^0.2", RestartPolicy::Transient),
9906            ],
9907        };
9908        assert_eq!(
9909            s.validate_children().unwrap_err(),
9910            SupervisorError::DuplicateChildCaixa {
9911                caixa: "worker".into(),
9912            },
9913            "per-slot gate must resolve per-child refusal directly against \
9914             `&self` — a dependency on the peer `:max-restarts` gate \
9915             running first would surface ZeroMaxRestarts here instead",
9916        );
9917        // The peer gate is still the surface `validate` reaches — pin
9918        // the ordering to establish that `validate_children` truly runs
9919        // last in `validate`'s dispatch, so a direct call bypasses the
9920        // peer gates on any spec whose per-child cascade would fail.
9921        assert_eq!(
9922            s.validate().unwrap_err(),
9923            SupervisorError::ZeroMaxRestarts,
9924            "validate() must surface the peer `:max-restarts` gate before \
9925             reaching the per-child cascade — this pins the dispatch \
9926             ordering the per-slot gate's self-containment complements",
9927        );
9928    }
9929
9930    #[test]
9931    fn child_spec_restart_accessor_is_const_fn() {
9932        // The [`ChildSpec::restart`] per-`:children` restart-decision-
9933        // policy `Copy`-return scalar accessor is declared
9934        // `#[must_use] pub const fn` — matching the sibling M2
9935        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
9936        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
9937        // both converted in this commit), the sibling M2
9938        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
9939        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
9940        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
9941        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
9942        // `Copy`-return `pub const fn` scalar accessors on the sibling
9943        // M3 surface. Pin the `const`-eval posture here so a future
9944        // accidental downgrade to non-`const` (an added runtime helper
9945        // reachable only from a non-`const` context, an
9946        // `Option<RestartPolicy>`-shape migration on the per-child
9947        // restart-decision axis once heterogeneous per-cluster
9948        // restart-policy overlays land that would silently drop the
9949        // `const` qualifier, a manual hand-rolled shadow) trips at
9950        // caixa-core build time rather than surfacing as a downstream
9951        // `const`-context regression far from the declaration.
9952        //
9953        // Same shape as the sibling M3
9954        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
9955        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
9956        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
9957        // accessor axis — the load-bearing witness lives in the
9958        // module-scope `const fn` wrapper `restart_via_const_fn` below:
9959        // a body that calls [`ChildSpec::restart`] under a `const fn`
9960        // signature is well-formed only when the callee is itself
9961        // `const fn`, so any future accidental downgrade of
9962        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
9963        // build time (const-eval E0015 `cannot call non-const method`),
9964        // strictly stronger than a runtime `assert!(CONST)` and
9965        // side-stepping the destructor-in-const restriction that
9966        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
9967        // items on `ChildSpec`'s `String` carriers.
9968        //
9969        // The runtime body sweeps every closed-set [`RestartPolicy`]
9970        // arm and asserts the wrapped and direct dispatches agree.
9971        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
9972            c.restart()
9973        }
9974        for restart in [
9975            RestartPolicy::Permanent,
9976            RestartPolicy::Transient,
9977            RestartPolicy::Temporary,
9978        ] {
9979            let c = ChildSpec {
9980                caixa: "worker".into(),
9981                versao: "^0.1".into(),
9982                restart,
9983            };
9984            assert_eq!(
9985                restart_via_const_fn(&c),
9986                c.restart(),
9987                "const-fn-wrapped and direct dispatch on \
9988                 ChildSpec::restart must agree for {restart:?}",
9989            );
9990            assert_eq!(
9991                c.restart(),
9992                restart,
9993                "ChildSpec::restart must return the storage-side \
9994                 RestartPolicy verbatim for {restart:?} (a violation \
9995                 means the accessor stopped being a raw field-return \
9996                 copy)",
9997            );
9998        }
9999    }
10000
10001    #[test]
10002    fn supervisor_spec_estrategia_accessor_is_const_fn() {
10003        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
10004        // sibling-restart-strategy `Copy`-return scalar accessor is
10005        // declared `#[must_use] pub const fn` — matching the sibling M2
10006        // per-`:children` [`ChildSpec::restart`] (pinned by
10007        // [`child_spec_restart_accessor_is_const_fn`] above, both
10008        // converted in this commit), the sibling M2 per-`:supervisor`
10009        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
10010        // accessor already `pub const fn`, and mirroring the peer M3
10011        // mesh-slot per-`:placement`
10012        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
10013        // `pub const fn` scalar accessor whose method-name discipline
10014        // the [`SupervisorSpec::estrategia`] method was authored to
10015        // match. Pin the `const`-eval posture here so a future
10016        // accidental downgrade to non-`const` (an added runtime helper
10017        // reachable only from a non-`const` context, an
10018        // `Option<RestartStrategy>`-shape migration once the substrate
10019        // grows per-cluster strategy overlays that would silently drop
10020        // the `const` qualifier, a manual hand-rolled shadow) trips at
10021        // caixa-core build time rather than surfacing as a downstream
10022        // `const`-context regression far from the declaration.
10023        //
10024        // Same shape as the sibling
10025        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
10026        // load-bearing witness lives in the module-scope `const fn`
10027        // wrapper `estrategia_via_const_fn` below: a body that calls
10028        // [`SupervisorSpec::estrategia`] under a `const fn` signature
10029        // is well-formed only when the callee is itself `const fn`,
10030        // side-stepping the destructor-in-const restriction that would
10031        // otherwise block a direct
10032        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
10033        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
10034        // carriers.
10035        //
10036        // The runtime body sweeps every closed-set [`RestartStrategy`]
10037        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
10038        // direct dispatches agree.
10039        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
10040            s.estrategia()
10041        }
10042        for &estrategia in RestartStrategy::ALL {
10043            let s = SupervisorSpec {
10044                estrategia,
10045                max_restarts: 5,
10046                restart_window: Some(Duration::from_secs(60)),
10047                children: Vec::new(),
10048            };
10049            assert_eq!(
10050                estrategia_via_const_fn(&s),
10051                s.estrategia(),
10052                "const-fn-wrapped and direct dispatch on \
10053                 SupervisorSpec::estrategia must agree for {estrategia:?}",
10054            );
10055            assert_eq!(
10056                s.estrategia(),
10057                estrategia,
10058                "SupervisorSpec::estrategia must return the storage-side \
10059                 RestartStrategy verbatim for {estrategia:?} (a violation \
10060                 means the accessor stopped being a raw field-return \
10061                 copy)",
10062            );
10063        }
10064    }
10065
10066    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
10067    // macro definition (see the paired doc-block above the macro
10068    // definition) — every generated `<ctor>(caixa: &str) -> Self`
10069    // constructor folds the uniform `Self::<Variant> { caixa:
10070    // caixa.to_string() }` one-field struct-literal onto one substrate
10071    // primitive. The three per-variant equivalence pins below
10072    // (fail-before-pass-after by construction — a byte-mismatched macro
10073    // arm would trip its equivalence pin first) lock each generated
10074    // constructor to its struct-literal peer under `PartialEq`, so
10075    // every wire-up in [`SupervisorSpec::validate_children`] and
10076    // [`validate_no_self_supervision`] on that variant produces a
10077    // byte-equal `SupervisorError` to the pre-lift open-coded
10078    // struct-literal. The cross-axis pin that follows (non-default
10079    // caixa name) routes the sole constructor input axis through
10080    // `.to_string()`, so the fold does not silently collapse onto a
10081    // fixed name.
10082    //
10083    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
10084    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
10085    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
10086    // `missing_entry_ctor_matches_struct_literal_wrap` /
10087    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
10088    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
10089    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
10090    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
10091    // on the six sibling ctor families the recent trajectory closed
10092    // on the peer `LayoutError` / `AplicacaoError` envelopes.
10093
10094    #[test]
10095    fn empty_child_version_ctor_matches_struct_literal_wrap() {
10096        assert_eq!(
10097            SupervisorError::empty_child_version("worker"),
10098            SupervisorError::EmptyChildVersion {
10099                caixa: "worker".to_string(),
10100            },
10101            "generated empty_child_version ctor must produce byte-equal \
10102             SupervisorError to the open-coded struct-literal wrap on the \
10103             same &str fixture",
10104        );
10105    }
10106
10107    #[test]
10108    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
10109        assert_eq!(
10110            SupervisorError::duplicate_child_caixa("worker"),
10111            SupervisorError::DuplicateChildCaixa {
10112                caixa: "worker".to_string(),
10113            },
10114            "generated duplicate_child_caixa ctor must produce byte-equal \
10115             SupervisorError to the open-coded struct-literal wrap on the \
10116             same &str fixture",
10117        );
10118    }
10119
10120    #[test]
10121    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
10122        assert_eq!(
10123            SupervisorError::child_supervises_self("orquestra"),
10124            SupervisorError::ChildSupervisesSelf {
10125                caixa: "orquestra".to_string(),
10126            },
10127            "generated child_supervises_self ctor must produce byte-equal \
10128             SupervisorError to the open-coded struct-literal wrap on the \
10129             same &str fixture",
10130        );
10131    }
10132
10133    // Per-variant equivalence pins for the two lifted
10134    // [`SupervisorError::child_caixa_invalid`] /
10135    // [`SupervisorError::child_versao_invalid`] inherent constructors
10136    // (fail-before-pass-after by construction — a byte-mismatched ctor body
10137    // would trip its equivalence pin first). Each pins the ctor output to
10138    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
10139    // in [`SupervisorSpec::validate_children`] on the two variants
10140    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
10141    // struct-literal on the same scalar fixtures. Peers of the sibling
10142    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
10143    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
10144    // the peer `AplicacaoError` envelope's
10145    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
10146
10147    #[test]
10148    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
10149        let caixa = "Worker";
10150        let reason = "sample reason text";
10151        assert_eq!(
10152            SupervisorError::child_caixa_invalid(caixa, reason),
10153            SupervisorError::ChildCaixaInvalid {
10154                caixa: caixa.to_string(),
10155                reason: reason.to_string(),
10156            },
10157            "lifted child_caixa_invalid ctor must produce byte-equal \
10158             SupervisorError to the open-coded struct-literal wrap on the \
10159             same (&str, reason) fixture",
10160        );
10161    }
10162
10163    #[test]
10164    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
10165        let caixa = "worker";
10166        let versao = "not-a-req";
10167        let reason = "sample reason text";
10168        assert_eq!(
10169            SupervisorError::child_versao_invalid(caixa, versao, reason),
10170            SupervisorError::ChildVersaoInvalid {
10171                caixa: caixa.to_string(),
10172                versao: versao.to_string(),
10173                reason: reason.to_string(),
10174            },
10175            "lifted child_versao_invalid ctor must produce byte-equal \
10176             SupervisorError to the open-coded struct-literal wrap on the \
10177             same (&str, &str, reason) fixture",
10178        );
10179    }
10180
10181    #[test]
10182    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
10183        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
10184        // against a `&str`-literal vs. `format!(…)` reason input to pin
10185        // both constructors accept the `impl Into<String>` bound
10186        // uniformly, so neither wire-up site drifts under a per-arm
10187        // wrapper transformation on the caller-side `reason` axis. Peer
10188        // of the sibling
10189        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
10190        // sweep on the peer `AplicacaoError` envelope.
10191        let via_literal = "literal reason text";
10192        let via_format = format!("{} reason text", "literal");
10193        assert_eq!(
10194            SupervisorError::child_caixa_invalid("Worker", via_literal),
10195            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
10196        );
10197        assert_eq!(
10198            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
10199            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
10200        );
10201    }
10202
10203    #[test]
10204    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
10205        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
10206        // &str`) through a non-default fixture name against every
10207        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
10208        // so any wrapper-side lowercase / trim / truncate / re-order on
10209        // the `caixa.to_string()` sole-field construction surfaces
10210        // here rather than at a downstream diagnostic-shape mismatch.
10211        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
10212        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
10213        // through_to_string` / `contrato_target_ctors_route_edge_
10214        // triple_through_verbatim` / `contrato_empty_pair_ctors_
10215        // route_edge_pair_through_verbatim` cross-axis routing pins on
10216        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
10217        // here onto the `SupervisorError` `{ caixa: String }` envelope
10218        // so every substrate-primitive ctor family in caixa-core
10219        // guarantees the sole-field construction routes the caller's
10220        // `&str` through `.to_string()` verbatim.
10221        let name = "cache-v2";
10222        assert_eq!(
10223            SupervisorError::empty_child_version(name),
10224            SupervisorError::EmptyChildVersion {
10225                caixa: name.to_string(),
10226            },
10227        );
10228        assert_eq!(
10229            SupervisorError::duplicate_child_caixa(name),
10230            SupervisorError::DuplicateChildCaixa {
10231                caixa: name.to_string(),
10232            },
10233        );
10234        assert_eq!(
10235            SupervisorError::child_supervises_self(name),
10236            SupervisorError::ChildSupervisesSelf {
10237                caixa: name.to_string(),
10238            },
10239        );
10240    }
10241
10242    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
10243    //
10244    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
10245    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
10246    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
10247    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
10248    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
10249    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
10250    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
10251    // / silent constant-substitution on any one variant surfaces here rather
10252    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
10253    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
10254    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
10255    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
10256    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
10257    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
10258    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
10259    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
10260    #[test]
10261    fn no_children_ctor_matches_struct_literal_wrap() {
10262        let estrategia = RestartStrategy::OneForAll;
10263        assert_eq!(
10264            SupervisorError::no_children(estrategia),
10265            SupervisorError::NoChildren { estrategia },
10266            "generated no_children ctor must produce byte-equal \
10267             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
10268             on the same `Copy`-`RestartStrategy` fixture",
10269        );
10270    }
10271
10272    #[test]
10273    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
10274        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
10275        assert_eq!(
10276            SupervisorError::max_restarts_exceeds_cap(max_restarts),
10277            SupervisorError::MaxRestartsExceedsCap { max_restarts },
10278            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
10279             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
10280             struct-literal wrap on the same `Copy`-`u32` fixture",
10281        );
10282    }
10283
10284    #[test]
10285    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
10286        let window = Duration::from_micros(1_500);
10287        assert_eq!(
10288            SupervisorError::restart_window_not_canonical(window),
10289            SupervisorError::RestartWindowNotCanonical { window },
10290            "generated restart_window_not_canonical ctor must produce \
10291             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
10292             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
10293        );
10294    }
10295
10296    #[test]
10297    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
10298        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
10299        assert_eq!(
10300            SupervisorError::restart_window_exceeds_cap(window),
10301            SupervisorError::RestartWindowExceedsCap { window },
10302            "generated restart_window_exceeds_cap ctor must produce \
10303             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
10304             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
10305        );
10306    }
10307
10308    #[test]
10309    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
10310        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
10311        // constructor input axis through a non-default `Copy` fixture against
10312        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
10313        // side silent `.into()` / silent constant-substitution / silent field
10314        // re-name away from the canonical `estrategia | max_restarts | window`
10315        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
10316        // axis silently rerouted through some other `Copy` coercion, surfaces
10317        // here rather than at a downstream per-`:supervisor` diagnostic-shape
10318        // drift. Peer of the sibling
10319        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
10320        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
10321        // envelope's per-`:politicas` per-axis ctor family, extended here onto
10322        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
10323        // variant family folded onto a substrate primitive.
10324        //
10325        // Fixtures picked out of each variant's accept-set boundary rather
10326        // than the default value so a silent constant-substitution to a per-
10327        // variant sentinel surfaces here on the structural-equality assertion.
10328        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
10329        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
10330        // isn't the `SimpleOneForOne` arm the sibling
10331        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
10332        // `max_restarts` fixture picks an above-cap magnitude the cap arm
10333        // rejects; the two `Duration` fixtures pick the sub-millisecond and
10334        // above-cap ends of the `:restart-window` canonical-form + cap
10335        // bracket respectively.
10336        let estrategia = RestartStrategy::RestForOne;
10337        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
10338        let sub_ms = Duration::from_micros(1_500);
10339        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
10340        assert_eq!(
10341            SupervisorError::no_children(estrategia),
10342            SupervisorError::NoChildren { estrategia },
10343        );
10344        assert_eq!(
10345            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
10346            SupervisorError::MaxRestartsExceedsCap {
10347                max_restarts: above_cap_restarts,
10348            },
10349        );
10350        assert_eq!(
10351            SupervisorError::restart_window_not_canonical(sub_ms),
10352            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
10353        );
10354        assert_eq!(
10355            SupervisorError::restart_window_exceeds_cap(above_hour),
10356            SupervisorError::RestartWindowExceedsCap { window: above_hour },
10357        );
10358    }
10359
10360    #[test]
10361    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
10362        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
10363        // generated ctor `const fn` so a caller can pin a `SupervisorError`
10364        // at compile time — the same zero-runtime-work property the pre-lift
10365        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
10366        // its `Copy`-pass-through construction path (no `.to_string()` /
10367        // `.into()` allocation, no branching). If any future edit silently
10368        // drops the `const` qualifier from the macro body the per-arm `const`
10369        // bindings below fail to compile, which surfaces the regression at
10370        // the substrate-primitive definition rather than at some downstream
10371        // consumer that had come to rely on the `const`-constructibility.
10372        // Peer of the sibling
10373        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
10374        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
10375        // per-`:politicas` per-axis ctor family.
10376        const NO_CHILDREN: SupervisorError =
10377            SupervisorError::no_children(RestartStrategy::OneForAll);
10378        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
10379        const WINDOW_NC: SupervisorError =
10380            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
10381        const WINDOW_CAP: SupervisorError =
10382            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
10383        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
10384        assert!(matches!(
10385            MAX_RESTARTS_CAP,
10386            SupervisorError::MaxRestartsExceedsCap { .. }
10387        ));
10388        assert!(matches!(
10389            WINDOW_NC,
10390            SupervisorError::RestartWindowNotCanonical { .. }
10391        ));
10392        assert!(matches!(
10393            WINDOW_CAP,
10394            SupervisorError::RestartWindowExceedsCap { .. }
10395        ));
10396    }
10397}