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/// Per-child restart policy.
534///
535/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
536#[derive(
537    Serialize,
538    Deserialize,
539    Debug,
540    Clone,
541    Copy,
542    PartialEq,
543    Eq,
544    Hash,
545    gen_platform::TypedDispatcher,
546    gen_platform::Discriminant,
547    gen_platform::IsVariant,
548    gen_platform::FromStrKind,
549)]
550pub enum RestartPolicy {
551    /// Always restart the child, regardless of how it died. Used for
552    /// long-running services that must always be up.
553    Permanent,
554    /// Never restart. Used for one-shot work whose completion is
555    /// itself the success signal (`oneShot` triggers map here).
556    Temporary,
557    /// Restart only when the child died *abnormally* (non-zero exit
558    /// or unhandled exception). A clean exit completes the child.
559    Transient,
560}
561
562impl Default for RestartPolicy {
563    fn default() -> Self {
564        // Route the [`Default for RestartPolicy`] impl's return arm through
565        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
566        // `pub const` rather than a raw `Self::Permanent` arm — one source
567        // of truth for the Erlang/OTP-canonical `permanent` worker-child
568        // default across the two production consumers that currently
569        // dispatch on it (this impl at the [`RestartPolicy::default`] call
570        // and the serde-side `#[serde(default)]` on
571        // [`ChildSpec::restart`] that resolves an author-omitted
572        // `:children :restart` slot through `RestartPolicy::default()`).
573        // Peer of the sibling per-`:supervisor` axis
574        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
575        // route (95ffacc) — the two impls now share one substrate-primitive
576        // lift discipline, so any future coherent rebrand of the OTP-shape
577        // supervisor+child default set migrates through typed constants in
578        // lockstep instead of splitting a lifted supervisor half against
579        // an open-coded child half. Pinned by
580        // `restart_policy_default_routes_through_lifted_default` +
581        // `child_spec_serde_default_restart_routes_through_lifted_default`
582        // in the tests module.
583        SUPERVISOR_CHILD_RESTART_DEFAULT
584    }
585}
586
587impl RestartPolicy {
588    /// Exhaustive iteration surface for every consumer that walks the
589    /// closed three-arm [`RestartPolicy`] discriminator set (the future
590    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
591    /// per-child admission-webhook rejection body naming the accepted-
592    /// `:restart` list, a future `feira supervisor --restart …` CLI
593    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
594    /// over the slice, the future `feira app graph` per-child restart
595    /// column, any future round-trip fuzz harness that sweeps every
596    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
597    /// theory
598    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
599    /// might reach for once the three canonical OTP restart policies
600    /// stop covering the substrate's discovered load-shape) extends
601    /// this slice as one edit and every consumer picks up the new entry
602    /// by construction; the compiler-checked exhaustiveness on the
603    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
604    /// is the build-time guarantee that no arm forgets to grow.
605    ///
606    /// Peer of the sibling closed-set typed enums'
607    /// [`RestartStrategy::ALL`] (4eec29c) /
608    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
609    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
610    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
611    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
612    /// surfaces — the sixth (and the third and final M2 OTP-shape)
613    /// closed-set typed enum on the caixa surface to converge onto the
614    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
615    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
616    /// sibling-restart-strategy axis; this closes the per-child
617    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
618    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
619
620    /// Canonical PascalCase discriminator scalar this variant serializes
621    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
622    /// arms return the paired
623    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
624    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
625    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
626    /// constants so every substrate consumer that dispatches on the
627    /// per-child restart-decision policy (the future wasm-operator's
628    /// per-child post-exit restart-decision branch, the future M4
629    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
630    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
631    /// reconciliation scheduler's per-child-policy fan-out) reads the
632    /// same byte-string the `Serialize` derive emits — the pin test in
633    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
634    /// asserts the two paths agree, peer of the M2
635    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
636    /// sibling-restart-strategy axis and the M3
637    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
638    /// per-Aplicacao distribution-strategy axis — the third of three
639    /// OTP-shaped closed-enum discriminator axes on the caixa typed
640    /// surface to converge onto the same three-path-convergence
641    /// (`Serialize` derive → `as_str` helper → lifted constant)
642    /// drift-detection posture.
643    #[must_use]
644    pub const fn as_str(self) -> &'static str {
645        match self {
646            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
647            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
648            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
649        }
650    }
651
652    /// Substrate-canonical reverse projection on the `:children :restart`
653    /// closed-set axis — parses the `PascalCase` discriminator scalar
654    /// back to the typed variant, or `None` when `s` is outside the
655    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
656    /// the same lifted
657    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
658    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
659    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
660    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
661    /// of the round-trip migrate through one caixa-core edit on any
662    /// future arm addition.
663    ///
664    /// Prior to this lift the substrate carried only the forward
665    /// `Self → &str` projection on the OTP per-child restart-policy
666    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
667    /// impl routed through it, the `Serialize` derive that emits the
668    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
669    /// plus the kebab-case dispatcher-catalog identity via
670    /// [`Self::discriminant`] — every non-serde consumer that wanted to
671    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
672    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
673    /// "Transient" => …, _ => … }` cascade that expressed no
674    /// compile-time link back to the typed variant's canonical lifted
675    /// constant. A future variant rename or per-arm serde-attribute
676    /// drift would silently split the wire byte-string one non-serde
677    /// consumer parsed from the one the emitter wrote, with the failure
678    /// surfacing at the operator's reconcile posture (a `:temporary`
679    /// `oneShot` child being restarted on clean exit, treating the
680    /// successful-completion signal as failure and re-running the
681    /// completion-terminal one-shot indefinitely; a `:transient` child
682    /// that clean-exited being restarted, masking the clean-completion
683    /// contract) far from the rebrand commit and with no field naming
684    /// the drift.
685    ///
686    /// Distinct axis from the [`std::str::FromStr`] impl the
687    /// [`gen_platform::FromStrKind`] derive already installs on this
688    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
689    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
690    /// `"transient"` — the inverse of [`Self::discriminant`]), while
691    /// this method inverts the `PascalCase` wire byte-string
692    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
693    /// catalog identity live in kebab-case (where every peer catalog
694    /// identifier already lives) without forcing a wire-format rename
695    /// on the tatara-lisp author surface (`:restart Permanent`,
696    /// `PascalCase`) — the same two-axis distinction the sibling
697    /// [`RestartStrategy::from_wire`] (4eec29c) /
698    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
699    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
700    /// carry on their peer closed-set typed-enum wire round-trips.
701    ///
702    /// Same closed-set-reverse-projection discipline the sibling
703    /// [`RestartStrategy::from_wire`] (4eec29c) /
704    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
705    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
706    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
707    /// carry on the peer wire-side `str → Self` axes — extended onto
708    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
709    /// sixth substrate-side closed-set typed enum (and the third and
710    /// final OTP-shape closed-enum discriminator axis) to converge on
711    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
712    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
713    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
714    /// derive already installs on the sibling kebab-case axis. Returns
715    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
716    /// shapes: the caller picks the diagnostic form appropriate for
717    /// its use site.
718    #[must_use]
719    pub fn from_wire(s: &str) -> Option<Self> {
720        match s {
721            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
722            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
723            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
724            _ => None,
725        }
726    }
727}
728
729/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
730/// pretty-printed byte-string every consumer that formats the policy as
731/// user-facing text lands on (the future wasm-operator's per-child
732/// post-exit restart-decision diagnostic line, the future `feira app
733/// graph` per-child restart column, the future M4
734/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
735/// admission-webhook rejection body) reaches for the same lifted
736/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
737/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
738/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
739/// wire-format `Serialize` derive already emits under
740/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
741/// [`RestartPolicy::as_str`] helper already returns.
742///
743/// Pre-convergence the two paths structurally disagreed — the
744/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
745/// route (now retired here) sent [`std::fmt::Display`] through the
746/// gen-platform discriminant catalog string, which arrives kebab-case as
747/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
748/// (whose variant names each collapse to their own lowercase form under
749/// the kebab-case transform), while the wire format ran as `PascalCase`
750/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
751/// serde derive. Every consumer that formatted the policy for a
752/// diagnostic line, a graph column, or a rejection body under
753/// `format!("{v}")` therefore landed under a different byte-string than
754/// the wire format the operator's per-child-policy dispatch keyed off —
755/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
756/// diagnostic quoting `"permanent"` while the wire scalar the operator
757/// probed was `"Permanent"`) surfaced as a confused correlate at
758/// operator-log time far from the two-declaration site.
759///
760/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
761/// path: every `format!("{v}")` call reaches the same lifted
762/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
763/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
764/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
765/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
766/// byte-string per variant. A future variant rename or
767/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
768/// exactly one place, structurally.
769///
770/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
771/// (from `#[derive(gen_platform::Discriminant)]`) still returns
772/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
773/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
774/// registration keys the catalog off the same kebab identity. The two
775/// naming worlds now live on separate typed methods (`Display` /
776/// `as_str` for the wire byte-string, `discriminant` for the catalog
777/// identity) rather than sharing one `Display` route that structurally
778/// disagrees with the wire format.
779///
780/// Pin tests
781/// [`tests::restart_policy_display_routes_through_as_str_helper`]
782/// and
783/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
784/// assert the three paths agree byte-for-byte on every variant, so a
785/// future variant rename or per-arm serde attribute drift is a build
786/// error visible at caixa-core test time, not a silent per-consumer
787/// dispatch miss at apply / reconcile time.
788///
789/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
790/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
791/// and the sibling [`RestartStrategy`] `Display` impl on the
792/// per-supervisor sibling-restart-strategy axis — same three-path-
793/// convergence discipline, extended to close the third and final of
794/// three OTP-shaped closed-enum discriminator axes on the caixa typed
795/// surface.
796impl std::fmt::Display for RestartPolicy {
797    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
798        f.write_str(self.as_str())
799    }
800}
801
802/// Substrate-canonical [`AsRef<str>`] projection on the M2
803/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
804/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
805/// scalar accessor the paired [`std::fmt::Display`] impl and the
806/// un-`rename`d [`serde::Serialize`] derive already key off, so any
807/// future consumer that binds a [`RestartPolicy`] through the
808/// standard-library `impl AsRef<str>` bound (a future
809/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
810/// composes the emitted `PascalCase` wire scalar into a
811/// [`std::process::Command::arg`] shell-out of the future
812/// wasm-operator's per-child admission gate, a per-child structured-
813/// log recorder on the future `caixa-operator`'s hierarchical
814/// reconciliation surface that accepts `impl AsRef<str>` at the
815/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
816/// lookup keyed on the restart-policy wire byte through
817/// `map.get::<str>(policy.as_ref())` on a future per-policy
818/// dispatch table) reaches the paired
819/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
820/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
821/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
822/// lifted-const through one substrate-primitive dispatch rather
823/// than an open-coded `.as_str()` projection at every wire-up.
824///
825/// Peer of the sibling [`std::fmt::Display`] impl on the same
826/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
827/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
828/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
829/// byte-string per instance by construction. A future variant rename
830/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
831/// enum reaches every one of the three paths (plus the wire-format
832/// `Serialize` derive that already routes through the same lifted
833/// const) through exactly one caixa-core edit.
834///
835/// Same "route the trait impl through the substrate-primitive
836/// accessor" discipline the sibling [`crate::CaixaVersion`]
837/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
838/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
839/// the axis onto the paired per-child-restart-decision-policy
840/// sibling on the same M2 `:supervisor` slot (the second M2
841/// OTP-shape closed-set typed enum to converge onto the standard-
842/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
843/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
844/// primitive so a caller who has one has both; before this lift,
845/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
846/// [`AsRef<str>`] impl the convention names.
847///
848/// Pinned load-bearing by
849/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
850/// (byte-parity pin against [`RestartPolicy::as_str`] across the
851/// three-arm closed set) and
852/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
853/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
854/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
855/// arm) — any future silent detour that routes the impl through a
856/// divergent projection (a per-arm inline `match self { … }`
857/// re-inlining that opens a compile-time link to the un-lifted
858/// arm-literal, a swap onto the kebab-case
859/// [`gen_platform::Discriminant`] catalog identity that would
860/// collide the wire axis with the dispatcher-catalog axis) trips at
861/// caixa-core test time under `assert_eq!` rather than at a
862/// downstream `impl AsRef<str>`-bound consumer's silent split.
863impl AsRef<str> for RestartPolicy {
864    fn as_ref(&self) -> &str {
865        self.as_str()
866    }
867}
868
869/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
870/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
871/// byte-for-byte through the paired substrate-primitive
872/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
873/// consumer that binds a `PascalCase` `:children :restart` wire
874/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
875/// axis (a future [`caixa-feira`] `feira supervisor --restart
876/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
877/// `let restart: RestartPolicy = s.try_into()?`, a future
878/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
879/// `spec.children[*].restart: String` field through
880/// `RestartPolicy::try_from(&s)?`, a generic
881/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
882/// set typed enums) reaches the same three-arm accept-set the sibling
883/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
884/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
885/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
886/// … }` cascade whose arm-set has no compile-time link back to the
887/// substrate primitive.
888///
889/// Complements the pre-existing forward-projection triple
890/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
891/// with the paired trait-idiomatic reverse-projection axis: Rust-side
892/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
893/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
894/// caller who can project *out to* a `&str` can also project *in from*
895/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
896/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
897/// lint the sibling method-named [`RestartPolicy::from_wire`] would
898/// trigger under a `FromStr` impl and to avoid colliding with the
899/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
900/// already installs on the paired *kebab-case dispatcher-catalog* axis
901/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
902/// inverse of [`Self::discriminant`]) — this impl closes the trait-
903/// idiomatic reverse axis on the *`PascalCase` wire* half without
904/// disturbing either the method-named `from_wire` shape every sibling
905/// closed-set typed enum on the substrate already carries or the
906/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
907/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
908///
909/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
910/// `Option<Self>` return-shape's deliberate deferral of error typing: the
911/// caller picks the diagnostic form appropriate for its use site (a
912/// future `feira supervisor --restart` arg-parse composes its own
913/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
914/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
915/// wraps the `Err(())` outcome with the accepted-set enumeration for
916/// operator diagnostics, a `Result::map_err` at the call site lifts the
917/// unit-error to a per-verb error type). Same shape the peer
918/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
919/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
920/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
921/// their peer closed-set typed enums' reverse projections.
922///
923/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
924/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
925/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
926/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
927/// might reach for once the three canonical OTP restart policies stop
928/// covering the substrate's discovered load-shape) grows the trait-
929/// idiomatic axis by construction — one caixa-core edit on
930/// [`RestartPolicy::from_wire`] extends both the method-named reverse
931/// projection every existing consumer keys off and the trait-idiomatic
932/// reverse projection this impl exposes, without a coordinated rewrite
933/// across every future `TryFrom<&str>`-bound consumer's arm-set.
934///
935/// Extends the substrate-wide closed-set-enum reverse-projection family
936/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
937/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
938/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
939/// closed-enum discriminator axis on the caixa surface — the paired
940/// per-child `:children :restart` closed set the future wasm-operator's
941/// hierarchical reconciliation scheduler's per-child post-exit
942/// restart-decision branch keys off end-to-end.
943///
944/// Pinned load-bearing by
945/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
946/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
947/// three-arm accept-set),
948/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
949/// (rejection witness against silent accept-set widening), and
950/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
951/// (cross-axis partition pin locking the trait and method-named
952/// projections onto one accept-set).
953impl TryFrom<&str> for RestartPolicy {
954    type Error = ();
955
956    fn try_from(s: &str) -> Result<Self, Self::Error> {
957        Self::from_wire(s).ok_or(())
958    }
959}
960
961/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
962/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
963/// byte-for-byte through the paired substrate-primitive
964/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
965/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
966/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
967/// &str` with `'static` lifetime, so the trait's return-type promise is
968/// upheld structurally without a [`String::leak`] cast or a per-arm inline
969/// literal.
970///
971/// Every future consumer that specifically needs `&'static str` lifetime
972/// bytes on the per-child restart-decision axis (a
973/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
974/// arm's typing demands `&'static str`, a
975/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
976/// on the future M4 admission-webhook rejection body where the
977/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
978/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
979/// or error formatter that requires the `'static` bound) reaches the same
980/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
981/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
982/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
983/// primitive dispatch rather than an open-coded per-arm literal cascade
984/// whose arm-set has no compile-time link back to the substrate primitive.
985///
986/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
987/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
988/// the second (and second-of-two-in-M2) closed-set typed enum on the
989/// caixa surface to converge onto the paired trait-idiomatic forward-
990/// projection axis. With this lift the paired per-child
991/// `:children :restart` closed-set typed enum carries the full sibling
992/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
993/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
994/// lift) plus the round-trip witness through both the trait-idiomatic
995/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
996/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
997/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
998/// (an OTP-`intrinsic` fourth arm the theory
999/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1000/// might reach for once the three canonical OTP restart policies stop
1001/// covering the substrate's discovered load-shape) grows the trait-
1002/// idiomatic forward axis by construction: one caixa-core edit on
1003/// [`RestartPolicy::as_str`] extends every one of the five sibling
1004/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1005/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1006/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1007/// bytes) without a coordinated rewrite across every future
1008/// `Into<&'static str>`-bound consumer's arm-set.
1009///
1010/// Pinned load-bearing by
1011/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1012/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1013/// three-arm emit-set, plus a `const`-context materialization witness for
1014/// the `&'static str` lifetime promise) and
1015/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1016/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1017/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1018/// round-trip witness through the paired trait-idiomatic reverse-
1019/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1020/// `policy.into::<&'static str>()` output re-parses back through
1021/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1022/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1023impl From<RestartPolicy> for &'static str {
1024    fn from(policy: RestartPolicy) -> &'static str {
1025        policy.as_str()
1026    }
1027}
1028
1029// Fleet-wide dispatcher-catalog registrations for caixa's OTP
1030// supervisor surface — two more typed shadows over Erlang/OTP
1031// primitives the substrate now mechanically tracks (see
1032// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
1033// theory/TYPED-ABSORPTION.md for the absorption arc).
1034gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
1035gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
1036
1037/// One child entry in the supervisor's `:children` list.
1038///
1039/// Every child references another caixa by `:caixa <nome>` + version
1040/// constraint. The supervisor materializes one ComputeUnit per entry.
1041#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1042#[serde(rename_all = "camelCase")]
1043pub struct ChildSpec {
1044    /// The child caixa's `:nome`. Must resolve via the same dependency
1045    /// resolution path as `:deps` (caixa-resolver).
1046    pub caixa: String,
1047
1048    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
1049    /// [`crate::dep::Dep::versao`].
1050    pub versao: String,
1051
1052    /// Restart policy — an author-omitted slot degrades onto the
1053    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
1054    /// (`permanent`, the Erlang/OTP worker-child default) through the
1055    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
1056    /// to.
1057    #[serde(default)]
1058    pub restart: RestartPolicy,
1059}
1060
1061impl ChildSpec {
1062    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
1063    /// accessor every consumer that reads the OTP-shape supervised
1064    /// child's identity keys off — returns the author-declared
1065    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
1066    /// from the typed slot's own [`String`] storage.
1067    ///
1068    /// The `:children :caixa` slot carries the DNS-1123 label — the
1069    /// child caixa's `:nome` — that every emitted cluster artifact
1070    /// derives its `metadata.name` from verbatim: the rendered
1071    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
1072    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
1073    /// identity, and the per-child K8s Service `metadata.name` the
1074    /// future wasm-operator (M3) provisions for inter-child supervision-
1075    /// tree wiring. Every downstream consumer that fans on the child's
1076    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
1077    /// per-child DNS-1123 gate at
1078    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
1079    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
1080    /// [`validate_no_self_supervision`] cross-slot equality check
1081    /// against the parent's `:nome`, every `SupervisorError` variant
1082    /// carrying the offending child caixa verbatim for `feira lint`
1083    /// rendering, the future wasm-operator's hierarchical reconciliation
1084    /// scheduler's per-child ComputeUnit-name projection, the future M4
1085    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1086    /// admission webhook).
1087    ///
1088    /// Prior to this lift the `.caixa` byte-string was accessed inline
1089    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
1090    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
1091    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
1092    /// carriers' `child.caixa.clone()`, the dedup key's
1093    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
1094    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
1095    /// field-accesses that expressed no compile-time link back to the
1096    /// typed slot. A future extension of the `:children :caixa` axis to
1097    /// a richer author surface (a per-cluster alias table the operator
1098    /// pins through a future `:placement`-scoped slot on the supervisor
1099    /// tree, a namespace-qualified rewrite the M4 CR materializer
1100    /// applies per-CR, a per-child overlay from the future `:children
1101    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1102    /// acknowledges) would have had to be threaded through every
1103    /// open-coded copy in lockstep or one consumer would silently
1104    /// disagree with the peers on which caixa a given child resolves to
1105    /// — a child-set lookup that treated the name as `"cart-worker"`
1106    /// while the peer duplicate-detector treated it as
1107    /// `"tenant-a/cart-worker"` would silently split the
1108    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
1109    /// self-supervision detector's parent-equality check, a two-consumer
1110    /// split at the validator far from the source `caixa.lisp` with no
1111    /// field naming the identity-drift root cause. Lifting the resolution
1112    /// rule to a typed method on the substrate primitive means every
1113    /// downstream consumer of the Supervisor's per-`:children` identity
1114    /// surface reaches for exactly one typed dispatch — the resolver's
1115    /// accept-set migrates as a unit on any future axis addition.
1116    ///
1117    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
1118    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
1119    /// mesh-slot surface — same "one typed dispatch on the substrate
1120    /// primitive, thin projections at each consumer" discipline extended
1121    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
1122    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
1123    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
1124    /// accessor discipline for the shared substrate concept "another
1125    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
1126    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
1127    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
1128    /// slot family's typed-accessor discipline now spans both the
1129    /// upgrade axis (`:upgrade-from`) and the supervision axis
1130    /// (`:children`), matching the closed M3 mesh-slot accessor family's
1131    /// shape. Named `nome()` to match the tatara-lisp author-surface
1132    /// term the field's docstring already reaches for ("The child
1133    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
1134    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
1135    /// discipline the substrate already carries — the accessor's name
1136    /// maps directly onto the canonical caixa-identity vocabulary rather
1137    /// than shadowing the field's storage-side `caixa` label.
1138    #[must_use]
1139    pub const fn nome(&self) -> &str {
1140        self.caixa.as_str()
1141    }
1142
1143    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
1144    /// requirement scalar accessor every consumer that reads the OTP-shape
1145    /// supervised child's version pin keys off — returns the author-declared
1146    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
1147    /// the typed slot's own [`String`] storage.
1148    ///
1149    /// The `:children :versao` slot carries the Cargo-shaped semver
1150    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
1151    /// which release of the supervised child caixa the OTP-shape supervisor
1152    /// tree materializes against — the same requirement grammar the peer
1153    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
1154    /// shared [`crate::render::require_valid_versao_requirement`] cascade
1155    /// and the shared [`crate::version::parse_requirement`] parser. Every
1156    /// downstream consumer that fans on the child's version pin keys off
1157    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
1158    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
1159    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
1160    /// for `feira lint` rendering, every future per-cluster version-lock
1161    /// overlay the caixa-operator's hierarchical reconciliation scheduler
1162    /// pins through a future `:placement`-scoped supervisor-tree slot, the
1163    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1164    /// per-child version resolver, the future wasm-operator's per-child
1165    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
1166    ///
1167    /// Prior to this lift the `.versao` byte-string was accessed inline at
1168    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
1169    /// [`SupervisorSpec::validate`] requirement-gate call
1170    /// `require_valid_versao_requirement(&child.versao, …)` and the
1171    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
1172    /// `versao: child.versao.clone()` — two open-coded field-accesses that
1173    /// expressed no compile-time link back to the typed slot. A future
1174    /// extension of the `:children :versao` axis to a richer author surface
1175    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1176    /// flow, a lacre-projected concrete-version rewrite the operator
1177    /// materializes at CR-admission time, a future `:children :versao-lock`
1178    /// per-cluster override slot the wasm-operator's hierarchical
1179    /// reconciliation scheduler authors per-CR) would have had to be
1180    /// threaded through both open-coded copies in lockstep or one consumer
1181    /// would silently disagree with the peer on which release constraint a
1182    /// given child resolves to — the requirement-gate call reading
1183    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
1184    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
1185    /// the actual gate rejection input, a two-consumer split at the
1186    /// validator far from the source `caixa.lisp` with no field naming the
1187    /// version-pin drift root cause. Lifting the resolution rule to a typed
1188    /// method on the substrate primitive means every downstream
1189    /// requirement-facing consumer of the Supervisor's per-`:children`
1190    /// version-pin surface reaches for exactly one typed dispatch — the
1191    /// resolver's accept-set migrates as a unit on any future axis addition.
1192    ///
1193    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
1194    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
1195    /// surface — same "one typed dispatch on the substrate primitive, thin
1196    /// projections at each consumer" discipline extended onto the M2
1197    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
1198    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
1199    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
1200    /// one accessor discipline for the shared substrate concept "another
1201    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
1202    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
1203    /// `:nome` scalar accessor — the pair
1204    /// `(nome(), versao_requirement())` jointly projects the
1205    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
1206    /// that fans on per-child identity + version pin keys off, closing the
1207    /// last unlifted per-`:children` `String`-carry axis so every downstream
1208    /// per-`:children` reader now routes through a typed dispatch on the
1209    /// substrate primitive. Named `versao_requirement()` rather than
1210    /// `versao()` because the field's storage-side `.versao` label is
1211    /// already the author-surface term (`:versao`); the accessor's name
1212    /// carries the semantic role — the semver *requirement* string the
1213    /// shared [`crate::version::parse_requirement`] entry-point consumes —
1214    /// so a raw field access and a typed dispatch read differently at every
1215    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
1216    /// naming discipline verbatim.
1217    #[must_use]
1218    pub const fn versao_requirement(&self) -> &str {
1219        self.versao.as_str()
1220    }
1221
1222    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
1223    /// per-child post-exit restart-decision policy scalar accessor every
1224    /// consumer that dispatches on the supervised child's post-exit
1225    /// reconcile posture keys off — returns the author-declared
1226    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
1227    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
1228    /// storage.
1229    ///
1230    /// The `:children :restart` slot carries the closed-set OTP-shaped
1231    /// per-child restart-decision policy discriminator
1232    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
1233    /// worker-child default; [`RestartPolicy::Transient`] — restart only
1234    /// on abnormal exit, the OTP `transient` clean-completion-aware
1235    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
1236    /// `temporary` one-shot default) that every downstream consumer of
1237    /// the Supervisor's per-child post-exit reconcile branch keys off.
1238    /// Every future downstream consumer that fans on the per-child
1239    /// restart-decision keys off this scalar (the future `feira app
1240    /// graph` per-child restart column, the future wasm-operator's
1241    /// per-child post-exit restart-decision branch, the future M4
1242    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1243    /// admission webhook, the `caixa-operator`'s hierarchical
1244    /// reconciliation scheduler's per-child post-exit reconcile branch,
1245    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
1246    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1247    /// pin threads through).
1248    ///
1249    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
1250    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
1251    /// scalar accessor and the M3 mesh-slot
1252    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
1253    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
1254    /// — same "one typed dispatch on the substrate primitive,
1255    /// `Copy`-projected closed-set enum-arm discriminator that partitions
1256    /// the downstream renderer's per-arm fan-out" discipline extended
1257    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
1258    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
1259    /// [`ChildSpec`] type — companion to the sibling per-`:children`
1260    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
1261    /// and the per-`:children` [`ChildSpec::versao_requirement`]
1262    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
1263    /// on the sibling `String`-carry axes. The triple
1264    /// `(nome(), versao_requirement(), restart())` jointly projects the
1265    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
1266    /// tree consumer that fans on per-child identity + version pin +
1267    /// restart-decision keys off, closing the last unlifted per-`:children`
1268    /// axis so every downstream per-`:children` reader now routes through
1269    /// a typed dispatch on the substrate primitive. Named `restart()` to
1270    /// match the storage field's name and the author-surface
1271    /// `:children :restart` slot term verbatim; the accessor's identity
1272    /// name maps onto the canonical OTP-shape per-child restart-decision-
1273    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
1274    /// carries.
1275    ///
1276    /// Declared `pub const fn` to close the last non-`const`
1277    /// `Copy`-return raw-field-getter posture on the M2
1278    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
1279    /// of the sibling M2 per-`:supervisor`
1280    /// [`SupervisorSpec::estrategia`] (converted in this commit)
1281    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
1282    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1283    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
1284    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
1285    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
1286    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
1287    /// downstream substrate-side `const`-context consumer of the
1288    /// per-`:children` restart-decision-policy scalar (a future
1289    /// module-scope `const _:() = assert!(matches!(child.restart(),
1290    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
1291    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1292    /// admission-webhook `const fn` per-child restart-decision floor
1293    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
1294    /// composer over the substrate primitive that fans on the per-child
1295    /// restart-decision policy at compile time) now reaches through the
1296    /// same typed dispatch on the substrate primitive at const-eval
1297    /// time as at runtime. A future non-`Copy`-return promotion of the
1298    /// scalar (an `Option<RestartPolicy>`-shape migration on the
1299    /// per-child restart-decision axis once heterogeneous per-cluster
1300    /// restart-policy overlays land, a per-tenant restart-policy-alias
1301    /// table the M4 CR materializer resolves per-CR) that would drop
1302    /// the `const` qualifier fails the fail-before-pass-after pin
1303    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
1304    /// build time rather than surfacing as a downstream consumer
1305    /// regression.
1306    #[must_use]
1307    pub const fn restart(&self) -> RestartPolicy {
1308        self.restart
1309    }
1310}
1311
1312/// Supervisor-typed slots that live alongside the standard Caixa
1313/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
1314/// the manifest stays a single typed form; this struct exists for
1315/// validation + conversion.
1316#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1317#[serde(rename_all = "camelCase")]
1318pub struct SupervisorSpec {
1319    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
1320    #[serde(default)]
1321    pub estrategia: RestartStrategy,
1322
1323    /// Max restarts within [`Self::restart_window`] before the
1324    /// supervisor itself terminates (and its parent supervisor decides
1325    /// what to do). Default 5.
1326    #[serde(default = "default_max_restarts")]
1327    pub max_restarts: u32,
1328
1329    /// Sliding window for `max_restarts`. Authored as a duration
1330    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
1331    /// is rejected by [`Self::validate`] — Erlang/OTP's
1332    /// `MaxIntensity / Period` invariant requires a positive window
1333    /// (a zero-period supervisor either trips on the first failure or
1334    /// never trips, depending on operator interpretation, neither of
1335    /// which is the author's intent). Omit the slot to express "no
1336    /// reset"; carry a positive duration to express the sliding window.
1337    #[serde(
1338        default,
1339        skip_serializing_if = "Option::is_none",
1340        with = "duration_codec"
1341    )]
1342    pub restart_window: Option<Duration>,
1343
1344    /// Static children. Empty for `SimpleOneForOne` (children added
1345    /// dynamically); required for the other three strategies.
1346    #[serde(default)]
1347    pub children: Vec<ChildSpec>,
1348}
1349
1350const fn default_max_restarts() -> u32 {
1351    // Route the private serde-`#[serde(default = "…")]` helper through
1352    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
1353    // `pub const` rather than the raw `5` literal — one source of truth
1354    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
1355    // default across the two production consumers that currently
1356    // dispatch on it (this helper via `#[serde(default = "…")]` on
1357    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
1358    // impl at line 962). Pinned by
1359    // `default_max_restarts_helper_routes_through_lifted_default` +
1360    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
1361    // in the tests module; peer of the sibling caixa-core
1362    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
1363    // that now routes its author-omitted `:max-restarts` arm through
1364    // the same lifted constant.
1365    SUPERVISOR_MAX_RESTARTS_DEFAULT
1366}
1367
1368/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
1369/// count default for the `:supervisor :max-restarts` axis — the
1370/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
1371/// Erlang's worker-supervisor default, extracted as a typed `pub const`
1372/// so every substrate-side consumer that resolves "what
1373/// [`SupervisorSpec::max_restarts`] value does an author-omitted
1374/// `:max-restarts` slot degrade onto?" reaches for exactly one
1375/// substrate-primitive `u32`.
1376///
1377/// The `:max-restarts` default axis has two production consumers on the
1378/// substrate side today (both prior to this lift folded onto raw `5`
1379/// literals with no compile-time link back to a shared truth): the
1380/// serde-`#[serde(default = "default_max_restarts")]` helper on
1381/// [`SupervisorSpec::max_restarts`] that every author-omitted
1382/// `:supervisor :max-restarts` slot lands in past the derive-macro's
1383/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
1384/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
1385/// the composed [`SupervisorSpec`] altitude reaches through
1386/// (`feira app graph`, the future wasm-operator's per-supervisor
1387/// restart-intensity counter, the future M4
1388/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1389/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
1390/// A pair of open-coded `5`s across two files that expressed no
1391/// compile-time link back to the shared OTP-canonical default — a
1392/// future rebrand of the default (a tightening to Elixir's
1393/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
1394/// the operator pins through a future
1395/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
1396/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1397/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
1398/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
1399/// per-child-cohort roadmap lands) would have had to be threaded
1400/// through both open-coded copies in lockstep or the wire-format
1401/// author-omitted arm and the view-construction author-omitted arm
1402/// would silently disagree on which restart-budget an omitted
1403/// `:max-restarts` resolves to (an author writing `:supervisor
1404/// (:max-restarts ())` would round-trip through serde with the new
1405/// default while `supervisor_view` silently continued to compose the
1406/// stale `5`, or vice versa), a two-consumer split at the composition
1407/// boundary far from the source `caixa.lisp` with no field naming the
1408/// default-drift root cause. Lifting the resolution rule to a typed
1409/// `pub const` on the substrate primitive means every downstream
1410/// consumer of the per-Supervisor default-restart-budget-count surface
1411/// reaches for exactly one substrate-primitive `u32` — the resolver's
1412/// accepted value migrates as a unit on any future axis change.
1413///
1414/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1415/// worker-supervisor default (the closest canonical OTP-shape
1416/// production reference the substrate carries, matching the sibling
1417/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
1418/// this constant with on the paired sliding-window axis). Two orders of
1419/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
1420/// (the upper bracket on the same axis, sibling of this lower default;
1421/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
1422/// axis and now share one accessor discipline on the substrate) and
1423/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
1424/// restart floor — the "one restart, then escalate" default is
1425/// deliberately loose enough to absorb a short burst of transient
1426/// child failures without escalating past the supervisor's parent
1427/// while remaining tight enough to trip the `MaxIntensity / Period`
1428/// ratio's escalation on a genuinely-stuck child within the sibling
1429/// `60s` sliding window.
1430///
1431/// Lifted as a typed `pub const` so the bound has exactly one source
1432/// of truth — the serde-side wire-format author-omitted arm at
1433/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
1434/// struct-literal default field, and the caixa-core
1435/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
1436/// arm all read from one place. Same shape every other typed default
1437/// in this crate carries (the sibling
1438/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
1439/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
1440/// sibling `:restart-window` axis, and the peer
1441/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1442/// per-renderer defaults on the caixa-flux / caixa-helm rendering
1443/// axes).
1444pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
1445
1446/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
1447/// validated [`SupervisorSpec::max_restarts`] past
1448/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
1449///
1450/// The typed field is `u32` (the zero-floor arm
1451/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
1452/// so a programmatic struct literal
1453/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
1454/// author-surface form (`:max-restarts 4294967295` or any
1455/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
1456/// cleanly through serde — a structurally unbounded `u32` ceiling. The
1457/// runtime substrate consuming the value (Erlang/OTP's
1458/// `MaxIntensity / Period` ratio, the future wasm-operator's
1459/// per-supervisor restart-intensity counter, the M4
1460/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
1461/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
1462/// escalation threshold is structurally so high that no realistic
1463/// restarts-per-`:restart-window` traffic shape can reach it, the
1464/// supervisor never escalates to its parent, and a bad child can loop
1465/// inside the window indefinitely with the parent supervisor structurally
1466/// never receiving the "this subtree has exceeded its restart budget"
1467/// signal the typed slot is meant to express — the canonical
1468/// "supervisor intensity declared, no escalation" footgun, exactly the
1469/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
1470/// on the `:politicas :circuit-breaker :max-failures` axis (both are
1471/// "trip the next-higher protection layer after N events in a rolling
1472/// window" counters with identical degenerate-at-the-high-end shape).
1473///
1474/// The `1000` ceiling matches the sibling
1475/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
1476/// peer — same "events-per-window trip threshold" semantics, same `u32`
1477/// type, same no-op-at-the-high-end failure mode) so the M4
1478/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
1479/// and the future wasm-operator's per-supervisor restart-intensity
1480/// counter reach for either field knowing the value is in `1..=1000`
1481/// without re-validating at the reconciler layer. The cap sits two
1482/// orders of magnitude above every documented Erlang/OTP production
1483/// playbook recommendation (Learn You Some Erlang's
1484/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
1485/// `max_restarts: 3` default, OTP's `supervisor` callback module
1486/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
1487/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
1488/// default) and below the clearly-pathological "effectively no
1489/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
1490/// author can plausibly want at hyperscale (a long-running supervisor
1491/// over a very-flaky pool tolerating thousands of transient restarts
1492/// before escalating), but a hard wall above which the typed policy is
1493/// structurally a no-op carried verbatim on every emitted child-restart
1494/// reconciliation contract.
1495///
1496/// Lifted as a typed `pub const` so the bound has exactly one source of
1497/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1498/// materializer's admission webhook and the wasm-operator-side
1499/// per-supervisor restart-intensity reconciler read from one place. Same
1500/// shape every other typed upper bound in this crate carries
1501/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1502/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1503/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1504/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1505/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1506/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1507pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
1508
1509/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
1510/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
1511/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
1512/// (inclusive on both ends, integer-millisecond magnitudes by the
1513/// canonical-form gate immediately preceding).
1514///
1515/// The typed field is `Option<Duration>` (the zero-floor arm
1516/// [`SupervisorError::RestartWindowZero`] already rejects
1517/// `Some(Duration::ZERO)`, and the canonical-form arm
1518/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
1519/// sub-millisecond residue), so a programmatic struct literal
1520/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
1521/// .. }` — 24h) and the equivalent author-surface form
1522/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
1523/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
1524/// cleanly through serde — a structurally unbounded `Duration` ceiling.
1525/// A `:restart-window` value far above the documented Erlang/OTP
1526/// `MaxIntensity / Period` production-playbook band (Learn You Some
1527/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
1528/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
1529/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
1530/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
1531/// degenerates the supervisor's restart-intensity counter into a
1532/// lifetime counter: the rolling failure-counting window is structurally
1533/// so long that transient restarts are never forgotten, so the
1534/// `MaxIntensity / Period` ratio degenerates from "trip the parent
1535/// supervisor when the child has exceeded its restart budget *within
1536/// the recent window*" to "trip the parent when the child has exceeded
1537/// its restart budget *over its lifetime*" — every transient restart
1538/// counts against the budget forever, the supervisor's reset semantic
1539/// never reaches the child, and the typed `:restart-window` slot
1540/// becomes a no-op rolling window carried on every emitted hierarchical
1541/// reconciliation contract. The canonical
1542/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
1543/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
1544/// `:politicas :circuit-breaker :window` axis with identical shape (both
1545/// are "rolling failure-counting window with a per-`Period` reset" Duration
1546/// axes whose lifetime-counter degenerate at the high end is the same
1547/// "the reset semantic never fires" CSE invariant violation).
1548///
1549/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
1550/// the shared duration codec emits (`"<n>h"` for any integer-hour
1551/// magnitude) — every value in the canonical authoring form's
1552/// `<integer><unit>` grammar at or below this cap renders to a clean
1553/// canonical string — and matches the three sibling typed-`Duration`
1554/// caps already lifted to this surface
1555/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1556/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
1557/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
1558/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
1559/// per-supervisor `:supervisor :restart-window` — now share a single
1560/// uniform top edge at the codec's largest emitted unit so the next
1561/// typed-slot wiring (the future wasm-operator's per-supervisor
1562/// `MaxIntensity / Period` reconciler, the M4
1563/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1564/// webhook, the `caixa-operator`'s hierarchical reconciliation
1565/// scheduler) reaches for any of the four knowing the value is in
1566/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
1567/// two orders of magnitude above every documented Erlang/OTP / Elixir /
1568/// Riak Core / RabbitMQ production-playbook recommendation band
1569/// (`5s..=300s`) and below the clearly-pathological "rolling window
1570/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
1571/// a value the author can plausibly want for a very-low-traffic
1572/// long-tail failure-restart window over a hyperscale-flaky child pool,
1573/// but a hard wall above which the rolling-window contract is
1574/// structurally a lifetime-counter contract.
1575///
1576/// Lifted as a typed `pub const` so the bound has exactly one source
1577/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1578/// materializer's admission webhook, the wasm-operator-side
1579/// per-supervisor `MaxIntensity / Period` reconciler, and the
1580/// `caixa-operator`'s hierarchical reconciliation scheduler all read
1581/// from one place. Same shape every other typed upper bound in this
1582/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
1583/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1584/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1585/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1586/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1587/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1588/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
1589/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1590/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1591pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
1592
1593/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
1594/// default for the `:supervisor :restart-window` axis — the canonical
1595/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
1596/// worker-supervisor default, extracted as a typed `pub const` so every
1597/// substrate-side consumer that resolves "what
1598/// [`SupervisorSpec::restart_window`] value does an author-omitted
1599/// `:restart-window` slot degrade onto?" reaches for exactly one
1600/// substrate-primitive [`Duration`].
1601///
1602/// The `:restart-window` default axis has one production consumer on the
1603/// substrate side today: the [`Default for SupervisorSpec`] impl's
1604/// struct-literal `restart_window` field, which prior to this lift folded
1605/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
1606/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
1607/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
1608/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
1609/// *not* fall back to this default on the sibling `:restart-window` axis
1610/// — an author-omitted `:supervisor :restart-window` composes to
1611/// `restart_window: None` (the shared codec's soft-swallow shape),
1612/// keeping author-declared intent ("no reset — never escalate on rolling
1613/// window") distinct from the [`Default for SupervisorSpec`] "canonical
1614/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
1615/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
1616/// default was split across two files with no compile-time link between
1617/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
1618/// `MaxIntensity` half at the substrate primitive while the `Period`
1619/// half rode as an open-coded literal at the composition site, so a
1620/// future coherent rebrand of the paired canonical (a tightening to
1621/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
1622/// per-cluster overlay the operator pins through a future
1623/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
1624/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1625/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
1626/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
1627/// roadmap lands) would have had to migrate the `MaxIntensity` half
1628/// through the lifted constant and the `Period` half through a raw
1629/// literal in lockstep or the two halves of the same OTP-canonical
1630/// default would silently drift out of pairing. Lifting the resolution
1631/// rule to a typed `pub const` on the substrate primitive means the
1632/// paired OTP-canonical default migrates as one unit on any future
1633/// axis change.
1634///
1635/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1636/// worker-supervisor default (the closest canonical OTP-shape
1637/// production reference the substrate carries, matching the paired
1638/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
1639/// constant is the `Period` denominator of on the same
1640/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
1641/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
1642/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
1643/// this lower default; both are typed [`Duration`] const bounds on the
1644/// `:supervisor :restart-window` axis and now share one accessor
1645/// discipline on the substrate) and above the OTP-`supervisor`
1646/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
1647/// rolling window" default is deliberately loose enough to absorb a
1648/// short burst of transient child failures without escalating past the
1649/// supervisor's parent while remaining tight enough for the paired
1650/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
1651/// stuck child within a human-scale observation window.
1652///
1653/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1654/// exactly one source of truth on each half — the sibling
1655/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
1656/// `Period` `60s` half now share the same substrate-primitive lift
1657/// discipline. Same shape every other typed default in this crate
1658/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
1659/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
1660/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
1661/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
1662/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
1663/// caixa-flux / caixa-helm rendering axes).
1664pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
1665
1666/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
1667/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
1668/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
1669/// worker-supervisor default, extracted as a typed `pub const` so every
1670/// substrate-side consumer that resolves "what
1671/// [`SupervisorSpec::estrategia`] variant does an author-omitted
1672/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
1673/// primitive [`RestartStrategy`].
1674///
1675/// The `:estrategia` default axis has three production consumers on the
1676/// substrate side today: the [`Default for RestartStrategy`] impl's
1677/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
1678/// `estrategia` field, and the
1679/// [`crate::manifest::Caixa::supervisor_view`] fold's
1680/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
1681/// collapse arm — three entry points onto the same OTP-canonical
1682/// `one_for_one` value that prior to this lift folded onto a raw
1683/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
1684/// implicit `RestartStrategy::default()` routes at the sibling consumers,
1685/// with no compile-time link back to the paired
1686/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
1687/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
1688/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
1689/// triple was split across three altitudes with no compile-time link
1690/// between the halves: the `MaxIntensity` half rode through the lifted
1691/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
1692/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1693/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
1694/// discriminator at the [`Default for RestartStrategy`] impl, so a future
1695/// coherent rebrand of the triple (Elixir's `{:one_for_one,
1696/// max_restarts: 3, max_seconds: 5}` — same strategy, different
1697/// intensity/period; an OTP `rest_for_one` widening once the substrate
1698/// discovers startup-order-coupled child cohorts as the more common
1699/// worker-supervisor default; a per-cluster overlay the operator pins
1700/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
1701/// §III.2 supervision-canary roadmap acknowledges) would have had to
1702/// migrate the `MaxIntensity` + `Period` halves through the lifted
1703/// constants and the `one_for_one` half through an open-coded arm in
1704/// lockstep or the three halves of the same OTP-canonical default would
1705/// silently drift out of pairing. Lifting the resolution rule to a typed
1706/// `pub const` on the substrate primitive means the paired OTP-canonical
1707/// worker-supervisor default migrates as one unit on any future axis
1708/// change.
1709///
1710/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
1711/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
1712/// closest canonical OTP-shape production reference the substrate
1713/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
1714/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1715/// `60s` `Period` half). The `one_for_one` strategy — restart only the
1716/// failed child, leaving siblings untouched — is the default for tree-of-
1717/// independent-workers use cases the substrate's [`RestartStrategy`]
1718/// discriminator's own docstring already carries as the default arm; it
1719/// composes with the `{5, 60}` restart-intensity ratio to name the same
1720/// substrate-canonical "canonical worker-supervisor" shape the paired
1721/// halves close on their respective axes.
1722///
1723/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1724/// exactly one source of truth on each of its three halves — the sibling
1725/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
1726/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
1727/// this `one_for_one` strategy half now share the same substrate-
1728/// primitive lift discipline. Same shape every other typed default in
1729/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
1730/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
1731/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
1732/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
1733/// upper caps on the paired sibling axes, and the peer
1734/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1735/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
1736pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
1737
1738/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
1739/// default for the `:children :restart` axis — the OTP `permanent`
1740/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
1741/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
1742/// `pub const` so every substrate-side consumer that resolves "what
1743/// [`ChildSpec::restart`] variant does an author-omitted `:children
1744/// :restart` slot degrade onto?" reaches for exactly one substrate-
1745/// primitive [`RestartPolicy`].
1746///
1747/// Completes the OTP-shape supervisor-tree default set at the substrate
1748/// primitive. The per-`:supervisor` axis already carries all three of its
1749/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1750/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
1751/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1752/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
1753/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
1754/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
1755/// the M2 `:supervisor` slot family. The split mattered because the two
1756/// axes resolve *together* on every author-omitted supervisor: a
1757/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
1758/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
1759/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
1760/// `permanent` through an open-coded enum arm, so a future coherent
1761/// rebrand of the OTP-shape default set (an Elixir-shaped
1762/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
1763/// per-cluster overlay the operator pins through the MESH-COMPOSITION
1764/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
1765/// once the substrate discovers clean-completion-aware children as the
1766/// more common child shape) would have had to migrate three halves
1767/// through typed constants and the fourth through a raw enum arm in
1768/// lockstep or the supervisor-level and child-level defaults would
1769/// silently drift apart.
1770///
1771/// The `:children :restart` default axis has two production consumers on
1772/// the substrate side today: the [`Default for RestartPolicy`] impl's
1773/// return arm, and the serde-side `#[serde(default)]` on
1774/// [`ChildSpec::restart`] that resolves an author-omitted `:children
1775/// :restart` slot through that same impl. Both now key off this one
1776/// substrate primitive, so the future wasm-operator's per-child post-exit
1777/// restart-decision branch, the future M4
1778/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1779/// admission webhook, and the `caixa-operator`'s hierarchical
1780/// reconciliation scheduler's per-child fan-out all reach for one typed
1781/// identifier when they resolve an omitted per-child restart posture.
1782///
1783/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
1784/// worker-child restart type — always restart the child regardless of how
1785/// it died, the canonical posture for long-running services that must
1786/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1787/// `one_for_one` tree-of-independent-workers strategy this constant pairs
1788/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
1789/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
1790/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
1791/// [`RestartPolicy::Temporary`] — never restart) express deliberate
1792/// one-shot / clean-completion-aware postures an author declares
1793/// explicitly, never a posture an omitted slot should silently assume.
1794pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
1795
1796/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
1797/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
1798/// `pub const fn` constructor rather than a struct-literal cascade over
1799/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
1800/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1801/// lifted consts — one source of truth for the Erlang/OTP-canonical
1802/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
1803/// paths every downstream consumer already reaches through (the
1804/// hand-authored-until-now [`Default::default`] the
1805/// `..SupervisorSpec::default()` struct-update-syntax on every
1806/// one-axis-under-test fixture in this crate's test module rests on,
1807/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
1808/// every `const`-context consumer reaches through).
1809///
1810/// Extends the [`Default`]-through-const-ctor fold discipline the
1811/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
1812/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
1813/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
1814/// and [`crate::BehaviorSpec`]
1815/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
1816/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
1817/// typed-slot spec family — extended here onto the M2 supervisor-slot
1818/// [`SupervisorSpec`] whose canonical baseline is not "everything
1819/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
1820/// supervisor triple. The `empty()` peer's naming did not fit
1821/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
1822/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
1823/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
1824/// the sibling `Option`-only slots fold to), so this peer is named
1825/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
1826/// existing per-arm pin tests
1827/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
1828/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
1829/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
1830/// already reach for. Pinned load-bearing by
1831/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
1832/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
1833/// [`PartialEq`], sharpening the sibling
1834/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
1835/// pins from a per-field lift into a whole-struct one-source-of-truth
1836/// pin — the derived-until-now [`Default::default`] and the
1837/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
1838/// construction, not by coincidence).
1839impl Default for SupervisorSpec {
1840    #[inline]
1841    fn default() -> Self {
1842        Self::otp_canonical()
1843    }
1844}
1845
1846impl SupervisorSpec {
1847    /// `const`-context peer of the [`Default for SupervisorSpec`]
1848    /// impl (which routes through this constructor) — returns the
1849    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
1850    /// baseline this crate reaches for in every fixture-builder
1851    /// `..SupervisorSpec::default()` struct-update expression and
1852    /// every downstream `SupervisorSpec::default()` seed.
1853    ///
1854    /// Each field routes through the same substrate-canonical
1855    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
1856    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
1857    /// per-arm pin tests
1858    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
1859    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
1860    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
1861    /// already assert, so a future coherent rebrand of the OTP-canonical
1862    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
1863    /// cluster overlay via a future `:restart-window-overrides` slot, a
1864    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
1865    /// absorption roadmap acknowledges) migrates through three typed
1866    /// constants in lockstep, and the paired [`Default`] impl inherits
1867    /// every future extension by construction.
1868    ///
1869    /// `pub const fn` rather than the derived-style `Default::default`
1870    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
1871    /// [`Default::default`] is not `const` on stable Rust, and
1872    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
1873    /// every consumer through a [`Clone::clone`]. The `pub const fn`
1874    /// discipline lets `const`-context callers construct the OTP-
1875    /// canonical baseline at compile time without runtime dispatch on
1876    /// the derived [`Default::default`], the same posture the sibling
1877    /// [`crate::LimitsSpec::empty`] (9739971) /
1878    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
1879    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
1880    /// spec `pub const fn` constructors carry on the sibling
1881    /// "everything `None`" baseline axis.
1882    ///
1883    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
1884    /// of the derived-style [`Default`]" family — sibling of the
1885    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
1886    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
1887    /// baseline" trio, extended here onto the M2 supervisor-slot
1888    /// [`SupervisorSpec`] whose canonical baseline is not "everything
1889    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
1890    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
1891    /// than `empty()` to name the actual invariant the return value
1892    /// pins — the same phrasing already used in the per-arm pin tests
1893    /// on this file. Pinned load-bearing by
1894    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
1895    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
1896    #[must_use]
1897    pub const fn otp_canonical() -> Self {
1898        Self {
1899            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
1900            max_restarts: default_max_restarts(),
1901            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
1902            children: Vec::new(),
1903        }
1904    }
1905
1906    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
1907    /// sibling-restart-strategy scalar accessor every consumer that
1908    /// dispatches on the supervisor's per-sibling restart-decision shape
1909    /// keys off — returns the author-declared `:supervisor :estrategia`
1910    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
1911    /// the typed slot's own [`RestartStrategy`] storage.
1912    ///
1913    /// The `:supervisor :estrategia` slot carries the closed-set
1914    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
1915    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
1916    /// [`RestartStrategy::OneForAll`] — restart every child on any child
1917    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
1918    /// [`RestartStrategy::RestForOne`] — restart the failed child and
1919    /// every child started after it, the Erlang/OTP `rest_for_one`
1920    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
1921    /// dynamic children of the same shape, the Erlang/OTP
1922    /// `simple_one_for_one` per-session default) that every downstream
1923    /// consumer of the Supervisor's per-sibling restart-decision fan-out
1924    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
1925    /// paired coherently with the sibling `:children` axis
1926    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
1927    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
1928    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
1929    /// downstream consumer that reads the strategy keys off this scalar
1930    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
1931    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
1932    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
1933    /// `estrategia:` field, the future `feira app graph` per-Supervisor
1934    /// strategy print line, the future wasm-operator's per-supervisor
1935    /// sibling-restart-strategy branch, the future M4
1936    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
1937    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
1938    /// reconciliation scheduler's per-strategy fan-out).
1939    ///
1940    /// Prior to this lift the `.estrategia` field was accessed inline at
1941    /// two production sites in `caixa-core/src/supervisor.rs` — the
1942    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
1943    /// `match self.estrategia { … }` partition dispatch, and the
1944    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
1945    /// carrier at `estrategia: self.estrategia` — two open-coded
1946    /// field-accesses that expressed no compile-time link back to the
1947    /// typed slot. A future extension of the `:supervisor :estrategia`
1948    /// axis to a richer author surface (a per-cluster strategy override
1949    /// the operator pins through a future `:supervisor :estrategia-overrides`
1950    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
1951    /// acknowledges, a per-tenant strategy-alias table the M4 CR
1952    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
1953    /// derivation the future adaptive-supervision engine computes from
1954    /// child-failure-history topology, a per-child-cohort strategy split
1955    /// the future `RestForCohort` extension acknowledged by the
1956    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
1957    /// would have had to be threaded through every open-coded copy in
1958    /// lockstep — one consumer reading the raw variant while a peer read
1959    /// the operator-resolved variant would silently split the
1960    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
1961    /// the actual partition-dispatch input the empty-children refusal
1962    /// arm reached under, a two-consumer split at the validator far from
1963    /// the source `caixa.lisp` with no field naming the strategy-drift
1964    /// root cause. Lifting the resolution rule to a typed method on the
1965    /// substrate primitive means every downstream consumer of the
1966    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
1967    /// reaches for exactly one typed dispatch — the resolver's accept-set
1968    /// migrates as a unit on any future axis addition.
1969    ///
1970    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
1971    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
1972    /// per-`:placement` distribution-strategy axis — same "one typed
1973    /// dispatch on the substrate primitive, thin projections at each
1974    /// consumer" discipline extended onto the M2 supervisor-slot
1975    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
1976    /// scalar axis. The two typed axes (`Placement::estrategia` on the
1977    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
1978    /// Supervisor side) now share one accessor discipline for the shared
1979    /// substrate concept "a `Copy`-projected closed-set enum-arm
1980    /// discriminator that partitions the downstream renderer's per-arm
1981    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
1982    /// `SupervisorSpec` type — companion to the sibling per-`:children`
1983    /// [`crate::ChildSpec::nome`] (57c61d0) /
1984    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
1985    /// scalar accessors on the sibling per-`:children` `String`-carry
1986    /// axes. Named `estrategia()` to match the storage field's name and
1987    /// the peer [`crate::Placement::estrategia`] method-name discipline
1988    /// verbatim; the accessor's identity name maps onto the canonical
1989    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
1990    /// docstring already carries.
1991    ///
1992    /// Declared `pub const fn` to close the M2 supervisor-slot
1993    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
1994    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
1995    /// (converted in this commit) `Copy`-composite-enum accessor, peer
1996    /// of the sibling M2 per-`:supervisor`
1997    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1998    /// already lifted, and mirror of the peer M3 mesh-slot
1999    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
2000    /// `Copy`-return `pub const fn` scalar accessor whose method-name
2001    /// discipline this accessor was authored to match. Every downstream
2002    /// substrate-side `const`-context consumer of the per-`:supervisor`
2003    /// sibling-restart-strategy scalar (a future module-scope `const
2004    /// _:() = assert!(matches!(sup.estrategia(),
2005    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
2006    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2007    /// admission-webhook `const fn` per-supervisor strategy-arm floor
2008    /// over a typed [`SupervisorSpec`], any future `const fn`
2009    /// supervisor-tree composer over the substrate primitive that fans
2010    /// on the sibling-restart-strategy at compile time) now reaches
2011    /// through the same typed dispatch on the substrate primitive at
2012    /// const-eval time as at runtime. A future non-`Copy`-return
2013    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
2014    /// migration once the substrate grows per-cluster strategy overlays
2015    /// the [`SupervisorSpec`] docstring already anticipates, a
2016    /// per-tenant strategy-alias table the M4 CR materializer resolves
2017    /// per-CR) that would drop the `const` qualifier fails the
2018    /// fail-before-pass-after pin
2019    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
2020    /// caixa-core build time rather than surfacing as a downstream
2021    /// consumer regression.
2022    #[must_use]
2023    pub const fn estrategia(&self) -> RestartStrategy {
2024        self.estrategia
2025    }
2026
2027    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
2028    /// `MaxIntensity` restart-budget scalar accessor every consumer that
2029    /// reads the supervisor's per-`:restart-window` restart-budget count
2030    /// keys off — returns the author-declared `:supervisor :max-restarts`
2031    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
2032    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
2033    /// borrow of `&self` past the call). Non-optional (the `u32` field
2034    /// carries the restart-budget count as a required axis with a
2035    /// [`default_max_restarts`]-supplied default; the zero-floor arm
2036    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
2037    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
2038    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
2039    ///
2040    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
2041    /// `MaxIntensity` restart-budget count that pairs with the sibling
2042    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
2043    /// restart-intensity ratio the supervisor trips its own escalation on
2044    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
2045    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
2046    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
2047    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
2048    /// upper-cap bracket at
2049    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
2050    /// wasm-operator's per-supervisor restart-intensity counter's
2051    /// budget-vs-count comparator, the future M4
2052    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2053    /// webhook, the `caixa-operator`'s hierarchical reconciliation
2054    /// scheduler's per-supervisor escalation-decision branch, every
2055    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
2056    /// offending count verbatim for `feira lint` rendering).
2057    ///
2058    /// Prior to this lift the `.max_restarts` field was accessed inline at
2059    /// one production site in `caixa-core/src/supervisor.rs` — the
2060    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
2061    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
2062    /// that expressed no compile-time link back to the typed slot. A
2063    /// future extension of the `:max-restarts` axis to a richer author
2064    /// surface (a per-cluster restart-budget override the operator pins
2065    /// through a future `:supervisor :max-restarts-overrides` slot the
2066    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
2067    /// a per-tenant restart-budget-alias table the M4 CR materializer
2068    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
2069    /// the future adaptive-supervision engine computes from child-failure-
2070    /// history topology, a promotion of the plain `u32` count to a richer
2071    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
2072    /// budget-partition slot comes into scope) would have had to be
2073    /// threaded through every open-coded copy in lockstep or the validate
2074    /// gate and the future M4 emit path would silently disagree on which
2075    /// restart-budget count a given supervisor resolves to — an author's
2076    /// `:max-restarts 5` would satisfy validate while the emit path
2077    /// silently read a drifted other value (a `:max-restarts 10000`
2078    /// no-op supervisor at the emit boundary would carry the author's
2079    /// declared `5` verbatim in `feira lint` output while the future
2080    /// wasm-operator's restart-intensity counter operated under the
2081    /// drifted count), a two-consumer split at the validator far from the
2082    /// source `caixa.lisp` with no field naming the restart-budget-drift
2083    /// root cause. Lifting the resolution rule to a typed method on the
2084    /// substrate primitive means every downstream consumer of the
2085    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
2086    /// for exactly one typed dispatch — the resolver's accept-set migrates
2087    /// as a unit on any future axis addition.
2088    ///
2089    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
2090    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
2091    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
2092    /// outlier-detection trip-threshold axis — same "one typed dispatch on
2093    /// the substrate primitive, thin projections at each consumer"
2094    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
2095    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
2096    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
2097    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
2098    /// one accessor discipline for the shared substrate concept "a
2099    /// `Copy`-projected required `u32` count that trips the next-higher
2100    /// protection layer after N events in a rolling window" — both are
2101    /// counters with identical degenerate-at-the-high-end shape and share
2102    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
2103    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
2104    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
2105    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
2106    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
2107    /// the storage field's name verbatim and the peer
2108    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
2109    /// accessor's identity maps onto the canonical OTP-shape supervision
2110    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
2111    /// already carries.
2112    #[must_use]
2113    pub const fn max_restarts(&self) -> u32 {
2114        self.max_restarts
2115    }
2116
2117    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
2118    /// `Period` sliding-window scalar accessor every consumer of the
2119    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
2120    /// keys off — returns the author-declared `:supervisor :restart-window`
2121    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
2122    /// the typed slot's own `Option<Duration>` storage (`Duration` is
2123    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
2124    /// value; no borrow of `&self` past the call). `None` when the slot is
2125    /// absent (the canonical "never reset — every restart across the
2126    /// supervisor's lifetime counts against the sibling `:max-restarts`
2127    /// budget" sentinel the field's own docstring names and the peer
2128    /// `validate_accepts_none_restart_window` pin locks in on the
2129    /// [`SupervisorSpec::validate`] entry-side).
2130    ///
2131    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
2132    /// `Period` sliding-observation-interval that pairs with the sibling
2133    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
2134    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
2135    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
2136    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
2137    /// default). The typed slot's `Option<Duration>` accept-set —
2138    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
2139    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
2140    /// `Period > 0`; a zero period either trips on the first failure or
2141    /// never trips depending on operator interpretation, neither of which
2142    /// is the author's intent — omit the slot to express "no reset";
2143    /// carry a positive duration to express the sliding window),
2144    /// integer-millisecond canonical form enforced through
2145    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
2146    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
2147    /// future wasm-operator's per-supervisor restart-intensity counter
2148    /// quantizes at milliseconds), upper-bounded by
2149    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
2150    /// supervisor rolling window any operationally-reachable supervisor
2151    /// can honor without spanning multiple scheduler epochs the
2152    /// hierarchical-reconciliation scheduler treats as independent) —
2153    /// maps onto the future wasm-operator (M3) per-supervisor
2154    /// restart-intensity counter's rolling-observation-interval, the
2155    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2156    /// per-`spec.restartWindow` admission webhook, and the sibling
2157    /// `duration_codec`-serialized wire scalar every downstream consumer
2158    /// of the supervisor's per-`:supervisor` restart-intensity denominator
2159    /// keys off.
2160    ///
2161    /// Prior to this lift the `.restart_window` field was accessed inline
2162    /// at one production site in `caixa-core/src/supervisor.rs` — the
2163    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
2164    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
2165    /// open-coded field-access that expressed no compile-time link back to
2166    /// the typed slot. A future extension of the `:restart-window` axis to
2167    /// a richer author surface (a per-cluster restart-window override the
2168    /// operator pins through a future `:supervisor :restart-window-overrides`
2169    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2170    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
2171    /// materializer resolves per-CR, a per-supervisor dynamic
2172    /// restart-window derivation the future adaptive-supervision engine
2173    /// computes from child-failure-history topology, a promotion of the
2174    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
2175    /// pair once Erlang/OTP's per-child-cohort observation-interval-
2176    /// partition slot comes into scope) would have had to be threaded
2177    /// through every open-coded copy in lockstep or the validate gate and
2178    /// the future M4 emit path would silently disagree on which
2179    /// restart-window a given supervisor resolves to — an author's
2180    /// `:restart-window "60s"` would satisfy validate while the emit path
2181    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
2182    /// authored slot at the emit boundary would carry the author's
2183    /// declared window verbatim in `feira lint` output while the future
2184    /// wasm-operator's restart-intensity counter operated under a
2185    /// drifted window, or vice versa: an author's `:restart-window ()`
2186    /// would carry the "never reset" sentinel through validate while the
2187    /// emit path silently substituted a default sliding window), a
2188    /// two-consumer split at the validator far from the source
2189    /// `caixa.lisp` with no field naming the restart-window-drift root
2190    /// cause. Lifting the resolution rule to a typed method on the
2191    /// substrate primitive means every downstream consumer of the
2192    /// Supervisor's per-`:supervisor` restart-intensity-denominator
2193    /// surface reaches for exactly one typed dispatch — the resolver's
2194    /// accept-set migrates as a unit on any future axis addition.
2195    ///
2196    /// Third `Copy`-return accessor on the M2 supervisor-slot
2197    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
2198    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
2199    /// payload rather than a `Copy`-scalar, and the per-`:children`
2200    /// [`crate::ChildSpec::nome`] (57c61d0) /
2201    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2202    /// scalar accessors already close the per-element `String`-carry
2203    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
2204    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
2205    /// per-outermost-call wall-clock-deadline axis and the peer M3
2206    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
2207    /// accessor on the `:politicas` slot's per-call-deadline axis — all
2208    /// three share the shared substrate concept "a `Copy`-projected
2209    /// optional `Duration` that carries a positive integer-millisecond
2210    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
2211    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
2212    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
2213    /// bracket-helper the three axes each route through. Named
2214    /// `restart_window()` to match the storage field's name verbatim and
2215    /// the peer [`crate::LimitsSpec::wall_clock`] /
2216    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
2217    /// accessor's identity maps onto the canonical OTP-shape supervision
2218    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
2219    /// already carries.
2220    #[must_use]
2221    pub const fn restart_window(&self) -> Option<Duration> {
2222        self.restart_window
2223    }
2224
2225    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
2226    /// static-child-list slice accessor every consumer that walks the
2227    /// supervisor's declared child set keys off — returns the author-
2228    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
2229    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
2230    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
2231    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
2232    /// through). Non-optional: an empty slice is the load-bearing
2233    /// "author declared `:children ()`" sentinel every consumer of the
2234    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
2235    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
2236    /// three strategies require a non-empty slice — the paired
2237    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
2238    /// [`SupervisorError::NoChildren`] refusal cascade pins the
2239    /// partition on both arms).
2240    ///
2241    /// The `:supervisor :children` slot carries the OTP-shaped static
2242    /// child list the supervisor materializes one ComputeUnit per
2243    /// entry from — the Erlang/OTP `supervisor:init/1`'s
2244    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
2245    /// through the tatara-lisp `:children` author surface onto a typed
2246    /// `Vec<ChildSpec>` whose per-element `(nome(),
2247    /// versao_requirement(), restart)` triple the per-child
2248    /// [`SupervisorSpec::validate`] loop already gates through the
2249    /// lifted [`ChildSpec::nome`] (57c61d0) /
2250    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
2251    /// Every downstream consumer that fans on the static child list
2252    /// keys off this slice (the [`SupervisorSpec::validate`]
2253    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
2254    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
2255    /// per-child DNS-1123 / semver-requirement / duplicate-detection
2256    /// fan-out loop, every future wasm-operator (M3) per-supervisor
2257    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
2258    /// materialization loop, the future M4
2259    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2260    /// admission-webhook fan-out, the future `feira app graph`
2261    /// per-supervisor tree-print traversal).
2262    ///
2263    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
2264    /// inline at three production sites in `caixa-core/src/supervisor.rs`
2265    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
2266    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
2267    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
2268    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
2269    /// validate loop's `for child in &self.children` traversal head —
2270    /// three open-coded field-accesses that expressed no compile-time
2271    /// link back to the typed slot. A future extension of the
2272    /// `:supervisor :children` axis to a richer author surface (a
2273    /// per-cluster child-set overlay the operator pins through a future
2274    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
2275    /// supervision-canary roadmap acknowledges, a per-tenant
2276    /// child-set-alias table the M4 CR materializer resolves per-CR,
2277    /// a per-supervisor dynamic-child derivation the future adaptive-
2278    /// supervision engine computes from child-failure-history topology,
2279    /// a promotion of the plain `Vec<ChildSpec>` to a richer
2280    /// `{static, dynamic}` partition once Erlang/OTP's
2281    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
2282    /// would have had to be threaded through all three open-coded copies
2283    /// in lockstep or one consumer would silently disagree with the
2284    /// peers on which child-set a given supervisor resolves to — the
2285    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
2286    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
2287    /// would silently split the partition-dispatch's two-arm coherence
2288    /// (a supervisor that satisfies neither arm's precondition, or that
2289    /// satisfies both, at the cost of the paired
2290    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
2291    /// silently drifting from the per-child validate loop's actual
2292    /// traversal input), a three-consumer split at the validator far
2293    /// from the source `caixa.lisp` with no field naming the
2294    /// child-set-drift root cause. Lifting the resolution rule to a
2295    /// typed method on the substrate primitive means every downstream
2296    /// consumer of the Supervisor's per-`:supervisor` static-child-list
2297    /// surface reaches for exactly one typed dispatch — the resolver's
2298    /// accept-set migrates as a unit on any future axis addition.
2299    ///
2300    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
2301    /// — the seed for the same "one typed dispatch on the substrate
2302    /// primitive, thin projections at each consumer" discipline the
2303    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
2304    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
2305    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
2306    /// onto the first `Vec`-carry axis on the substrate. The four peer
2307    /// `Vec`-carry axes still unlifted at the time of this seed —
2308    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
2309    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
2310    /// (`Vec<Membro>` per-Aplicacao member list),
2311    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
2312    /// per-Aplicacao WIT-typed edge list),
2313    /// [`crate::UpgradeFromEntry::instructions`]
2314    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
2315    /// — inherit this accessor's discipline as future compounding runs
2316    /// migrate their consumers onto the shared slice-return shape.
2317    /// Fourth (and final) accessor on the M2 supervisor-slot
2318    /// `SupervisorSpec` type, sibling to the three `Copy`-return
2319    /// [`SupervisorSpec::estrategia`] (eafb619) /
2320    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
2321    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
2322    /// the last unlifted per-`:supervisor` field axis (the
2323    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
2324    /// per-`:supervisor` reader now routes through a typed dispatch on
2325    /// the substrate primitive. Named `children()` to match the storage
2326    /// field's name verbatim and the tatara-lisp author-surface term
2327    /// (`:children`) the field's own docstring already carries; the
2328    /// accessor's identity maps onto the canonical OTP-shape
2329    /// supervision vocabulary the [`SupervisorSpec::children`] field's
2330    /// docstring already reaches for ("Static children ..."). Returns
2331    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
2332    /// consumer of the child list treats it as a read-only sequence —
2333    /// the slice-view is the narrowest borrow that supports every
2334    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
2335    /// index, `.len()`) without leaking the backing `Vec`'s
2336    /// grow/push/reserve surface that no consumer of the typed view
2337    /// reaches for (the storage-side `Vec` remains reachable through
2338    /// the `pub children` field for the mutation-carrying
2339    /// `Caixa::supervisor_view` fold-in path in
2340    /// `manifest.rs:supervisor_view`).
2341    #[must_use]
2342    pub const fn children(&self) -> &[ChildSpec] {
2343        self.children.as_slice()
2344    }
2345
2346    /// Validate the supervisor's typed shape — strategy ↔ children
2347    /// invariants, max_restarts > 0, restart_window > 0 when set,
2348    /// per-child non-empty + duplicate-free names.
2349    ///
2350    /// Mirrors the value-shape discipline applied to every other
2351    /// typed slot:
2352    ///
2353    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
2354    ///     same "0 means the opposite of what you think" footgun
2355    ///     closed for `:politicas :timeout` (Envoy interprets a zero
2356    ///     timeout as `infinite`), `:politicas :circuit-breaker
2357    ///     :window`, and `:limits :wall-clock`. The
2358    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
2359    ///     `supervisor` requires `Period > 0`; a zero period either
2360    ///     trips on the first failure or never trips depending on
2361    ///     operator interpretation, neither of which is the
2362    ///     author's intent. Omit `:restart-window` to express "no
2363    ///     reset"; carry a positive duration to express the window.
2364    ///   - duplicate `:children` `:caixa` names are the same
2365    ///     graph-node-set / multiset distinction closed for
2366    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
2367    ///     and `:entrada :paths` (eb3456d). Two children with the
2368    ///     same `:caixa` materialize as two ComputeUnits with the
2369    ///     same name in the cluster's HelmRelease values, one
2370    ///     silently overwriting the other. Erlang/OTP's
2371    ///     `child_spec.id` is required-unique per supervisor;
2372    ///     pleme-io enforces the same set-not-multiset shape on
2373    ///     `:caixa` (the load-bearing identity in our renderer).
2374    pub fn validate(&self) -> Result<(), SupervisorError> {
2375        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
2376        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2377        // error carrier's `estrategia:` field through the lifted
2378        // [`SupervisorSpec::estrategia`] accessor rather than the raw
2379        // `self.estrategia` field access — the two production consumers
2380        // of the per-`:supervisor` sibling-restart-strategy scalar now
2381        // key off exactly one typed dispatch on the substrate primitive,
2382        // so any future rebrand on the axis (a per-cluster strategy
2383        // override the operator pins through a future `:supervisor
2384        // :estrategia-overrides` slot, a per-tenant strategy-alias table
2385        // the M4 CR materializer resolves per-CR) migrates as a single
2386        // caixa-core edit rather than a coordinated rewrite of the two
2387        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
2388        // (921fe1b) four-consumer migration on the per-`:placement`
2389        // distribution-strategy axis.
2390        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
2391        // dispatch's paired `.is_empty()` cross-slot refusal probes
2392        // (the `SimpleOneForOne`-arm
2393        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
2394        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2395        // refusal) through the lifted [`SupervisorSpec::children`]
2396        // slice-return accessor rather than the raw `self.children`
2397        // field access — the two paired production consumers of the
2398        // per-`:supervisor` static-child-list scalar-shape now key off
2399        // exactly one typed dispatch on the substrate primitive, so any
2400        // future rebrand on the axis (a per-cluster child-set overlay
2401        // the operator pins through a future `:supervisor
2402        // :children-overrides` slot, a per-tenant child-set-alias table
2403        // the M4 CR materializer resolves per-CR) migrates as a single
2404        // caixa-core edit rather than a coordinated rewrite of the
2405        // paired arms — first slice-return migration on any typed slot,
2406        // seed for the peer per-`:placement :clusters`,
2407        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
2408        // :instructions` `Vec`-carry axes.
2409        match self.estrategia() {
2410            RestartStrategy::SimpleOneForOne => {
2411                // SimpleOneForOne: children added at runtime. Static
2412                // list must be empty (one shape declared elsewhere).
2413                if !self.children().is_empty() {
2414                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
2415                }
2416            }
2417            _ => {
2418                if self.children().is_empty() {
2419                    return Err(SupervisorError::no_children(self.estrategia()));
2420                }
2421            }
2422        }
2423        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
2424        // axis. See [`crate::render::require_positive_bounded_u32`] for
2425        // the ordering discipline (zero-floor arm strictly precedes cap
2426        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
2427        // diagnostic with its counter-axis remediation directly named,
2428        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
2429        // cap-arm miss). Until this bracket landed the top edge ran all
2430        // the way to `u32::MAX` and a struct-literal
2431        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
2432        // equivalent author-surface `:max-restarts 100000` /
2433        // `:max-restarts 4294967295` typo landing in the slot) silently
2434        // passed validate. The runtime substrate consuming the value
2435        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
2436        // wasm-operator's per-supervisor restart-intensity counter, the
2437        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2438        // admission webhook) then turned a typed `:max-restarts`
2439        // policy into a no-op supervisor: the escalation threshold is
2440        // structurally so high that no realistic
2441        // restarts-per-`:restart-window` traffic shape can reach it,
2442        // the supervisor never escalates to its parent, and a bad
2443        // child can loop inside the window indefinitely with the
2444        // parent supervisor structurally never receiving the "this
2445        // subtree has exceeded its restart budget" signal the typed
2446        // slot is meant to express. The bracket set is
2447        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
2448        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
2449        // the sibling `:politicas :circuit-breaker :max-failures` axis:
2450        // both are "trip the next-higher protection layer after N
2451        // events in a rolling window" counters with identical
2452        // degenerate-at-the-high-end shape and now share one canonical
2453        // bracket helper. The bracket precedes the sibling
2454        // `:restart-window` zero-floor / canonical-millisecond arms so
2455        // an over-cap `max_restarts` paired with a structurally invalid
2456        // window surfaces the bracket diagnostic first, mirroring the
2457        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
2458        // ordering on the peer `:politicas :circuit-breaker` slot.
2459        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
2460        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
2461        // accessor rather than the raw `self.max_restarts` field access —
2462        // the one production consumer of the per-`:supervisor`
2463        // restart-budget-count scalar now keys off exactly one typed
2464        // dispatch on the substrate primitive, so any future rebrand on
2465        // the axis (a per-cluster restart-budget override the operator
2466        // pins through a future `:supervisor :max-restarts-overrides`
2467        // slot, a per-tenant restart-budget-alias table the M4 CR
2468        // materializer resolves per-CR) migrates as a single caixa-core
2469        // edit rather than a coordinated rewrite — sibling of the peer M3
2470        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
2471        // the per-`:politicas :circuit-breaker :max-failures` axis.
2472        crate::render::require_positive_bounded_u32(
2473            self.max_restarts(),
2474            SUPERVISOR_MAX_RESTARTS_MAX,
2475            || SupervisorError::ZeroMaxRestarts,
2476            SupervisorError::max_restarts_exceeds_cap,
2477        )?;
2478        // Route the [`SupervisorSpec::validate`] `:restart-window`
2479        // zero-floor + integer-millisecond canonical-form + upper-cap
2480        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
2481        // accessor rather than the raw `self.restart_window` field access —
2482        // the one production consumer of the per-`:supervisor`
2483        // restart-intensity-denominator scalar now keys off exactly one
2484        // typed dispatch on the substrate primitive, so any future rebrand
2485        // on the axis (a per-cluster restart-window override the operator
2486        // pins through a future `:supervisor :restart-window-overrides`
2487        // slot, a per-tenant restart-window-alias table the M4 CR
2488        // materializer resolves per-CR) migrates as a single caixa-core
2489        // edit rather than a coordinated rewrite — sibling of the peer M2
2490        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
2491        // on the per-`:limits :wall-clock` axis and the peer M3
2492        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
2493        // per-`:politicas :timeout` axis.
2494        if let Some(w) = self.restart_window() {
2495            // Zero-floor + integer-millisecond canonical-form +
2496            // upper-cap bracket on the typed `:restart-window` axis.
2497            // See
2498            // [`crate::render::require_positive_canonical_bounded_duration`]
2499            // for the full three-arm ordering discipline (zero-floor
2500            // strictly precedes canonical-form so `Duration::ZERO`
2501            // surfaces the self-locating `RestartWindowZero`
2502            // diagnostic; canonical-form strictly precedes the cap arm
2503            // so a sub-millisecond above-cap value surfaces the more
2504            // fundamental round-trip-shape diagnostic first) and the
2505            // three peer typed-`Duration` sites that share this
2506            // canonical bracket ([`crate::MeshPolicy::timeout`],
2507            // [`crate::CircuitBreaker::window`],
2508            // [`crate::LimitsSpec::wall_clock`]). Every validated
2509            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2510            // (1ms..=1h), integer-millisecond granularity.
2511            crate::render::require_positive_canonical_bounded_duration(
2512                w,
2513                SUPERVISOR_RESTART_WINDOW_MAX,
2514                || SupervisorError::RestartWindowZero,
2515                SupervisorError::restart_window_not_canonical,
2516                SupervisorError::restart_window_exceeds_cap,
2517            )?;
2518        }
2519        // Route the per-child DNS-1123 / semver-requirement / duplicate-
2520        // detection fan-out loop through the lifted named per-slot gate
2521        // [`SupervisorSpec::validate_children`] rather than an inline
2522        // three-per-child cascade — every future consumer that wants to
2523        // re-check only the `:children` slot's per-entry axes (the M4
2524        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2525        // admission webhook re-validating one added/renamed child, the
2526        // future wasm-operator's per-child dynamic-add re-validator on
2527        // the `SimpleOneForOne` runtime-add path once dynamic-children
2528        // graduate to a typed slot, a future partial re-validator on a
2529        // per-`:children`-entry patch) reaches every per-entry axis
2530        // through one dispatch rather than re-inlining the three-arm
2531        // cascade in lockstep with `validate` or paying the peer
2532        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
2533        // reach one entry check. Sibling of the peer M3 mesh-slot
2534        // per-slot gate family (`validate_membros` — the exact peer on
2535        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
2536        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
2537        // `validate_placement`; `validate_politicas` routing through
2538        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
2539        // per-slot gate discipline now spans both the M3 mesh-slot
2540        // family and the M2 `:children` per-child-cascade axis on one
2541        // shape: one named per-slot gate per typed per-entry loop.
2542        self.validate_children()?;
2543        Ok(())
2544    }
2545
2546    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
2547    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
2548    /// gate, and duplicate-`:caixa` dedup arm into one call every
2549    /// consumer that wants to re-validate one `:children` entry (or the
2550    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
2551    /// admits reaches through.
2552    ///
2553    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
2554    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
2555    /// three-per-entry shape (DNS-1123 name + semver-requirement +
2556    /// duplicate-`:caixa` dedup), lifted to one named substrate
2557    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2558    /// materializer's admission webhook re-checking one added or renamed
2559    /// child, the future wasm-operator's per-child dynamic-add
2560    /// re-validator on the `SimpleOneForOne` runtime-add path once
2561    /// dynamic-children graduate to a typed slot, a future partial
2562    /// re-validator on a per-`:children`-entry patch — each reaches the
2563    /// three per-entry axes through this one dispatch rather than
2564    /// re-inlining the three-arm cascade in lockstep with `validate`
2565    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
2566    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
2567    /// reach one entry check.
2568    ///
2569    /// Self-contained on `&self` — resolves its own dedup `HashSet`
2570    /// through [`SupervisorSpec::children`] rather than borrowing one
2571    /// threaded down from `validate`, the same posture the peer M3
2572    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
2573    /// [`crate::AplicacaoSpec::validate_contratos`],
2574    /// [`crate::AplicacaoSpec::validate_entrada`],
2575    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
2576    /// consumer that reaches this gate directly (without first calling
2577    /// `validate`) still runs the full per-child cascade — pinned by
2578    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2579    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2580    /// + `validate_children_is_self_contained_on_children_slot`.
2581    ///
2582    /// The three per-entry arms run in the same canonical order the
2583    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
2584    /// the diagnostic every author-declared per-`:children` entry surfaces
2585    /// through `validate` is byte-equal to the diagnostic this gate
2586    /// surfaces when called directly — the equivalence-pin pair
2587    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2588    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2589    /// asserts the two altitudes discriminate the same set on every
2590    /// per-entry-covered input.
2591    pub fn validate_children(&self) -> Result<(), SupervisorError> {
2592        let mut seen = std::collections::HashSet::new();
2593        for child in self.children() {
2594            // Every emitted cluster artifact's `metadata.name` for a
2595            // supervised child derives from this `:children :caixa` value
2596            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
2597            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
2598            // label value on every child's pod identity, and the per-
2599            // child K8s [`Service`][svc] `metadata.name` the future
2600            // wasm-operator (M3) provisions for inter-child supervision
2601            // tree wiring. Each apiserver-side schema on each landing
2602            // site enforces the DNS-1123 label rule on admission; a
2603            // structurally invalid child name (`"Worker"`, `"my_worker"`,
2604            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
2605            // UUID-shaped mistaken-identity slug) silently passes the
2606            // prior empty-/duplicate-only gate and the failure surfaces
2607            // at `kubectl apply` time as a `metadata.name: Invalid value`
2608            // rejection, far from the source caixa.lisp, with no field
2609            // naming the offending `:children` entry. Lifting the gate
2610            // to caixa-build time mirrors the `:membros :caixa` value-
2611            // shape trajectory (3f9d7a0) and the `:placement :clusters`
2612            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
2613            // identifier axis — the supervisor tree's child names —
2614            // through the lifted
2615            // [`crate::render::require_valid_dns_1123_label`] gate the
2616            // seven peer name axes (`:membros :caixa`, `:placement
2617            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
2618            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
2619            // route through, so drift between the eight axes' accepted
2620            // DNS-1123-label sets is structurally impossible.
2621            //
2622            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
2623            crate::render::require_valid_dns_1123_label(
2624                child.nome(),
2625                || SupervisorError::EmptyChildName,
2626                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
2627            )?;
2628            // The author surface for `:children :versao` is the same
2629            // Cargo-shaped semver requirement string `:deps :versao` and
2630            // `:membros :versao` carry — and the lacre pipeline resolves
2631            // all three axes through the same
2632            // [`crate::version::parse_requirement`] entry-point. The
2633            // shared [`crate::render::require_valid_versao_requirement`]
2634            // helper brackets the empty-first + parse cascade both peer
2635            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
2636            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
2637            // :versao`) route through, so drift between the three axes'
2638            // accepted requirement sets is structurally impossible and
2639            // the parse-side no-op the empty-first arm closes (semver's
2640            // empty parse yields an implicit `*`) lives in exactly one
2641            // predicate. Every `ChildSpec::versao` past validate is
2642            // round-trippable through [`crate::parse_requirement`]
2643            // without re-checking at the resolver layer, and the three
2644            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
2645            // are now structurally equivalent by construction.
2646            crate::render::require_valid_versao_requirement(
2647                child.versao_requirement(),
2648                || SupervisorError::empty_child_version(child.nome()),
2649                |reason| {
2650                    SupervisorError::child_versao_invalid(
2651                        child.nome(),
2652                        child.versao_requirement(),
2653                        reason,
2654                    )
2655                },
2656            )?;
2657            crate::render::insert_first_seen(&mut seen, child.nome(), || {
2658                SupervisorError::duplicate_child_caixa(child.nome())
2659            })?;
2660        }
2661        Ok(())
2662    }
2663}
2664
2665/// Cross-slot coherence gate on the supervision tree: no
2666/// `:children :caixa` entry may name the supervisor's own `:nome`.
2667///
2668/// A supervisor that lists itself as a child is a degenerate self-parent
2669/// — the supervision tree is a DAG rooted at the supervisor (OTP child
2670/// specs reference *distinct* child processes; a supervisor is never its
2671/// own child), and the wasm-operator's hierarchical reconciliation would
2672/// otherwise be handed a node that is its own parent: a one-node cycle it
2673/// either rejects far from the source `caixa.lisp` or recurses on. Because
2674/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
2675/// lacre closure root), a child whose `:caixa` equals the supervisor's
2676/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
2677///
2678/// Lives outside [`SupervisorSpec::validate`] because the typed view
2679/// carries the children but not the parent `:nome`; mirrors the
2680/// cross-slot precedence gate `validate_upgrade_from_against_versao`
2681/// (which likewise reads one slot against another at the
2682/// [`crate::layout`] wire-up site) and the mesh self-edge gate
2683/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
2684/// node to itself is structurally not a tree/mesh edge" discipline, here
2685/// on the supervision-tree axis.
2686pub fn validate_no_self_supervision(
2687    children: &[ChildSpec],
2688    parent_nome: &str,
2689) -> Result<(), SupervisorError> {
2690    for child in children {
2691        if child.nome() == parent_nome {
2692            return Err(SupervisorError::child_supervises_self(parent_nome));
2693        }
2694    }
2695    Ok(())
2696}
2697
2698#[derive(Debug, Error, PartialEq, Eq)]
2699pub enum SupervisorError {
2700    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
2701    NoChildren { estrategia: RestartStrategy },
2702    #[error(
2703        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
2704    )]
2705    SimpleOneForOneWithStaticChildren,
2706    #[error(":max-restarts must be > 0")]
2707    ZeroMaxRestarts,
2708    #[error(
2709        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
2710         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
2711         restart-intensity policy into a no-op supervisor: the escalation threshold is \
2712         structurally so high that no realistic restarts-per-:restart-window traffic shape \
2713         can reach it, so the supervisor never escalates to its parent and a bad child can \
2714         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
2715         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
2716         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2717         materializer's admission webhook) emits a `:max-restarts` declaration that is \
2718         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
2719         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
2720         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
2721         band) or restructure the supervision tree (split the flaky child into its own \
2722         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
2723    )]
2724    MaxRestartsExceedsCap { max_restarts: u32 },
2725    #[error(
2726        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
2727         requires Period > 0; a zero window either trips on the first failure or \
2728         never trips depending on operator interpretation. Omit :restart-window to \
2729         express `never reset`; carry a positive duration to express the window."
2730    )]
2731    RestartWindowZero,
2732    #[error(
2733        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
2734         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
2735         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
2736         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
2737         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
2738    )]
2739    RestartWindowNotCanonical { window: Duration },
2740    #[error(
2741        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
2742         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
2743         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
2744         failure-counting window is structurally so long that transient restarts are never \
2745         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
2746         when the child has exceeded its restart budget within the recent window` to `trip the \
2747         parent when the child has exceeded its restart budget over its lifetime`, and the \
2748         supervisor's reset semantic never reaches the child — every typed-slot consumer \
2749         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
2750         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2751         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
2752         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
2753         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
2754         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
2755         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
2756         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
2757         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
2758         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
2759         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
2760         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
2761         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
2762         hiding it behind a rolling-window declaration the cap arm rejects)"
2763    )]
2764    RestartWindowExceedsCap { window: Duration },
2765    #[error("child entry has empty :caixa name")]
2766    EmptyChildName,
2767    #[error(
2768        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
2769         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
2770         name / label value the child name lands in — the per-child \
2771         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
2772         label value, and the future wasm-operator per-child Service `metadata.name` \
2773         — each apiserver-side schema rejects names that don't match; use a \
2774         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
2775    )]
2776    ChildCaixaInvalid { caixa: String, reason: String },
2777    #[error("child {caixa:?} has empty :versao constraint")]
2778    EmptyChildVersion { caixa: String },
2779    #[error(
2780        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
2781         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
2782         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
2783         `:membros :versao` carry; the lacre pipeline resolves all three \
2784         through the same parser)"
2785    )]
2786    ChildVersaoInvalid {
2787        caixa: String,
2788        versao: String,
2789        reason: String,
2790    },
2791    #[error(
2792        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
2793         child_spec.id per supervisor; duplicate children materialize as duplicate \
2794         ComputeUnits in the rendered chart, one silently overwriting the other)"
2795    )]
2796    DuplicateChildCaixa { caixa: String },
2797    #[error(
2798        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
2799         never its own child (the supervision tree is a DAG rooted at the supervisor; \
2800         OTP child specs reference distinct child processes). Since every :nome is a \
2801         globally-unique substrate identity, a child naming the supervisor's own :nome \
2802         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
2803         self-referential :children entry or rename it to the actual child caixa."
2804    )]
2805    ChildSupervisesSelf { caixa: String },
2806}
2807
2808// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
2809// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
2810// and [`validate_no_self_supervision`] onto one substrate primitive per
2811// typed variant — the sibling on `SupervisorError` of the four uniform-shape
2812// `LayoutError`-envelope constructor families the peer
2813// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
2814// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
2815// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
2816// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
2817// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
2818// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
2819// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
2820// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
2821// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
2822// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
2823// variants on `{ de, para }`) already at that discipline on the peer
2824// `AplicacaoError` envelopes.
2825//
2826// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
2827// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
2828// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
2829// self-supervision arm) opened the identical
2830// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
2831// the exact "same block re-inlined at every consumer" shape the PRIME
2832// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
2833// `AplicacaoError` families each closed on their sibling envelopes. The
2834// three variants share one `{ caixa: String }` shape, so the fold routes
2835// each wire-up site through one dispatch per typed variant.
2836//
2837// The macro below generates one static constructor per variant of shape
2838// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
2839// collapses onto one dispatch:
2840// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
2841// struct-literal on the same `&str` fixture. The uniform one-field
2842// construction (`caixa: caixa.to_string()`) is spelled once — inside the
2843// macro — rather than at every wire-up site. Every constructor is
2844// `#[must_use]` so a caller who mistakenly discards the constructed error
2845// trips a compile warning at the wire-up site.
2846//
2847// Every future consumer that wants to construct one of these three
2848// variants outside `SupervisorSpec::validate_children` /
2849// `validate_no_self_supervision` — a deferred
2850// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2851// webhook re-checking one added/renamed child, a future
2852// `feira validate --supervisor` per-caixa admission verb, a per-child
2853// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
2854// once dynamic-children graduate to a typed slot, a per-Supervisor
2855// overlay resolver rejecting a duplicate/self-supervising child against
2856// a cluster-local snapshot — now reaches each variant through one call
2857// rather than re-inlining the three-line struct-literal in lockstep
2858// with the three in-crate wire-up sites.
2859macro_rules! supervisor_caixa_only_ctors {
2860    ($($ctor:ident => $variant:ident),* $(,)?) => {
2861        impl SupervisorError {
2862            $(
2863                #[doc = concat!(
2864                    "Construct a [`SupervisorError::",
2865                    stringify!($variant),
2866                    "`] naming the offending `:children :caixa` (or ",
2867                    "supervisor `:nome`, on the self-supervision arm). ",
2868                    "Folds the uniform `Self::",
2869                    stringify!($variant),
2870                    " { caixa: caixa.to_string() }` one-field ",
2871                    "struct-literal onto one substrate primitive so ",
2872                    "every [`SupervisorSpec::validate_children`] / ",
2873                    "[`validate_no_self_supervision`] wire-up on this ",
2874                    "variant reads through one dispatch rather than the ",
2875                    "pre-lift open-coded struct-literal block."
2876                )]
2877                #[must_use]
2878                pub fn $ctor(caixa: &str) -> Self {
2879                    Self::$variant { caixa: caixa.to_string() }
2880                }
2881            )*
2882        }
2883    };
2884}
2885
2886supervisor_caixa_only_ctors! {
2887    empty_child_version => EmptyChildVersion,
2888    duplicate_child_caixa => DuplicateChildCaixa,
2889    child_supervises_self => ChildSupervisesSelf,
2890}
2891
2892// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
2893// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
2894// one substrate primitive per typed variant — the M2 supervisor-side siblings
2895// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
2896// already lifted through the sibling
2897// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
2898// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
2899// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
2900// String }` two-slot shape the peer seven-variant
2901// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
2902// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
2903// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
2904// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
2905// variant carries the `{ caixa: String, versao: String, reason: String }`
2906// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
2907// carries on the same `:versao` value-shape.
2908//
2909// Each of the two wire-up sites opened the same closure-shaped
2910// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
2911// [versao: child.versao_requirement().to_string(),] reason }` block inside
2912// the paired [`crate::render::require_valid_dns_1123_label`] and
2913// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
2914// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
2915// as a bug, on the same altitude the peer `AplicacaoError` /
2916// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
2917// families already closed on their sibling envelopes.
2918//
2919// The two `#[must_use]` inherent constructors below fold each wire-up onto
2920// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
2921// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
2922// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
2923// The uniform per-field `.to_string()` / `.into()` construction is spelled
2924// once — inside each ctor body — rather than at every wire-up site. The
2925// `reason: impl Into<String>` bound accepts both `&str` literals and
2926// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
2927// diagnostic shape at the lift, matching the peer
2928// [`aplicacao_field_reason_ctors!`] and
2929// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
2930// sibling envelopes.
2931//
2932// Every future consumer that wants to construct one of these two variants
2933// outside `SupervisorSpec::validate_children` — a deferred
2934// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
2935// re-checking one added/renamed child's `:caixa` or `:versao`, a future
2936// `feira validate --supervisor` per-caixa admission verb, a per-child
2937// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
2938// dynamic-children graduate to a typed slot, a per-Supervisor overlay
2939// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
2940// cluster-local snapshot — now reaches each variant through one call rather
2941// than re-inlining the per-shape struct-literal block in lockstep with the
2942// two in-crate wire-up sites.
2943impl SupervisorError {
2944    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
2945    /// offending `:children :caixa` value under the given `reason`. Folds
2946    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
2947    /// reason: reason.into() }` two-slot struct-literal onto one substrate
2948    /// primitive so every wire-up on this variant reads through one
2949    /// dispatch, matching the peer
2950    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
2951    /// sibling `AplicacaoError { caixa: String, reason: String }`
2952    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
2953    /// outputs through the `impl Into<String>` bound.
2954    #[must_use]
2955    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
2956        Self::ChildCaixaInvalid {
2957            caixa: caixa.to_string(),
2958            reason: reason.into(),
2959        }
2960    }
2961
2962    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
2963    /// offending `:children :caixa` and its `:versao` requirement under
2964    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
2965    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
2966    /// reason.into() }` three-slot struct-literal onto one substrate
2967    /// primitive so every wire-up on this variant reads through one
2968    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
2969    /// { caixa, versao, reason }` three-slot axis on the peer
2970    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
2971    /// and `format!(…)` outputs through the `impl Into<String>` bound.
2972    #[must_use]
2973    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
2974        Self::ChildVersaoInvalid {
2975            caixa: caixa.to_string(),
2976            versao: versao.to_string(),
2977            reason: reason.into(),
2978        }
2979    }
2980}
2981
2982// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
2983// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
2984// three bracket-arms — one struct-literal at the `:children`-empty
2985// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
2986// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
2987// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
2988// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
2989// [`crate::render::require_positive_canonical_bounded_duration`]
2990// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
2991// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
2992// primitive per typed variant, matching the sibling
2993// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
2994// variants on the same `{ <field>: Duration | u32 }` shape) at that
2995// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
2996// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
2997// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
2998// wire-up site through one dispatch per typed variant without a runtime-
2999// work delta.
3000//
3001// Each of the four wire-up sites opened the identical
3002// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
3003// exact "same block re-inlined at every consumer" shape the PRIME
3004// DIRECTIVE names as a bug, on the same altitude the peer
3005// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
3006// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
3007// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
3008// the fold routes each wire-up site through one dispatch per typed
3009// variant.
3010//
3011// The macro below generates one static constructor per variant of shape
3012// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
3013// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
3014// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
3015// fixture — as a direct call at the [`SupervisorSpec::validate`]
3016// `:children`-empty refusal, or as a bare function pointer in the
3017// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
3018// [`crate::render::require_positive_bounded_u32`] /
3019// [`crate::render::require_positive_canonical_bounded_duration`] gate
3020// carries — rather than the pre-lift open-coded one-line closure over
3021// the same one-field struct-literal. `const fn` preserves the `Copy`-
3022// pass-through's zero-runtime-work property verbatim. Every constructor
3023// is `#[must_use]` so a caller who mistakenly discards the constructed
3024// error trips a compile warning at the wire-up site.
3025//
3026// Every future consumer that wants to construct one of these four
3027// variants outside `SupervisorSpec::validate` — a deferred
3028// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3029// webhook re-checking one edited `:estrategia` / `:max-restarts` /
3030// `:restart-window` slot against the cap + canonical-form cascade, a
3031// future `feira validate --supervisor` per-caixa admission verb re-
3032// running the shape gates on demand, a per-Supervisor overlay resolver
3033// rejecting an author-supplied slot against a cluster-local snapshot —
3034// now reaches each variant through one call rather than re-inlining the
3035// per-shape struct-literal block in lockstep with the four in-crate
3036// wire-up sites.
3037macro_rules! supervisor_scalar_ctors {
3038    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
3039        impl SupervisorError {
3040            $(
3041                #[doc = concat!(
3042                    "Construct a [`SupervisorError::",
3043                    stringify!($variant),
3044                    "`] naming the offending per-`:supervisor` `",
3045                    stringify!($field),
3046                    "` scalar. Folds the uniform `Self::",
3047                    stringify!($variant),
3048                    " { ",
3049                    stringify!($field),
3050                    " }` one-field `Copy`-pass-through struct-literal onto ",
3051                    "one substrate primitive so every per-axis wire-up on ",
3052                    "this variant reads through one dispatch — as a direct ",
3053                    "call (`SupervisorError::",
3054                    stringify!($ctor),
3055                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
3056                    "the same `Copy`-`",
3057                    stringify!($ty),
3058                    "` fixture) or as a bare function pointer in the ",
3059                    "`impl FnOnce(",
3060                    stringify!($ty),
3061                    ") -> SupervisorError` bracket-closure slot every ",
3062                    "`crate::render::require_positive_bounded_*` / ",
3063                    "`crate::render::require_positive_canonical_bounded_*` ",
3064                    "gate carries — rather than the pre-lift open-coded ",
3065                    "one-line closure over the same one-field struct-",
3066                    "literal. `const fn` preserves the `Copy`-pass-through's ",
3067                    "zero-runtime-work property verbatim."
3068                )]
3069                #[must_use]
3070                pub const fn $ctor($field: $ty) -> Self {
3071                    Self::$variant { $field }
3072                }
3073            )*
3074        }
3075    };
3076}
3077
3078supervisor_scalar_ctors! {
3079    no_children => NoChildren { estrategia: RestartStrategy },
3080    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
3081    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
3082    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
3083}
3084
3085/// Shared duration string codec for the typed slots that take a
3086/// duration (`restart_window`, `MeshPolicy::timeout`,
3087/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
3088/// reuse it without duplicating the parser.
3089pub mod duration_codec {
3090    use super::Duration;
3091    use serde::{Deserializer, Serializer};
3092
3093    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
3094        // Route through the canonical [`crate::render::serialize_option_via_str`]
3095        // — the substrate-side single-owner primitive for the forward
3096        // arm of the typed-magnitude codec family. See its docstring
3097        // for the full sibling roster.
3098        crate::render::serialize_option_via_str(v, s, render)
3099    }
3100
3101    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
3102        // Route through the canonical [`crate::render::deserialize_option_via_str`]
3103        // — the substrate-side single-owner primitive for the reverse
3104        // arm of the typed-magnitude codec family. See its docstring
3105        // for the full sibling roster.
3106        crate::render::deserialize_option_via_str(d, parse)
3107    }
3108
3109    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
3110        // Paired whitespace-rejection arm — same canonical-form
3111        // render-determinism discipline as the peer
3112        // `limits::parse_byte_size` / `limits::parse_duration` /
3113        // `limits::parse_millicores` /
3114        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
3115        // byte-scan closes the WhatWG-conformant whitespace bytes
3116        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
3117        // `char::is_whitespace` scan closes the strictly-complementary
3118        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
3119        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
3120        // codepoints) that `str::trim` at parse entry silently strips.
3121        // Either drift class would round-trip through `render` to a
3122        // *different* canonical form on next emit — breaking the
3123        // THEORY.md Part V render-determinism contract on three typed-
3124        // duration slots at once (`:supervisor :restart-window`,
3125        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
3126        // via the shared codec.
3127        //
3128        // Routed through the lifted [`crate::render::reject_whitespace`]
3129        // primitive — the substrate-side single-owner paired-arm gate
3130        // every typed-magnitude codec in caixa-core shares.
3131        crate::render::reject_whitespace::<String, _, _>(
3132            s,
3133            |b| {
3134                format!(
3135                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
3136                 authoring form for the typed duration slots routed through this shared codec \
3137                 (`:supervisor :restart-window`, `:politicas :timeout`, \
3138                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3139                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
3140                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
3141                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
3142                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
3143                 Part V render-determinism contract every typed slot carries. Strip every \
3144                 whitespace byte (write `\"30s\"` verbatim)"
3145                )
3146            },
3147            |ch| {
3148                format!(
3149                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
3150                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
3151                 duration slots routed through this shared codec (`:supervisor \
3152                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
3153                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
3154                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
3155                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
3156                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
3157                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
3158                 `White_Space` property, strictly wider than the ASCII byte set) silently \
3159                 strips it at parse entry, and the value round-trips through `render` to \
3160                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
3161                 the THEORY.md Part V render-determinism contract every typed slot \
3162                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
3163                 verbatim with only ASCII bytes)",
3164                    cp = ch as u32
3165                )
3166            },
3167        )?;
3168        let s = s.trim();
3169        // Routed through the lifted
3170        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
3171        // the single-owner split every ASCII-alphabetic-unit typed-
3172        // magnitude codec in caixa-core (`limits::parse_byte_size` /
3173        // `limits::parse_duration` / this shared duration codec) shares.
3174        // See its docstring for the full sibling roster on the same
3175        // primitive altitude.
3176        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
3177        let num_trim = num_part.trim();
3178        // The canonical authoring form for every typed slot routed
3179        // through this shared codec — `:supervisor :restart-window`,
3180        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
3181        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
3182        // non-negative integer with no decimal point and no leading
3183        // sign, so the parser's accepted set must match for
3184        // serialize/deserialize to round-trip without canonical-form
3185        // drift. Until this gate landed the parser accepted any
3186        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
3187        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
3188        // tripped the value to a *different* canonical string on the
3189        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
3190        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
3191        // — breaking the THEORY.md Part V render-determinism contract
3192        // on three typed slots at once. Same canonical-form discipline
3193        // `crate::limits::parse_duration` (818dd38, the immediate
3194        // predecessor on the peer `:limits :wall-clock` codec) applies;
3195        // this gate lifts the discipline onto the shared codec that
3196        // backs the remaining three typed-duration slots in caixa-core.
3197        //
3198        // Strict canonical form: every byte of the magnitude is an
3199        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
3200        // inputs the gate distinguishes "non-canonical-but-numeric"
3201        // (parses as f64 or i64 — surfaced with a self-locating
3202        // diagnostic naming the canonical authoring form, the
3203        // round-trip drift each rejected shape would produce on first
3204        // serialize, and the canonical-form remediation) from
3205        // "garbage" (parses as neither — surfaced with the existing
3206        // narrower "bad duration magnitude" wording so its diagnostic
3207        // shape remains stable for the parser-shape footgun case).
3208        // The pre-existing `num < 0.0` arm is now unreachable — the
3209        // digit-only gate strictly precedes magnitude parsing, and a
3210        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
3211        // non-canonical-but-numeric branch with the `-30` named
3212        // verbatim in the diagnostic rather than the prior
3213        // value-laundered "negative duration in \"-30s\"" wording.
3214        //
3215        // Routed through the lifted
3216        // [`crate::render::is_digit_only_magnitude`] predicate — the
3217        // same source of truth the four peer typed-magnitude codec
3218        // sites share.
3219        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
3220        if !digit_only {
3221            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
3222            if numeric {
3223                return Err(format!(
3224                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
3225                     canonical authoring form for the typed duration slots routed through \
3226                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3227                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3228                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
3229                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
3230                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
3231                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
3232                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
3233                     THEORY.md Part V render-determinism contract every typed slot carries. \
3234                     Pick an integer magnitude in the unit that divides cleanly (write \
3235                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
3236                ));
3237            }
3238            return Err(format!("bad duration magnitude in {s:?}"));
3239        }
3240        // Leading-zero arm — peer with the `rate_limit_codec` leading-
3241        // zero arm (4f46830) on the same canonical-form render-
3242        // determinism axis. The digit-only gate accepts `"030s"`,
3243        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
3244        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
3245        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
3246        // *different* canonical string on the next emit, breaking the
3247        // THEORY.md Part V render-determinism contract the same way
3248        // `"+30s"` did before the leading-`+` arm landed. The single-
3249        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
3250        // losslessly through `render` (`render(Duration::ZERO)` emits
3251        // `"0s"`) — the downstream semantic-zero gates (e.g.
3252        // `SupervisorError::ZeroRestartWindow` on
3253        // `:supervisor :restart-window`,
3254        // `AplicacaoError::PolicyTimeoutZero` /
3255        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
3256        // duration slots) refuse zero-magnitude authoring at the typed-
3257        // validate layer above, so the single-byte `"0"` stays in the
3258        // accepted set at this codec layer and the diagnostic
3259        // partitioning between canonical-form drift (this arm) and
3260        // semantic-zero (the downstream gates) remains stable.
3261        // Peer with the future leading-zero arms on the two remaining
3262        // typed-magnitude codecs the trajectory acknowledges:
3263        // `limits::parse_duration` backing `:limits :wall-clock`,
3264        // `limits::parse_byte_size` backing `:limits :memory` — each
3265        // carries the same canonical-form-drift class today; this
3266        // gate lands the discipline on the shared duration codec
3267        // first because the `rate_limit_codec` predecessor on the
3268        // same canonical-form-drift axis is the closest peer on the
3269        // trajectory.
3270        //
3271        // Routed through the lifted
3272        // [`crate::render::is_leading_zero_padded_magnitude`]
3273        // predicate — the same source of truth the four peer
3274        // typed-magnitude codec sites share.
3275        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
3276            return Err(format!(
3277                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
3278                 canonical authoring form for the typed duration slots routed through \
3279                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3280                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3281                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
3282                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
3283                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
3284                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
3285                 serialize — breaking the THEORY.md Part V render-determinism contract \
3286                 every typed slot carries. Strip the leading zeros (write \
3287                 `\"30s\"` instead of `\"030s\"`)"
3288            ));
3289        }
3290        // The digit-only gate guarantees every byte is `[0-9]`, and
3291        // the leading-zero arm above guarantees the magnitude is
3292        // either the single byte `"0"` or starts with `[1-9]`, so
3293        // the only way `u64::from_str` can fail here is overflow (the
3294        // magnitude exceeds `u64::MAX`). Surface that with an
3295        // overflow-shaped wording so the diagnostic names the offending
3296        // magnitude verbatim rather than collapsing onto the
3297        // non-canonical arm. The codec now operates on `u64` end-to-end
3298        // — every accepted magnitude is integer-exact; no f64 mantissa
3299        // drift between author-supplied magnitude and the consumer's
3300        // `Duration` value. Same shape `crate::limits::parse_duration`
3301        // (818dd38) carries on the peer `:limits :wall-clock` axis.
3302        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
3303            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
3304        })?;
3305        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
3306        // unit-arm dispatch through the canonical
3307        // [`crate::render::duration_from_integer_magnitude_and_unit`]
3308        // primitive — the substrate-side single-owner unit-dispatch
3309        // table every typed-duration codec in caixa-core routes
3310        // through (peer: `crate::limits::parse_duration` backing
3311        // `:limits :wall-clock`). Every unit conversion is integer-
3312        // exact for an integer magnitude; overflow surfaces via the
3313        // typed `DurationUnitError::Overflow { multiplier }`
3314        // discriminant so this arm reconstructs the pre-lift
3315        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
3316        // wording verbatim from `num` / `unit_trim` / the returned
3317        // `multiplier`, and the unknown-unit arm reconstructs the
3318        // pre-lift `"unknown duration unit \"<other>\""` wording from
3319        // the caller-scoped `unit_trim`. Load-bearing pinned by
3320        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
3321        let unit_trim = unit.trim();
3322        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
3323            |e| match e {
3324                crate::render::DurationUnitError::Overflow { multiplier } => format!(
3325                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
3326                ),
3327                crate::render::DurationUnitError::UnknownUnit => {
3328                    format!("unknown duration unit {unit_trim:?}")
3329                }
3330            },
3331        )?;
3332        Ok(dur)
3333    }
3334
3335    /// Render a [`Duration`] in the canonical pleme-io duration string
3336    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
3337    /// caixa typed-duration slot serializes to and the same form K8s
3338    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
3339    /// EnvoyConfig per-route timeouts both expect (an integer
3340    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
3341    /// `+`). Lifted to `pub` so caixa-side renderers
3342    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
3343    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
3344    /// emitter, the future caixa-otel collector pipeline emitter) can
3345    /// consume the same canonical formatter without re-inlining the
3346    /// magnitude/unit decision tree (and inheriting the same drift
3347    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
3348    /// downstream apply-time parsing in non-obvious ways).
3349    pub fn render(d: Duration) -> String {
3350        let total_ms = d.as_millis();
3351        if total_ms == 0 {
3352            return "0s".into();
3353        }
3354        if total_ms.is_multiple_of(3600 * 1000) {
3355            return format!("{}h", total_ms / (3600 * 1000));
3356        }
3357        if total_ms.is_multiple_of(60 * 1000) {
3358            return format!("{}m", total_ms / (60 * 1000));
3359        }
3360        if total_ms.is_multiple_of(1000) {
3361            return format!("{}s", total_ms / 1000);
3362        }
3363        format!("{total_ms}ms")
3364    }
3365
3366    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
3367    ///
3368    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
3369    /// largest divisor unit, so any sub-millisecond residue
3370    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
3371    /// §V.2.7 render-determinism contract:
3372    ///
3373    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
3374    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
3375    ///     `1_000_000` ns ≠ original `1_500_000` ns;
3376    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
3377    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
3378    ///     on every typed-`Duration` slot then rejects on re-validate.
3379    ///
3380    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
3381    /// the codec's round-trippable accepted set lives in exactly one place —
3382    /// every typed-`Duration` slot that routes through this shared codec
3383    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
3384    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
3385    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
3386    /// every typed-`Duration` slot whose own codec shares the same
3387    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
3388    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
3389    /// pair) calls this predicate from its `validate()` to bracket the
3390    /// accepted set against the codec's accepted set, structurally. Drift
3391    /// between the codec's granularity and any typed slot's accepted set is
3392    /// then a single-source-of-truth edit at this predicate rather than a
3393    /// silent round-trip break the next consumer discovers at apply time.
3394    ///
3395    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
3396    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
3397    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
3398    /// family — same "typed-slot's valid set matches its codec's accepted
3399    /// set, structurally" discipline carried at the codec layer.
3400    #[must_use]
3401    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
3402        d.subsec_nanos().is_multiple_of(1_000_000)
3403    }
3404}
3405
3406/// Required-Duration variant for fields that aren't Option<Duration>.
3407pub mod duration_codec_required {
3408    use super::Duration;
3409    use serde::{Deserialize, Deserializer, Serializer};
3410
3411    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
3412        s.serialize_str(&super::duration_codec::render(*v))
3413    }
3414
3415    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
3416        let s = String::deserialize(d)?;
3417        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
3418    }
3419}
3420
3421#[cfg(test)]
3422mod tests {
3423    use super::*;
3424
3425    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
3426        ChildSpec {
3427            caixa: name.into(),
3428            versao: ver.into(),
3429            restart,
3430        }
3431    }
3432
3433    #[test]
3434    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
3435        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
3436        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
3437        // posture. Each accessor projects the per-`:children :caixa`
3438        // / per-`:children :versao` [`String`] storage through the
3439        // `pub const fn` [`String::as_str`] (const-stable since Rust
3440        // 1.87, well within the workspace MSRV) — any future
3441        // accidental downgrade to non-`const` fails the corresponding
3442        // `<name>_via_const_fn` wrapper at caixa-core build time with
3443        // E0015 (`cannot call non-const method`), strictly stronger
3444        // than a runtime `assert!`. Sibling of the peer
3445        // per-M2/M3/universal-axis `String → &str` scalar-accessor
3446        // family pins on the sibling `const`-eval-surface passes
3447        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
3448        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
3449        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
3450        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
3451        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
3452        // [`crate::aplicacao::Entrada::destination`] at the M3
3453        // ingress axis,
3454        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
3455        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
3456        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
3457        // axis, and the per-`:contratos`
3458        // [`crate::aplicacao::WitContract::source`] /
3459        // [`crate::aplicacao::WitContract::destination`] /
3460        // [`crate::aplicacao::WitContract::world_ref`] trio the
3461        // sibling pin at 279823b already anchors).
3462        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
3463            c.nome()
3464        }
3465        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
3466            c.versao_requirement()
3467        }
3468        for (caixa, versao) in [
3469            ("worker-a", "^0.1"),
3470            ("worker-b", "~0.2.3"),
3471            ("collector", "*"),
3472        ] {
3473            let c = child(caixa, versao, RestartPolicy::Permanent);
3474            assert_eq!(nome_via_const_fn(&c), c.nome());
3475            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
3476            assert_eq!(c.nome(), caixa);
3477            assert_eq!(c.versao_requirement(), versao);
3478        }
3479    }
3480
3481    #[test]
3482    fn supervisor_children_slice_return_accessor_is_const_fn() {
3483        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
3484        // `const`-eval-surface posture. The accessor destructures the
3485        // per-`:children` `Vec<ChildSpec>` storage through the
3486        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
3487        // 1.66, well within the workspace MSRV) — any future
3488        // accidental downgrade to non-`const` fails
3489        // `children_via_const_fn` at caixa-core build time with E0015
3490        // (`cannot call non-const method`), strictly stronger than a
3491        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
3492        // `Vec → &[T]` slice-return accessor family pin
3493        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
3494        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
3495        // per-`:membros` / per-`:contratos` slice-return axes, and of
3496        // the peer M2 upgrade-appup axis pin
3497        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
3498        // on the per-`:upgrade-from :instructions` slice-return axis.
3499        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
3500            s.children()
3501        }
3502        // Sweep both the empty-children (leaf-supervisor with no
3503        // static children — the `SimpleOneForOne` dynamic-child
3504        // arm's canonical shape) and the populated-children
3505        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
3506        // arm's canonical shape) axes so the accessor carries a
3507        // const-dispatch pin on both arms.
3508        let s_empty = SupervisorSpec {
3509            estrategia: RestartStrategy::SimpleOneForOne,
3510            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3511            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3512            children: vec![],
3513        };
3514        assert!(children_via_const_fn(&s_empty).is_empty());
3515        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
3516        let s_full = SupervisorSpec {
3517            estrategia: RestartStrategy::OneForOne,
3518            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3519            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3520            children: vec![
3521                child("worker-a", "^0.1", RestartPolicy::Permanent),
3522                child("worker-b", "~0.2.3", RestartPolicy::Transient),
3523                child("collector", "*", RestartPolicy::Temporary),
3524            ],
3525        };
3526        assert_eq!(children_via_const_fn(&s_full).len(), 3);
3527        assert_eq!(children_via_const_fn(&s_full), s_full.children());
3528    }
3529
3530    #[test]
3531    fn default_has_one_for_one_and_5_restarts_in_60s() {
3532        let s = SupervisorSpec::default();
3533        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
3534        assert_eq!(s.max_restarts, 5);
3535        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
3536        assert!(s.children.is_empty());
3537    }
3538
3539    #[test]
3540    fn validate_one_for_one_requires_children() {
3541        let mut s = SupervisorSpec::default();
3542        s.children = vec![];
3543        assert!(matches!(
3544            s.validate().unwrap_err(),
3545            SupervisorError::NoChildren { .. }
3546        ));
3547        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
3548        s.validate().unwrap();
3549    }
3550
3551    #[test]
3552    fn validate_simple_one_for_one_forbids_static_children() {
3553        let mut s = SupervisorSpec {
3554            estrategia: RestartStrategy::SimpleOneForOne,
3555            ..SupervisorSpec::default()
3556        };
3557        s.children
3558            .push(child("w", "^0.1", RestartPolicy::Permanent));
3559        assert_eq!(
3560            s.validate().unwrap_err(),
3561            SupervisorError::SimpleOneForOneWithStaticChildren
3562        );
3563        s.children.clear();
3564        s.validate().unwrap();
3565    }
3566
3567    #[test]
3568    fn validate_rejects_zero_max_restarts() {
3569        let s = SupervisorSpec {
3570            max_restarts: 0,
3571            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3572            ..SupervisorSpec::default()
3573        };
3574        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
3575    }
3576
3577    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
3578    //
3579    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
3580    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
3581    // `:supervisor :max-restarts` axis — both fields are "trip the
3582    // next-higher protection layer after N events in a rolling window"
3583    // counters with identical degenerate-at-the-high-end shape, so the
3584    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
3585    // exactly as it lies in `1..=1000` on the breaker side.
3586
3587    #[test]
3588    fn validate_rejects_max_restarts_above_cap() {
3589        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
3590        // 1` is structurally one past the cap and silently passed
3591        // validate on every pre-gate codebase because the typed slot's
3592        // only check was the zero-floor arm. The no-op-supervisor vector
3593        // only surfaced at the runtime substrate (Erlang/OTP
3594        // MaxIntensity/Period ratio, the future wasm-operator's
3595        // per-supervisor restart-intensity counter) far from the source
3596        // caixa.lisp with no field naming the offending supervisor.
3597        let s = SupervisorSpec {
3598            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3599            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3600            ..SupervisorSpec::default()
3601        };
3602        assert_eq!(
3603            s.validate().unwrap_err(),
3604            SupervisorError::MaxRestartsExceedsCap {
3605                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3606            }
3607        );
3608    }
3609
3610    #[test]
3611    fn validate_rejects_max_restarts_far_above_cap() {
3612        // The `u32::MAX` worst case — the four-billion-restart
3613        // threshold a typo (`:max-restarts 4294967295`) or a
3614        // struct-literal copy-paste lands in the slot. Pin the cap
3615        // arm's coverage explicitly across the full `u32` overflow so
3616        // a future relaxation that drops the upper bound surfaces
3617        // here. Same shape every other typed-cap arm on this surface
3618        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
3619        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
3620        let s = SupervisorSpec {
3621            max_restarts: u32::MAX,
3622            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3623            ..SupervisorSpec::default()
3624        };
3625        assert_eq!(
3626            s.validate().unwrap_err(),
3627            SupervisorError::MaxRestartsExceedsCap {
3628                max_restarts: u32::MAX,
3629            }
3630        );
3631    }
3632
3633    #[test]
3634    fn validate_accepts_max_restarts_at_cap() {
3635        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
3636        // must validate. The cap is inclusive on the top edge,
3637        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
3638        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
3639        // discipline on the sibling capped axes. Pin the boundary
3640        // explicitly so a future off-by-one tightening
3641        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
3642        // here as a test failure rather than a silent contract
3643        // narrowing.
3644        let s = SupervisorSpec {
3645            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
3646            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3647            ..SupervisorSpec::default()
3648        };
3649        s.validate()
3650            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
3651    }
3652
3653    #[test]
3654    fn validate_accepts_max_restarts_typical_values() {
3655        // The documented production-playbook band positive-control
3656        // sweep — every value Erlang/OTP / Elixir / Riak Core /
3657        // RabbitMQ recommend (1..=100) must pass, plus a sweep
3658        // through the hyperscale band (200, 500, 1000) the cap
3659        // accepts. Pin the inclusive validated set explicitly so a
3660        // future tightening of the ceiling surfaces here.
3661        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
3662            let s = SupervisorSpec {
3663                max_restarts: n,
3664                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3665                ..SupervisorSpec::default()
3666            };
3667            s.validate()
3668                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
3669        }
3670    }
3671
3672    #[test]
3673    fn zero_max_restarts_takes_precedence_over_cap() {
3674        // The cross-arm ordering pin: `0` is structurally outside
3675        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
3676        // (cap), but the zero-floor diagnostic is the more
3677        // self-locating one (it directly names the counter-axis
3678        // remediation), so the validate gate must fire on zero first.
3679        // Same shape every other zero-then-shape ordering on this
3680        // surface uses (PolicyRetriesZero then
3681        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
3682        // PolicyBreakerMaxFailuresExceedsCap).
3683        let s = SupervisorSpec {
3684            max_restarts: 0,
3685            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3686            ..SupervisorSpec::default()
3687        };
3688        assert_eq!(
3689            s.validate().unwrap_err(),
3690            SupervisorError::ZeroMaxRestarts,
3691            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
3692        );
3693    }
3694
3695    #[test]
3696    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
3697        // The cross-arm ordering pin between the cap and the sibling
3698        // `:restart-window` gates (zero-window, canonical-window). A
3699        // supervisor carrying both an over-cap `max_restarts` AND a
3700        // structurally invalid window (zero, sub-ms) must surface the
3701        // cap diagnostic first — the cap arm is wired immediately
3702        // after the zero-restart arm and strictly before the window
3703        // arms, so the offending value the diagnostic names matches
3704        // the order the author would discover the gates by reading
3705        // top-to-bottom through `SupervisorSpec::validate`. Pin the
3706        // order so a future refactor that reorders the arms surfaces
3707        // here as a test failure rather than a silent diagnostic
3708        // regression. Peer of
3709        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
3710        // on the sibling `:politicas :circuit-breaker` slot.
3711        let s = SupervisorSpec {
3712            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3713            restart_window: Some(Duration::ZERO),
3714            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3715            ..SupervisorSpec::default()
3716        };
3717        assert_eq!(
3718            s.validate().unwrap_err(),
3719            SupervisorError::MaxRestartsExceedsCap {
3720                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3721            },
3722            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
3723        );
3724    }
3725
3726    #[test]
3727    fn max_restarts_cap_diagnostic_carries_offending_value() {
3728        // The diagnostic-shape pin: the offending `u32` is carried
3729        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
3730        // variant so the surfaced error message names the value the
3731        // author wrote (`":supervisor :max-restarts (50000) exceeds the
3732        // supervisor-policy ceiling …"`), not just the cap. Same
3733        // self-locating diagnostic shape every other typed-cap arm on
3734        // this surface carries
3735        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
3736        // the offending failure count verbatim,
3737        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
3738        // retries count verbatim).
3739        let s = SupervisorSpec {
3740            max_restarts: 50_000,
3741            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3742            ..SupervisorSpec::default()
3743        };
3744        let err = s.validate().unwrap_err();
3745        assert!(
3746            matches!(
3747                err,
3748                SupervisorError::MaxRestartsExceedsCap {
3749                    max_restarts: 50_000
3750                }
3751            ),
3752            "got {err:?}"
3753        );
3754        let msg = err.to_string();
3755        assert!(
3756            msg.contains("50000"),
3757            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
3758        );
3759    }
3760
3761    #[test]
3762    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
3763        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
3764        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
3765        // half of Learn You Some Erlang's worker-supervisor default,
3766        // sibling of the `60s` `Period` half that the paired
3767        // [`Default for SupervisorSpec`] impl already pins on the
3768        // sibling `restart_window` axis. Pinning the literal here
3769        // surfaces a future rebrand (a tightening to Elixir's `3`,
3770        // a widening to a per-cluster overlay the operator pins
3771        // through a future `:max-restarts-overrides` slot) as a
3772        // deliberate test edit, not a silent contract migration.
3773        // Peer of the sibling
3774        // [`supervisor_max_restarts_cap_pins_canonical_value`]
3775        // upper-bracket pin on the same axis.
3776        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
3777    }
3778
3779    #[test]
3780    fn default_max_restarts_helper_routes_through_lifted_default() {
3781        // Composition pin: the private `default_max_restarts()`
3782        // serde-`#[serde(default = "…")]` helper on
3783        // [`SupervisorSpec::max_restarts`] must route through the
3784        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3785        // typed `pub const` rather than a raw `5` literal. Prior to
3786        // the lift the helper carried an inline `5` with no compile-
3787        // time link back to the shared default, so the wire-format
3788        // author-omitted arm and the caixa-core
3789        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
3790        // arm could silently split on any future default rebrand.
3791        // Byte-parity against the lifted constant closes the split.
3792        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
3793    }
3794
3795    #[test]
3796    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
3797        // Composition pin: the [`Default for SupervisorSpec`] impl's
3798        // struct-literal `max_restarts` field must route through the
3799        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3800        // typed `pub const` (via the private helper this test's
3801        // sibling `default_max_restarts_helper_routes_through_lifted_default`
3802        // already pins onto the constant). Structurally: every
3803        // `SupervisorSpec::default()` call must yield a
3804        // `max_restarts` field byte-equal to the lifted constant
3805        // (the two paired defaults — the serde-side wire-format arm
3806        // and the struct-literal default arm — cannot silently split
3807        // on any future default rebrand). Peer of the sibling
3808        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
3809        // — this pin closes the byte-parity arm on the two paired
3810        // altitude entry points onto the shared substrate constant.
3811        assert_eq!(
3812            SupervisorSpec::default().max_restarts(),
3813            SUPERVISOR_MAX_RESTARTS_DEFAULT,
3814        );
3815    }
3816
3817    #[test]
3818    fn supervisor_restart_window_default_pins_otp_canonical_value() {
3819        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
3820        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
3821        // Learn You Some Erlang's worker-supervisor default, paired
3822        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
3823        // `MaxIntensity` half this constant is the sliding-window
3824        // denominator of on the same `MaxIntensity / Period`
3825        // restart-intensity ratio. Pinning the literal here surfaces a
3826        // future coherent rebrand of the paired default (Elixir's
3827        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
3828        // the operator pins through a future
3829        // `:restart-window-overrides` slot) as a deliberate test edit,
3830        // not a silent contract migration. Peer of the sibling
3831        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
3832        // paired-half pin on the same OTP-canonical default and the
3833        // [`supervisor_restart_window_cap_pins_canonical_value`]
3834        // upper-bracket pin on the same axis.
3835        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
3836    }
3837
3838    #[test]
3839    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
3840        // Composition pin: the [`Default for SupervisorSpec`] impl's
3841        // struct-literal `restart_window` field must route through the
3842        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3843        // typed `pub const` rather than a raw
3844        // `Duration::from_secs(60)` literal. Prior to this lift the
3845        // paired `{intensity, 5, 60}` OTP-canonical default was split
3846        // across two altitudes with no compile-time link between the
3847        // halves — the `MaxIntensity` half rode through the lifted
3848        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
3849        // `Period` half rode as an open-coded literal at the
3850        // composition site, so a future coherent rebrand of the paired
3851        // canonical would have had to migrate one half through the
3852        // constant and the other through a raw literal in lockstep.
3853        // Byte-parity against the lifted constant on the `Period` half
3854        // closes the split — the paired OTP-canonical default now
3855        // migrates as one unit on any future axis change. Peer of the
3856        // sibling
3857        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3858        // byte-parity pin on the paired `MaxIntensity` half.
3859        assert_eq!(
3860            SupervisorSpec::default().restart_window(),
3861            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3862        );
3863    }
3864
3865    #[test]
3866    fn supervisor_estrategia_default_pins_otp_canonical_value() {
3867        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
3868        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
3869        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
3870        // canonical default, paired with the sibling
3871        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
3872        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
3873        // this constant is the strategy discriminator of on the same
3874        // OTP-canonical worker-supervisor default. Pinning the arm here
3875        // surfaces a future coherent rebrand of the paired triple (Elixir's
3876        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
3877        // intensity/period axes leaving this strategy arm untouched, an OTP
3878        // `rest_for_one` widening once the substrate discovers startup-
3879        // order-coupled child cohorts as the more common worker-supervisor
3880        // shape, a per-cluster overlay the operator pins through a future
3881        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
3882        // supervision-canary roadmap acknowledges) as a deliberate test
3883        // edit, not a silent contract migration. Peer of the sibling
3884        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
3885        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3886        // paired-half pins on the same OTP-canonical default.
3887        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
3888    }
3889
3890    #[test]
3891    fn restart_strategy_default_routes_through_lifted_default() {
3892        // Composition pin: the [`Default for RestartStrategy`] impl's
3893        // return arm must route through the substrate-canonical
3894        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
3895        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
3896        // an inline `Self::OneForOne` with no compile-time link back to
3897        // the shared OTP-canonical `one_for_one` strategy the paired
3898        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
3899        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
3900        // `.unwrap_or_default()` (now
3901        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
3902        // so a future rebrand of the OTP-canonical strategy default (an
3903        // OTP `rest_for_one` widening once the substrate discovers
3904        // startup-order-coupled child cohorts as the more common worker-
3905        // supervisor shape, a per-cluster overlay the operator pins
3906        // through a future `:estrategia-overrides` slot) would have had to
3907        // be threaded through the `Default` impl and the two peer routes
3908        // in lockstep or the three consumers would silently split. Byte-
3909        // parity against the lifted constant closes the split. Peer of
3910        // the sibling
3911        // [`default_max_restarts_helper_routes_through_lifted_default`] +
3912        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3913        // composition pins on the paired `MaxIntensity` + `Period` halves.
3914        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
3915    }
3916
3917    #[test]
3918    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
3919        // Composition pin: the [`Default for SupervisorSpec`] impl's
3920        // struct-literal `estrategia` field must route through the
3921        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
3922        // `pub const` (either directly, or via the
3923        // [`RestartStrategy::default`] impl that the sibling
3924        // `restart_strategy_default_routes_through_lifted_default` pin
3925        // already routes onto the constant). Structurally: every
3926        // `SupervisorSpec::default()` call must yield an `estrategia`
3927        // field byte-equal to the lifted constant (the three paired
3928        // defaults — the [`Default for RestartStrategy`] impl arm, the
3929        // struct-literal default arm here, and the
3930        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
3931        // silently split on any future default rebrand). Peer of the
3932        // sibling
3933        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3934        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3935        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
3936        // of the same `SupervisorSpec::default()` composed altitude.
3937        assert_eq!(
3938            SupervisorSpec::default().estrategia(),
3939            SUPERVISOR_ESTRATEGIA_DEFAULT,
3940        );
3941    }
3942
3943    #[test]
3944    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
3945        // Composition pin: the [`Default for SupervisorSpec`] impl must
3946        // route through the substrate-canonical
3947        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
3948        // rather than a re-hand-authored struct-literal cascade. Sharpens
3949        // the sibling per-arm
3950        // `supervisor_spec_default_*_routes_through_lifted_default` pins
3951        // from a per-field lift into a whole-struct one-source-of-truth
3952        // pin — the derived-until-now [`Default::default`] and the
3953        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
3954        // construction, not by coincidence.
3955        //
3956        // A future extension of the OTP-canonical baseline (a fifth
3957        // `restart_intensity` field the Erlang/OTP `#supervisor` record
3958        // grows, a per-child-cohort split of the `restart_window` /
3959        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
3960        // CR materializer's admission-time overlay pass) reaches both
3961        // paths through exactly one edit on
3962        // [`SupervisorSpec::otp_canonical`] — the derived path could
3963        // silently disagree with the constructor's shape on any new
3964        // field whose [`Default::default`] resolves to a different arm
3965        // than the OTP-canonical baseline the constructor names, while
3966        // this delegated impl reaches the constructor directly and
3967        // picks up every future extension by construction.
3968        //
3969        // Fourth peer on the M2 / M3 typed-slot-spec
3970        // [`Default`]-through-const-ctor fold family — sibling of the
3971        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
3972        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
3973        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
3974        // (91641a4), and [`crate::BehaviorSpec`]
3975        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
3976        // per-`Option`-only-typed-slot folds — extended here onto the
3977        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
3978        // is not "everything `None`" but the Erlang/OTP-canonical
3979        // `{one_for_one, 5, 60}` worker-supervisor triple.
3980        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
3981    }
3982
3983    #[test]
3984    fn supervisor_spec_otp_canonical_byte_equals_default() {
3985        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
3986        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
3987        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
3988        // pin already asserts against the [`Default::default`] path.
3989        // Sharpens the pair-invariant into a per-constructor pin so a
3990        // future extension of [`SupervisorSpec`] with a fifth field
3991        // whose OTP-canonical shape is non-`Default::default`-equivalent
3992        // trips at caixa-core test time rather than at a downstream
3993        // consumer that composed [`SupervisorSpec::otp_canonical`] with
3994        // [`SupervisorSpec::validate`] as its "canonical baseline
3995        // seed".
3996        let canonical = SupervisorSpec::otp_canonical();
3997        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
3998        assert_eq!(canonical.max_restarts, 5);
3999        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
4000        assert!(canonical.children.is_empty());
4001    }
4002
4003    #[test]
4004    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
4005        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
4006        // remain callable from a `const`-bound position so downstream
4007        // `const`-context callers wanting a canonical OTP-baseline seed
4008        // can construct one at compile time without runtime dispatch on
4009        // the derived [`Default::default`]. Peer of the sibling
4010        // `pub const fn` [`crate::LimitsSpec::empty`] /
4011        // [`crate::aplicacao::MeshPolicy::empty`] /
4012        // [`crate::BehaviorSpec::empty`] constructors on the sibling
4013        // typed-slot-spec `pub const fn` axis. If a future edit breaks
4014        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
4015        // (a non-`const` field-default helper, a non-`const`-stable
4016        // container type promotion), this evaluation fails at
4017        // build time on this file rather than at a downstream
4018        // `const`-context call site.
4019        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
4020        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
4021        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
4022        assert_eq!(
4023            CANONICAL.restart_window,
4024            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4025        );
4026        assert!(CANONICAL.children.is_empty());
4027    }
4028
4029    #[test]
4030    fn supervisor_child_restart_default_pins_otp_canonical_value() {
4031        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
4032        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
4033        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
4034        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
4035        // half of the same OTP-shape supervisor-tree default set whose
4036        // per-`:supervisor` halves the sibling
4037        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
4038        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
4039        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
4040        // arm here surfaces a future rebrand of the per-child default (an
4041        // OTP-`transient` widening once the substrate discovers clean-
4042        // completion-aware children as the more common child shape, a
4043        // per-cluster overlay the operator pins through a future
4044        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
4045        // supervision-canary roadmap acknowledges) as a deliberate test
4046        // edit, not a silent contract migration. Peer of the sibling
4047        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
4048        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
4049        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4050        // value pins on the per-`:supervisor` halves.
4051        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
4052    }
4053
4054    #[test]
4055    fn restart_policy_default_routes_through_lifted_default() {
4056        // Composition pin: the [`Default for RestartPolicy`] impl's return
4057        // arm must route through the substrate-canonical
4058        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
4059        // than a raw `Self::Permanent` arm. Prior to the lift the impl
4060        // carried an inline `Self::Permanent` with no compile-time link
4061        // back to the OTP-shape supervisor-tree default set whose three
4062        // per-`:supervisor` halves already rode through lifted constants
4063        // — so a future coherent rebrand of the set would have had to
4064        // migrate three halves through typed constants and this fourth
4065        // through a raw enum arm in lockstep or the supervisor-level and
4066        // child-level defaults would silently drift apart. Byte-parity
4067        // against the lifted constant closes the split. Peer of the
4068        // sibling
4069        // [`restart_strategy_default_routes_through_lifted_default`]
4070        // composition pin on the per-`:supervisor` `:estrategia` axis.
4071        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
4072    }
4073
4074    #[test]
4075    fn child_spec_serde_default_restart_routes_through_lifted_default() {
4076        // Composition pin: the serde-side `#[serde(default)]` on
4077        // [`ChildSpec::restart`] — the wire-format author-omitted
4078        // `:children :restart` arm — must resolve onto the substrate-
4079        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
4080        // (via the [`Default for RestartPolicy`] impl the sibling
4081        // `restart_policy_default_routes_through_lifted_default` pin
4082        // already routes onto the constant). Structurally: a `ChildSpec`
4083        // deserialized from a payload that omits the `restart` key must
4084        // yield a `restart` field byte-equal to the lifted constant, so
4085        // the wire-format author-omitted arm and the
4086        // [`RestartPolicy::default`] impl arm cannot silently split on any
4087        // future default rebrand. Peer of the sibling
4088        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
4089        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4090        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4091        // byte-parity pins on the per-`:supervisor` halves of the same
4092        // author-omitted-slot resolution surface.
4093        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
4094            .expect("ChildSpec must deserialize with the restart key omitted");
4095        assert_eq!(
4096            omitted.restart(),
4097            SUPERVISOR_CHILD_RESTART_DEFAULT,
4098            "an author-omitted :children :restart slot must degrade onto \
4099             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
4100             {:?}, expected {:?})",
4101            omitted.restart(),
4102            SUPERVISOR_CHILD_RESTART_DEFAULT,
4103        );
4104    }
4105
4106    #[test]
4107    fn supervisor_max_restarts_cap_pins_canonical_value() {
4108        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
4109        // 1000 — the same ceiling the peer
4110        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
4111        // `:politicas :circuit-breaker :max-failures` axis (both are
4112        // "trip the next-higher protection layer after N events in a
4113        // rolling window" counters with identical
4114        // degenerate-at-the-high-end shape; uniform top edge so the
4115        // M4 CR materializers and the wasm-operator reconciler reach
4116        // for either field knowing the value is in `1..=1000`). Two
4117        // orders of magnitude above every documented Erlang/OTP /
4118        // Elixir / Riak Core / RabbitMQ production-playbook
4119        // recommendation band and below the clearly-pathological
4120        // "effectively no escalation" floor (10_000, 100_000,
4121        // u32::MAX). Pinning the literal value here surfaces a future
4122        // drift (a relaxation to 10_000, a tightening to 100) as a
4123        // deliberate test edit, not a silent contract narrowing.
4124        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
4125    }
4126
4127    #[test]
4128    fn validate_rejects_empty_child_name() {
4129        let s = SupervisorSpec {
4130            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4131            ..SupervisorSpec::default()
4132        };
4133        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
4134    }
4135
4136    #[test]
4137    fn validate_rejects_empty_child_version() {
4138        let s = SupervisorSpec {
4139            children: vec![child("w", "", RestartPolicy::Permanent)],
4140            ..SupervisorSpec::default()
4141        };
4142        assert!(matches!(
4143            s.validate().unwrap_err(),
4144            SupervisorError::EmptyChildVersion { .. }
4145        ));
4146    }
4147
4148    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
4149
4150    #[test]
4151    fn validate_rejects_invalid_child_versao_requirement() {
4152        // The fail-before-pass-after pin: a non-empty but malformed
4153        // semver requirement (`"^bad-version"`) silently passed
4154        // `validate()` on every pre-gate codebase because the prior
4155        // shape only refused the empty string. The parse failure
4156        // surfaced far downstream at lacre-resolve time with a
4157        // `semver::Error` that didn't name which `:children` entry
4158        // carried the typo. The new gate moves the check to caixa-build
4159        // time at the source caixa.lisp — the third `:versao` typed
4160        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
4161        // structural parity.
4162        let s = SupervisorSpec {
4163            children: vec![
4164                child("worker", "^0.1", RestartPolicy::Permanent),
4165                child("cache", "^bad-version", RestartPolicy::Transient),
4166            ],
4167            ..SupervisorSpec::default()
4168        };
4169        let err = s.validate().unwrap_err();
4170        assert!(
4171            matches!(
4172                err,
4173                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4174                    if caixa == "cache" && versao == "^bad-version"
4175            ),
4176            "got {err:?}"
4177        );
4178    }
4179
4180    #[test]
4181    fn validate_rejects_child_versao_with_double_caret_typo() {
4182        // `"^^0.1"` is the canonical doubled-caret typo — looks
4183        // Cargo-shaped on first glance but fails the parser because
4184        // semver doesn't accept stacked operators. Pin this
4185        // adjacent-shape footgun explicitly so a future relaxation that
4186        // accepts "looks-canonical-but-isn't" forms surfaces here.
4187        let s = SupervisorSpec {
4188            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
4189            ..SupervisorSpec::default()
4190        };
4191        let err = s.validate().unwrap_err();
4192        assert!(
4193            matches!(
4194                err,
4195                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4196                    if caixa == "worker" && versao == "^^0.1"
4197            ),
4198            "got {err:?}"
4199        );
4200    }
4201
4202    #[test]
4203    fn validate_rejects_child_versao_with_v_prefixed_tag() {
4204        // `"v0.1"` is the canonical "git-tag-shape leaking into the
4205        // semver requirement slot" typo — an author copies the
4206        // publish-side git-tag string verbatim into `:versao`, but
4207        // Cargo's semver parser rejects the leading `v`. Same
4208        // adjacent-shape footgun pinned for `:membros :versao`
4209        // (9888b13).
4210        let s = SupervisorSpec {
4211            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
4212            ..SupervisorSpec::default()
4213        };
4214        let err = s.validate().unwrap_err();
4215        assert!(
4216            matches!(
4217                err,
4218                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4219                    if caixa == "worker" && versao == "v0.1"
4220            ),
4221            "got {err:?}"
4222        );
4223    }
4224
4225    #[test]
4226    fn validate_accepts_canonical_child_versao_forms() {
4227        // The Cargo-shaped requirement forms `:deps :versao` and
4228        // `:membros :versao` already accept via
4229        // `crate::parse_requirement` must pass the children gate
4230        // without re-validating at the resolver layer. Pin every leg so
4231        // a future tightening of the canonical set surfaces here as a
4232        // test failure.
4233        for form in [
4234            "^0.1",      // caret — minor-range pin (the most common shape)
4235            "~0.1.2",    // tilde — patch-range pin
4236            "0.1.0",     // exact — single-version pin
4237            "*",         // wildcard — any version (semver::VersionReq::STAR)
4238            ">=0.1, <2", // multi-range — comma-separated comparators
4239        ] {
4240            let s = SupervisorSpec {
4241                children: vec![child("worker", form, RestartPolicy::Permanent)],
4242                ..SupervisorSpec::default()
4243            };
4244            s.validate()
4245                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4246        }
4247    }
4248
4249    #[test]
4250    fn child_versao_empty_takes_precedence_over_invalid() {
4251        // Order pin: the existing `EmptyChildVersion` diagnostic (which
4252        // doesn't try to parse) fires before the new
4253        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
4254        // `:versao` keeps its narrower error message —
4255        // `parse_requirement` would also reject `""`, but the
4256        // empty-string arm is the more self-locating diagnostic for the
4257        // author. Same ordering discipline as
4258        // `membro_versao_empty_takes_precedence_over_invalid` in
4259        // aplicacao.rs.
4260        let s = SupervisorSpec {
4261            children: vec![child("worker", "", RestartPolicy::Permanent)],
4262            ..SupervisorSpec::default()
4263        };
4264        let err = s.validate().unwrap_err();
4265        assert!(
4266            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
4267            "got {err:?}"
4268        );
4269    }
4270
4271    #[test]
4272    fn child_versao_invalid_fires_before_duplicate_check() {
4273        // Order pin: a malformed requirement on a non-duplicate entry
4274        // surfaces *its own* diagnostic (which names the offending
4275        // `:versao` string), even when a later entry would otherwise
4276        // collapse onto an earlier name. The per-entry shape gate runs
4277        // inline before the duplicate-key insert — parallel to
4278        // `membro_versao_invalid_fires_before_duplicate_check` in
4279        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
4280        let s = SupervisorSpec {
4281            children: vec![
4282                child("worker", "^bad", RestartPolicy::Permanent),
4283                child("cache", "^0.1", RestartPolicy::Transient),
4284                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4285            ],
4286            ..SupervisorSpec::default()
4287        };
4288        let err = s.validate().unwrap_err();
4289        assert!(
4290            matches!(
4291                err,
4292                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
4293            ),
4294            "got {err:?}"
4295        );
4296    }
4297
4298    #[test]
4299    fn child_versao_invalid_diagnostic_carries_offending_versao() {
4300        // The diagnostic-shape pin: the error names the offending
4301        // `:versao` value verbatim so the author can grep their
4302        // caixa.lisp without re-running the build, and carries a
4303        // non-empty `reason` from `semver::VersionReq::parse` so the
4304        // parser's own wording flows through to the diagnostic.
4305        let s = SupervisorSpec {
4306            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
4307            ..SupervisorSpec::default()
4308        };
4309        let err = s.validate().unwrap_err();
4310        let SupervisorError::ChildVersaoInvalid {
4311            caixa,
4312            versao,
4313            reason,
4314        } = err
4315        else {
4316            panic!("expected ChildVersaoInvalid, got other variant");
4317        };
4318        assert_eq!(caixa, "worker");
4319        assert_eq!(versao, "not-a-req");
4320        assert!(
4321            !reason.is_empty(),
4322            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
4323        );
4324    }
4325
4326    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
4327
4328    #[test]
4329    fn validate_rejects_child_caixa_with_uppercase() {
4330        // The canonical "I copied the Servico's display name verbatim"
4331        // typo — child caixa names are lowercase per K8s DNS-1123 label
4332        // rule. The diagnostic names the offending name and suggests the
4333        // lower-cased fix in one edit, mirroring the
4334        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
4335        let s = SupervisorSpec {
4336            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
4337            ..SupervisorSpec::default()
4338        };
4339        let err = s.validate().unwrap_err();
4340        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4341            panic!("expected ChildCaixaInvalid, got other variant");
4342        };
4343        assert_eq!(caixa, "Worker");
4344        assert!(
4345            reason.contains("uppercase"),
4346            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
4347        );
4348        assert!(
4349            reason.contains("\"worker\""),
4350            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
4351        );
4352    }
4353
4354    #[test]
4355    fn validate_rejects_child_caixa_with_underscore() {
4356        // The canonical "I'm thinking of a Python module / Postgres
4357        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
4358        // label schema. K8s rejects `metadata.name: my_worker` at
4359        // admission time with an opaque `field is invalid` (no source-
4360        // citing diagnostic). The gate moves it to caixa-build time.
4361        let s = SupervisorSpec {
4362            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
4363            ..SupervisorSpec::default()
4364        };
4365        let err = s.validate().unwrap_err();
4366        assert!(
4367            matches!(
4368                err,
4369                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4370                    if caixa == "my_worker" && reason.contains('_')
4371            ),
4372            "got {err:?}"
4373        );
4374    }
4375
4376    #[test]
4377    fn validate_rejects_child_caixa_with_dot() {
4378        // A `:children :caixa` entry is a single DNS-1123 label, not a
4379        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
4380        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
4381        // (3f9d7a0) on the peer name axis.
4382        let s = SupervisorSpec {
4383            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
4384            ..SupervisorSpec::default()
4385        };
4386        let err = s.validate().unwrap_err();
4387        assert!(
4388            matches!(
4389                err,
4390                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4391                    if caixa == "team.worker" && reason.contains('.')
4392            ),
4393            "got {err:?}"
4394        );
4395    }
4396
4397    #[test]
4398    fn validate_rejects_child_caixa_with_leading_hyphen() {
4399        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
4400        // with an alphanumeric. The K8s apiserver rejects `-worker`
4401        // outright; the renderer would emit a `metadata.name: "-worker"`
4402        // that fails admission far from the source caixa.lisp.
4403        let s = SupervisorSpec {
4404            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
4405            ..SupervisorSpec::default()
4406        };
4407        let err = s.validate().unwrap_err();
4408        assert!(
4409            matches!(
4410                err,
4411                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4412                    if caixa == "-worker" && reason.contains("start and end")
4413            ),
4414            "got {err:?}"
4415        );
4416    }
4417
4418    #[test]
4419    fn validate_rejects_child_caixa_with_trailing_hyphen() {
4420        // The symmetric arm of the boundary rule. Pin separately so
4421        // both ends of the label are covered against a future relaxation
4422        // that only checks one boundary.
4423        let s = SupervisorSpec {
4424            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
4425            ..SupervisorSpec::default()
4426        };
4427        let err = s.validate().unwrap_err();
4428        assert!(
4429            matches!(
4430                err,
4431                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4432                    if caixa == "worker-"
4433            ),
4434            "got {err:?}"
4435        );
4436    }
4437
4438    #[test]
4439    fn validate_rejects_child_caixa_with_unicode() {
4440        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
4441        // (`xn--…`) by the author before it reaches K8s. The byte-by-
4442        // byte ASCII validity check rejects multi-byte UTF-8 sequences
4443        // by the first byte that fails the `[a-z0-9-]` predicate.
4444        let s = SupervisorSpec {
4445            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
4446            ..SupervisorSpec::default()
4447        };
4448        let err = s.validate().unwrap_err();
4449        assert!(
4450            matches!(
4451                err,
4452                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4453                    if caixa == "café"
4454            ),
4455            "got {err:?}"
4456        );
4457    }
4458
4459    #[test]
4460    fn validate_rejects_child_caixa_with_whitespace() {
4461        // Whitespace is the canonical "I pasted from a sketch / doc"
4462        // footgun. The apiserver rejects every `metadata.name` value
4463        // carrying whitespace; pin the gate fires at the right boundary.
4464        let s = SupervisorSpec {
4465            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
4466            ..SupervisorSpec::default()
4467        };
4468        let err = s.validate().unwrap_err();
4469        assert!(
4470            matches!(
4471                err,
4472                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4473                    if caixa == "my worker"
4474            ),
4475            "got {err:?}"
4476        );
4477    }
4478
4479    #[test]
4480    fn validate_rejects_child_caixa_too_long() {
4481        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
4482        // 63 bytes; the K8s apiserver rejects every `metadata.name`
4483        // axis over the limit at admission time. The diagnostic names
4484        // both the cap and the actual length so the author can shorten
4485        // in one edit, mirroring `rejects_membro_caixa_too_long`
4486        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
4487        let too_long = "a".repeat(64);
4488        let s = SupervisorSpec {
4489            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
4490            ..SupervisorSpec::default()
4491        };
4492        let err = s.validate().unwrap_err();
4493        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4494            panic!("expected ChildCaixaInvalid, got other variant");
4495        };
4496        assert_eq!(caixa, too_long);
4497        assert!(
4498            reason.contains("63"),
4499            "diagnostic must name the 63-byte cap (got: {reason:?})"
4500        );
4501        assert!(
4502            reason.contains("64"),
4503            "diagnostic must name the actual length (got: {reason:?})"
4504        );
4505    }
4506
4507    #[test]
4508    fn child_caixa_max_length_validates() {
4509        // The 63-byte boundary control pin — exactly-at-the-cap is
4510        // accepted, mirroring `membro_caixa_max_length_validates`
4511        // (3f9d7a0) and `placement_cluster_max_length_validates`
4512        // (6cbb900). Pinned separately so a future off-by-one tightening
4513        // surfaces here.
4514        let max_label = "a".repeat(63);
4515        let s = SupervisorSpec {
4516            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
4517            ..SupervisorSpec::default()
4518        };
4519        s.validate().unwrap();
4520    }
4521
4522    #[test]
4523    fn validate_accepts_canonical_child_caixa_forms() {
4524        // The realistic shapes a supervised child's `:caixa` carries —
4525        // single-word `worker`, version-suffixed `cache-v2`, single-char
4526        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
4527        // `payment-retry`, all-digit `0`. Pin every leg so a future
4528        // tightening (e.g. requiring a leading lowercase letter) surfaces
4529        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
4530        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
4531        // (6cbb900).
4532        for form in [
4533            "worker",
4534            "cache-v2",
4535            "a",
4536            "db",
4537            "2-pool",
4538            "payment-retry",
4539            "0",
4540        ] {
4541            let s = SupervisorSpec {
4542                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
4543                ..SupervisorSpec::default()
4544            };
4545            s.validate()
4546                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4547        }
4548    }
4549
4550    #[test]
4551    fn child_caixa_empty_takes_precedence_over_invalid() {
4552        // Order pin: the existing `EmptyChildName` diagnostic (which
4553        // doesn't try to parse the DNS-1123 shape) fires before the new
4554        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
4555        // its narrower error message — `is_dns_1123_label` would reject
4556        // the empty string too (boundary check on the first byte), but
4557        // the empty-string arm is the more self-locating diagnostic for
4558        // the author. Same ordering discipline as
4559        // `membro_caixa_empty_takes_precedence_over_invalid` in
4560        // aplicacao.rs.
4561        let s = SupervisorSpec {
4562            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4563            ..SupervisorSpec::default()
4564        };
4565        let err = s.validate().unwrap_err();
4566        assert_eq!(err, SupervisorError::EmptyChildName);
4567    }
4568
4569    #[test]
4570    fn child_caixa_invalid_fires_before_versao_check() {
4571        // Order pin: the per-axis shape gate runs inline before the
4572        // per-entry versao check, so a malformed `:caixa` on an entry
4573        // whose `:versao` would also fail surfaces the more self-
4574        // locating name-axis diagnostic first. Parallel to
4575        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
4576        // and `placement_cluster_invalid_fires_before_duplicate_check`
4577        // (6cbb900).
4578        let s = SupervisorSpec {
4579            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
4580            ..SupervisorSpec::default()
4581        };
4582        let err = s.validate().unwrap_err();
4583        assert!(
4584            matches!(
4585                err,
4586                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
4587            ),
4588            "got {err:?}"
4589        );
4590    }
4591
4592    #[test]
4593    fn child_caixa_invalid_fires_before_duplicate_check() {
4594        // Order pin: a malformed name on a non-duplicate entry surfaces
4595        // its own diagnostic, even when a later entry would otherwise
4596        // collapse onto an earlier name. The per-entry shape gate runs
4597        // inline before the duplicate-key HashSet insert, mirroring
4598        // `placement_cluster_invalid_fires_before_duplicate_check`
4599        // (6cbb900).
4600        let s = SupervisorSpec {
4601            children: vec![
4602                child("Worker", "^0.1", RestartPolicy::Permanent),
4603                child("cache", "^0.1", RestartPolicy::Transient),
4604                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4605            ],
4606            ..SupervisorSpec::default()
4607        };
4608        let err = s.validate().unwrap_err();
4609        assert!(
4610            matches!(
4611                err,
4612                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
4613            ),
4614            "got {err:?}"
4615        );
4616    }
4617
4618    #[test]
4619    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
4620        // The diagnostic-shape pin: the error names the offending
4621        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
4622        // the author can grep their caixa.lisp without re-running the
4623        // build. Mirrors the diagnostic-shape sweep on every prior
4624        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
4625        let s = SupervisorSpec {
4626            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
4627            ..SupervisorSpec::default()
4628        };
4629        let err = s.validate().unwrap_err();
4630        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4631            panic!("expected ChildCaixaInvalid, got other variant");
4632        };
4633        assert_eq!(caixa, "My_Worker");
4634        assert!(
4635            !reason.is_empty(),
4636            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
4637        );
4638    }
4639
4640    // ── value-shape: zero restart_window + duplicate child names ──────────
4641
4642    #[test]
4643    fn validate_accepts_none_restart_window() {
4644        // Omitted `:restart-window` is the "never reset" sentinel —
4645        // valid by design. Mirrors :limits axes where None = unbounded.
4646        let s = SupervisorSpec {
4647            restart_window: None,
4648            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4649            ..SupervisorSpec::default()
4650        };
4651        s.validate().unwrap();
4652    }
4653
4654    #[test]
4655    fn validate_rejects_zero_restart_window() {
4656        // Same "0 means the opposite of what you think" footgun closed
4657        // for :politicas :timeout (Envoy treats 0s as infinite) and
4658        // :limits :wall-clock (wasmtime traps before the call starts).
4659        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
4660        let s = SupervisorSpec {
4661            restart_window: Some(Duration::ZERO),
4662            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4663            ..SupervisorSpec::default()
4664        };
4665        assert_eq!(
4666            s.validate().unwrap_err(),
4667            SupervisorError::RestartWindowZero
4668        );
4669    }
4670
4671    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
4672    //
4673    // The fourth (and last) typed-`Duration` axis in caixa-core to get
4674    // the integer-millisecond canonical-form gate — peer with
4675    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
4676    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
4677    // path is already gated at the shared codec layer (see
4678    // `restart_window_serde_rejects_fractional_seconds`); this arm
4679    // closes the programmatic-struct-literal path the codec gate can't
4680    // see.
4681
4682    #[test]
4683    fn validate_rejects_sub_millisecond_restart_window() {
4684        // The fail-before-pass-after pin: a programmatic
4685        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
4686        // `validate` on every pre-gate codebase, then truncated to
4687        // `as_millis() == 1` on first serialize — the shared codec
4688        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
4689        // 1_000_000 ns, the typed `restart_window` no longer matches
4690        // its rendered form.
4691        let s = SupervisorSpec {
4692            restart_window: Some(Duration::from_micros(1500)),
4693            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4694            ..SupervisorSpec::default()
4695        };
4696        match s.validate().unwrap_err() {
4697            SupervisorError::RestartWindowNotCanonical { window } => {
4698                assert_eq!(window, Duration::from_micros(1500));
4699            }
4700            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4701        }
4702    }
4703
4704    #[test]
4705    fn validate_rejects_one_nanosecond_restart_window() {
4706        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
4707        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
4708        // so the shared codec emits the literal `"0s"` — the next
4709        // serde round-trip would parse back to `Duration::ZERO`, which
4710        // the `RestartWindowZero` arm then rejects on re-validate. The
4711        // canonical-form gate at this layer surfaces a self-locating
4712        // diagnostic naming the offending Duration verbatim rather
4713        // than a downstream `RestartWindowZero` whose remediation
4714        // points at omitting the slot.
4715        let s = SupervisorSpec {
4716            restart_window: Some(Duration::from_nanos(1)),
4717            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4718            ..SupervisorSpec::default()
4719        };
4720        match s.validate().unwrap_err() {
4721            SupervisorError::RestartWindowNotCanonical { window } => {
4722                assert_eq!(window, Duration::from_nanos(1));
4723            }
4724            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4725        }
4726    }
4727
4728    #[test]
4729    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
4730        // The 1-ns-past-1ms boundary case: a `Duration` carrying
4731        // 1_000_001 ns is structurally past the integer-ms granularity
4732        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
4733        // trip would truncate to `1ms` and the consumer would observe
4734        // a 1-ns drift on every emit. Same boundary the peer
4735        // `validate_rejects_nanosecond_past_canonical_boundary` test
4736        // in limits.rs pins for the `:limits :wall-clock` axis.
4737        let w = Duration::from_nanos(1_000_001);
4738        let s = SupervisorSpec {
4739            restart_window: Some(w),
4740            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4741            ..SupervisorSpec::default()
4742        };
4743        assert_eq!(
4744            s.validate().unwrap_err(),
4745            SupervisorError::RestartWindowNotCanonical { window: w }
4746        );
4747    }
4748
4749    #[test]
4750    fn validate_accepts_integer_millisecond_restart_window_values() {
4751        // The positive-control sweep: every `Duration` the shared
4752        // codec can round-trip losslessly — the canonical
4753        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
4754        // pair emits and accepts — passes `validate` without
4755        // surfacing the new canonical-form arm. Mirrors
4756        // `validate_accepts_integer_millisecond_wall_clock_values` on
4757        // the sibling `:limits :wall-clock` axis.
4758        for w in [
4759            Duration::from_millis(1),
4760            Duration::from_millis(500),
4761            Duration::from_millis(1500),
4762            Duration::from_secs(1),
4763            Duration::from_secs(30),
4764            Duration::from_secs(60),
4765            Duration::from_secs(120),
4766            Duration::from_secs(3600),
4767        ] {
4768            let s = SupervisorSpec {
4769                restart_window: Some(w),
4770                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4771                ..SupervisorSpec::default()
4772            };
4773            s.validate()
4774                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
4775        }
4776    }
4777
4778    #[test]
4779    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
4780        // Cross-arm ordering pin: `Duration::ZERO` has
4781        // `subsec_nanos() == 0` and would otherwise pass the
4782        // canonical-form arm — the zero-floor arm must fire first so
4783        // the more self-locating `RestartWindowZero` diagnostic (with
4784        // its omit-axis remediation directly named) leads. Same
4785        // posture every peer zero-then-shape gate uses
4786        // (`WallClockZero` → `WallClockNotCanonical`,
4787        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
4788        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
4789        let s = SupervisorSpec {
4790            restart_window: Some(Duration::ZERO),
4791            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4792            ..SupervisorSpec::default()
4793        };
4794        assert_eq!(
4795            s.validate().unwrap_err(),
4796            SupervisorError::RestartWindowZero
4797        );
4798    }
4799
4800    #[test]
4801    fn restart_window_canonical_diagnostic_carries_offending_duration() {
4802        // Diagnostic-shape pin: the canonical-form arm names the
4803        // offending `Duration` verbatim so the author's grep lands on
4804        // the field's value, not a generic "duration not canonical"
4805        // message. Same shape every other typed-canonical-form arm
4806        // on this surface carries (`WallClockNotCanonical` carries
4807        // the offending `Duration` verbatim,
4808        // `PolicyTimeoutNotCanonical` carries the offending
4809        // `Duration` verbatim).
4810        let w = Duration::from_micros(500);
4811        let s = SupervisorSpec {
4812            restart_window: Some(w),
4813            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4814            ..SupervisorSpec::default()
4815        };
4816        let err = s.validate().unwrap_err();
4817        let msg = err.to_string();
4818        assert!(
4819            msg.contains("500"),
4820            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
4821        );
4822        assert!(
4823            msg.contains("sub-millisecond"),
4824            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
4825        );
4826    }
4827
4828    #[test]
4829    fn restart_window_validated_value_round_trips_through_codec() {
4830        // The structural property the canonical-ms gate enforces:
4831        // every `SupervisorSpec::restart_window` past
4832        // `SupervisorSpec::validate` round-trips losslessly through
4833        // the shared duration codec (serialize → string →
4834        // deserialize → equal value). Pin this end-to-end so a future
4835        // change to either side (the validate gate's accepted
4836        // granularity, the codec's parse/render unit set) that breaks
4837        // the alignment surfaces here. Peer of
4838        // `wall_clock_validated_value_round_trips_through_codec` on
4839        // the sibling `:limits :wall-clock` axis.
4840        for w in [
4841            Duration::from_millis(1),
4842            Duration::from_millis(1500),
4843            Duration::from_secs(30),
4844            Duration::from_secs(3600),
4845        ] {
4846            let s = SupervisorSpec {
4847                restart_window: Some(w),
4848                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4849                ..SupervisorSpec::default()
4850            };
4851            s.validate().unwrap();
4852            let json = serde_json::to_string(&s).unwrap();
4853            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4854            assert_eq!(back.restart_window, Some(w));
4855        }
4856    }
4857
4858    // ── value-shape: upper cap on :restart-window ─────────────────────────
4859    //
4860    // The fourth (and last) typed-`Duration` axis in caixa-core to get
4861    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
4862    // `:politicas :timeout` (2e8ee7e), and `:politicas
4863    // :circuit-breaker :window` (379a814). Brackets the typed
4864    // `:restart-window` axis structurally: every validated value lies
4865    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
4866    // granularity, closing the
4867    // rolling-window-degenerates-to-lifetime-counter footgun the prior
4868    // zero-floor-and-canonical-form-only checks left open.
4869
4870    #[test]
4871    fn validate_rejects_restart_window_above_cap() {
4872        // The fail-before-pass-after pin: 3601s = 1h + 1s is
4873        // structurally one canonical-tick past the
4874        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
4875        // integer-millisecond magnitude the canonical-form arm above
4876        // accepts cleanly, that the shared duration codec round-trips
4877        // losslessly as `"3601s"`, and that silently passed validate on
4878        // every pre-gate codebase because the typed slot's only checks
4879        // were the zero-floor and canonical-form arms. The runtime
4880        // substrate consuming the value (Erlang/OTP's MaxIntensity/
4881        // Period reconciler, the future wasm-operator's per-supervisor
4882        // restart-intensity counter) reaches for a `Duration` so long
4883        // no realistic restart-recovery pattern resets the counter,
4884        // far from the source caixa.lisp.
4885        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
4886        let s = SupervisorSpec {
4887            restart_window: Some(w),
4888            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4889            ..SupervisorSpec::default()
4890        };
4891        assert_eq!(
4892            s.validate().unwrap_err(),
4893            SupervisorError::RestartWindowExceedsCap { window: w }
4894        );
4895    }
4896
4897    #[test]
4898    fn validate_rejects_restart_window_one_millisecond_above_cap() {
4899        // Boundary case: exactly 1ms past the cap (the granularity the
4900        // canonical-form gate enforces). Catches a future "strictly
4901        // less than" half-measure and pins the diagnostic to name the
4902        // offending `Duration` verbatim. Peer of
4903        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
4904        // `rejects_policy_timeout_one_millisecond_above_cap` /
4905        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
4906        // on the sibling typed-`Duration` axes' top edges.
4907        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
4908        let s = SupervisorSpec {
4909            restart_window: Some(w),
4910            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4911            ..SupervisorSpec::default()
4912        };
4913        assert_eq!(
4914            s.validate().unwrap_err(),
4915            SupervisorError::RestartWindowExceedsCap { window: w }
4916        );
4917    }
4918
4919    #[test]
4920    fn validate_rejects_restart_window_far_above_cap() {
4921        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
4922        // `(:restart-window "7d")`, or any "I want a lifetime counter
4923        // but wrote a `<integer>h` magnitude anyway" typo — values the
4924        // canonical-form arm accepts as integer-millisecond magnitudes,
4925        // the codec round-trips losslessly through serde, but the
4926        // operator's `MaxIntensity / Period` reconciler cannot honor
4927        // as a meaningful rolling window. Until this gate landed
4928        // validate accepted them. Pin the common above-cap values (24h,
4929        // 7d, ~11.5d) so a future relaxation that drops the upper bound
4930        // surfaces here.
4931        for w in [
4932            Duration::from_secs(86_400),    // 24h
4933            Duration::from_secs(604_800),   // 7d
4934            Duration::from_secs(1_000_000), // ~11.5 days
4935        ] {
4936            let s = SupervisorSpec {
4937                restart_window: Some(w),
4938                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4939                ..SupervisorSpec::default()
4940            };
4941            assert_eq!(
4942                s.validate().unwrap_err(),
4943                SupervisorError::RestartWindowExceedsCap { window: w }
4944            );
4945        }
4946    }
4947
4948    #[test]
4949    fn validate_accepts_restart_window_at_cap() {
4950        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
4951        // (1h) — must validate. The cap is inclusive on the top edge,
4952        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
4953        // [`crate::POLICY_TIMEOUT_MAX`] /
4954        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
4955        // capped axes. Pin the boundary explicitly so a future
4956        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
4957        // instead of `>`) surfaces here as a test failure rather than a
4958        // silent contract narrowing.
4959        let s = SupervisorSpec {
4960            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
4961            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4962            ..SupervisorSpec::default()
4963        };
4964        s.validate()
4965            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
4966    }
4967
4968    #[test]
4969    fn validate_accepts_restart_window_typical_values() {
4970        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
4971        // per-supervisor production-playbook band positive-control
4972        // sweep — every value Learn You Some Erlang's `{intensity, 5,
4973        // 60}` worker-supervisor `Period = 60s` default, Elixir's
4974        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
4975        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
4976        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
4977        // default recommend (5s..=300s) must pass, plus a sweep
4978        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
4979        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
4980        // on the sibling `:limits :wall-clock` axis.
4981        for w in [
4982            Duration::from_millis(1),
4983            Duration::from_millis(500),
4984            Duration::from_secs(1),
4985            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
4986            Duration::from_secs(10), // Riak Core lower
4987            Duration::from_secs(30),
4988            Duration::from_secs(60),  // Learn You Some Erlang default
4989            Duration::from_secs(120), // OTP supervisor MaxT typical
4990            Duration::from_secs(300), // Riak Core upper
4991            Duration::from_secs(900), // 15m
4992            Duration::from_secs(1800),
4993            Duration::from_secs(3600), // exactly 1h, the cap
4994        ] {
4995            let s = SupervisorSpec {
4996                restart_window: Some(w),
4997                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4998                ..SupervisorSpec::default()
4999            };
5000            s.validate()
5001                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
5002        }
5003    }
5004
5005    #[test]
5006    fn restart_window_zero_takes_precedence_over_cap() {
5007        // The cross-arm ordering pin: `Duration::ZERO` is structurally
5008        // outside both `>= 1ms` (zero-floor) and `<=
5009        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
5010        // diagnostic is the more self-locating one (it directly names
5011        // the omit-axis remediation), so the validate gate must fire
5012        // on zero first. Same shape every other zero-then-cap ordering
5013        // on this surface uses (`WallClockZero` then
5014        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
5015        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
5016        // `PolicyBreakerWindowExceedsCap`).
5017        let s = SupervisorSpec {
5018            restart_window: Some(Duration::ZERO),
5019            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5020            ..SupervisorSpec::default()
5021        };
5022        assert_eq!(
5023            s.validate().unwrap_err(),
5024            SupervisorError::RestartWindowZero,
5025            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
5026        );
5027    }
5028
5029    #[test]
5030    fn restart_window_canonical_takes_precedence_over_cap() {
5031        // The cross-arm ordering pin: a `Duration` that is *both*
5032        // sub-millisecond (non-canonical-form) and structurally above
5033        // the cap surfaces the canonical-form diagnostic first,
5034        // because the round-trip-shape break is the more fundamental
5035        // issue (the value can't even round-trip through the codec,
5036        // so the cap diagnostic naming `1ms..=1h` would be misleading
5037        // — there's no integer-ms form of the offending value). Pin
5038        // the order so a future refactor that reorders the arms
5039        // surfaces here as a test failure rather than a silent
5040        // diagnostic regression. Peer of
5041        // `wall_clock_canonical_takes_precedence_over_cap` /
5042        // `policy_timeout_canonical_takes_precedence_over_cap`.
5043        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
5044        let s = SupervisorSpec {
5045            restart_window: Some(w),
5046            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5047            ..SupervisorSpec::default()
5048        };
5049        assert_eq!(
5050            s.validate().unwrap_err(),
5051            SupervisorError::RestartWindowNotCanonical { window: w },
5052            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
5053        );
5054    }
5055
5056    #[test]
5057    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
5058        // The cross-arm ordering pin between the `:max-restarts` cap
5059        // and the sibling `:restart-window` cap. A supervisor carrying
5060        // both an over-cap `max_restarts` AND an over-cap window must
5061        // surface the `MaxRestartsExceedsCap` diagnostic first — the
5062        // cap arm is wired immediately after the zero-restart arm and
5063        // strictly before every window-axis arm (zero / canonical /
5064        // cap), so the offending value the diagnostic names matches
5065        // the order the author would discover the gates by reading
5066        // top-to-bottom through `SupervisorSpec::validate`. Pin the
5067        // order so a future refactor that reorders the arms surfaces
5068        // here as a test failure rather than a silent diagnostic
5069        // regression. Peer of
5070        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
5071        // on the sibling zero / canonical window arms.
5072        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5073        let s = SupervisorSpec {
5074            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5075            restart_window: Some(w),
5076            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5077            ..SupervisorSpec::default()
5078        };
5079        assert_eq!(
5080            s.validate().unwrap_err(),
5081            SupervisorError::MaxRestartsExceedsCap {
5082                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5083            },
5084            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5085        );
5086    }
5087
5088    #[test]
5089    fn restart_window_cap_diagnostic_carries_offending_value() {
5090        // The diagnostic-shape pin: the offending `Duration` is
5091        // carried verbatim into the
5092        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
5093        // surfaced error message names the value the author wrote,
5094        // not just the cap. Same self-locating diagnostic shape every
5095        // other typed-cap arm on this surface carries
5096        // (`WallClockExceedsCap` carries the offending `Duration`
5097        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
5098        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
5099        // the offending `Duration` verbatim).
5100        let w = Duration::from_secs(7200); // 2h
5101        let s = SupervisorSpec {
5102            restart_window: Some(w),
5103            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5104            ..SupervisorSpec::default()
5105        };
5106        let err = s.validate().unwrap_err();
5107        assert!(
5108            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
5109            "got {err:?}"
5110        );
5111        let msg = err.to_string();
5112        assert!(
5113            msg.contains("7200"),
5114            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
5115        );
5116    }
5117
5118    #[test]
5119    fn supervisor_restart_window_cap_pins_canonical_value() {
5120        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
5121        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
5122        // shared duration codec emits as a clean canonical string
5123        // (`"<n>h"`). Pinning the literal value here surfaces a future
5124        // drift (a relaxation to 24h, a tightening to 5m) as a
5125        // deliberate test edit, not a silent contract narrowing.
5126        //
5127        // The four typed-`Duration` caps on the validation surface
5128        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
5129        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
5130        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
5131        // single uniform top edge at the codec's largest emitted unit
5132        // — a structural-property invariant the equality assertions
5133        // here enshrine, so a future drift on any of the four
5134        // surfaces as a deliberate test edit. Same shape every other
5135        // typed-cap value pin uses
5136        // (`wall_clock_cap_pins_canonical_value`,
5137        // `policy_timeout_cap_pins_canonical_value`,
5138        // `circuit_breaker_window_cap_pins_canonical_value`).
5139        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
5140        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
5141        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
5142        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
5143        assert_eq!(
5144            SUPERVISOR_RESTART_WINDOW_MAX,
5145            crate::POLICY_BREAKER_WINDOW_MAX
5146        );
5147    }
5148
5149    #[test]
5150    fn restart_window_cap_value_round_trips_through_codec() {
5151        // The codec round-trip property the cap arm preserves: the
5152        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
5153        // through the shared duration codec — every value at the cap
5154        // serializes to the canonical `"1h"` form and parses back
5155        // identically. Pin the round-trip so a future change to the
5156        // codec's unit set or to the cap's magnitude that breaks the
5157        // round-trip property surfaces here. Peer of
5158        // `wall_clock_cap_value_round_trips_through_codec` on the
5159        // sibling `:limits :wall-clock` axis.
5160        let s = SupervisorSpec {
5161            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5162            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5163            ..SupervisorSpec::default()
5164        };
5165        s.validate().unwrap();
5166        let json = serde_json::to_string(&s).unwrap();
5167        assert!(
5168            json.contains("\"1h\""),
5169            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
5170        );
5171        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5172        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
5173    }
5174
5175    #[test]
5176    fn validate_rejects_duplicate_child_caixa() {
5177        // Two children with the same :caixa render to two ComputeUnits
5178        // with the same name in the cluster's HelmRelease values —
5179        // one silently overwrites the other. Erlang/OTP's child_spec.id
5180        // is required-unique per supervisor; same set-not-multiset
5181        // discipline applied here as for :membros / :placement
5182        // :clusters / :entrada :paths.
5183        let s = SupervisorSpec {
5184            children: vec![
5185                child("worker", "^0.1", RestartPolicy::Permanent),
5186                child("cache", "^0.1", RestartPolicy::Transient),
5187                child("worker", "^0.2", RestartPolicy::Permanent),
5188            ],
5189            ..SupervisorSpec::default()
5190        };
5191        let err = s.validate().unwrap_err();
5192        assert!(
5193            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
5194            "got {err:?}"
5195        );
5196    }
5197
5198    #[test]
5199    fn validate_duplicate_child_diagnostic_names_first_collision() {
5200        // Iteration walks the :children list in declaration order —
5201        // the diagnostic names the first repeat, deterministically,
5202        // even when multiple names duplicate.
5203        let s = SupervisorSpec {
5204            children: vec![
5205                child("a", "^0.1", RestartPolicy::Permanent),
5206                child("b", "^0.1", RestartPolicy::Permanent),
5207                child("a", "^0.1", RestartPolicy::Permanent),
5208                child("b", "^0.1", RestartPolicy::Permanent),
5209            ],
5210            ..SupervisorSpec::default()
5211        };
5212        let err = s.validate().unwrap_err();
5213        assert!(
5214            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
5215            "got {err:?}"
5216        );
5217    }
5218
5219    // ── self-supervision cross-slot gate ──────────────────────────
5220
5221    #[test]
5222    fn validate_no_self_supervision_rejects_self_referential_child() {
5223        // A supervisor whose `:children` lists its own `:nome` is a
5224        // one-node reconciliation cycle — rejected, naming the parent.
5225        let children = vec![
5226            child("worker", "^0.1", RestartPolicy::Permanent),
5227            child("orquestra", "^0.1", RestartPolicy::Permanent),
5228        ];
5229        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
5230        assert!(
5231            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
5232            "got {err:?}"
5233        );
5234    }
5235
5236    #[test]
5237    fn validate_no_self_supervision_accepts_distinct_children() {
5238        // Positive control: distinct child names (including a child that
5239        // is itself a supervisor — nested trees are valid OTP) pass.
5240        let children = vec![
5241            child("worker", "^0.1", RestartPolicy::Permanent),
5242            child("sub-tree", "^0.1", RestartPolicy::Permanent),
5243        ];
5244        validate_no_self_supervision(&children, "orquestra").unwrap();
5245    }
5246
5247    #[test]
5248    fn validate_no_self_supervision_empty_children_is_ok() {
5249        // SimpleOneForOne / no-static-children supervisors have nothing
5250        // to self-reference — the gate is vacuously satisfied.
5251        validate_no_self_supervision(&[], "orquestra").unwrap();
5252    }
5253
5254    #[test]
5255    fn validate_simple_one_for_one_skips_uniqueness_check() {
5256        // SimpleOneForOne supervisors carry no static children — the
5257        // duplicate-child loop never runs. A zero-window declaration
5258        // on a SimpleOneForOne supervisor still trips the window check
5259        // (window applies to dynamic children too).
5260        let s = SupervisorSpec {
5261            estrategia: RestartStrategy::SimpleOneForOne,
5262            restart_window: None,
5263            children: vec![],
5264            ..SupervisorSpec::default()
5265        };
5266        s.validate().unwrap();
5267        let s_zero = SupervisorSpec {
5268            estrategia: RestartStrategy::SimpleOneForOne,
5269            restart_window: Some(Duration::ZERO),
5270            children: vec![],
5271            ..SupervisorSpec::default()
5272        };
5273        assert_eq!(
5274            s_zero.validate().unwrap_err(),
5275            SupervisorError::RestartWindowZero
5276        );
5277    }
5278
5279    #[test]
5280    fn validate_zero_window_runs_after_max_restarts_check() {
5281        // Pin the order: max_restarts == 0 fires before
5282        // restart_window == 0s, so an author with both wrong sees the
5283        // counter-axis diagnostic first (matches the order in the
5284        // struct and in the doc comment).
5285        let s = SupervisorSpec {
5286            max_restarts: 0,
5287            restart_window: Some(Duration::ZERO),
5288            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5289            ..SupervisorSpec::default()
5290        };
5291        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5292    }
5293
5294    #[test]
5295    fn round_trip_all_strategies() {
5296        for &strat in RestartStrategy::ALL {
5297            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
5298            // shape partition through the [`gen_platform::IsVariant`]
5299            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
5300            // predicate rather than the raw
5301            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
5302            // open-coded pattern-match — same closed-set-typed-enum
5303            // arm-discriminator dispatch discipline the sibling
5304            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
5305            // (915a934) extended onto its two paired positive / negated
5306            // `matches!` filter sites, and the sibling
5307            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
5308            // predicate convergence (766ec63) extended onto the M3 mesh-
5309            // slot per-`:placement` distribution-strategy `matches!`
5310            // discriminator axis. See the sibling
5311            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
5312            // fixture and the peer `manifest::tests::
5313            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
5314            // fixture — all three sites (the last unlifted
5315            // `matches!`-based arm-discriminator axis on the OTP-shape
5316            // supervisor sibling-restart-strategy closed-set typed enum,
5317            // acknowledged in 915a934's Prior-commits footnote as the
5318            // outstanding follow-up) now consult one typed dispatch on
5319            // the substrate primitive.
5320            let s = SupervisorSpec {
5321                estrategia: strat,
5322                children: if strat.is_simple_one_for_one() {
5323                    vec![]
5324                } else {
5325                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
5326                },
5327                ..SupervisorSpec::default()
5328            };
5329            let json = serde_json::to_string(&s).unwrap();
5330            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5331            assert_eq!(s, back);
5332        }
5333    }
5334
5335    #[test]
5336    fn round_trip_all_restart_policies() {
5337        for policy in [
5338            RestartPolicy::Permanent,
5339            RestartPolicy::Temporary,
5340            RestartPolicy::Transient,
5341        ] {
5342            let c = child("w", "^0.1", policy);
5343            let json = serde_json::to_string(&c).unwrap();
5344            let back: ChildSpec = serde_json::from_str(&json).unwrap();
5345            assert_eq!(c, back);
5346        }
5347    }
5348
5349    #[test]
5350    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
5351        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
5352        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
5353        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
5354        // is the only variant that satisfies `.is_simple_one_for_one()`;
5355        // every static-children-bearing arm (`OneForOne` / `OneForAll`
5356        // / `RestForOne`) returns `false`. This pin makes the partition
5357        // invariant load-bearing at caixa-core test time so a future
5358        // derive regression (a hole that returns `false` for
5359        // `SimpleOneForOne` too, or a byte-collision that flips a second
5360        // variant to `true`) trips here rather than laundering the arm
5361        // at the three test-fixture builder sites (a hole flips the
5362        // `SimpleOneForOne` fixture to carry a non-empty children list
5363        // and the subsequent `SupervisorSpec::validate` would refuse the
5364        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
5365        // a collision flips a peer strategy's fixture to carry an empty
5366        // children list and the subsequent `validate` would refuse with
5367        // [`SupervisorError::NoChildren`] — either way, the pin fires
5368        // here, at the derive site, rather than at the fixture-refusal
5369        // site far away). Peer of the sibling
5370        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
5371        // (915a934) pin on the M2 OTP-appup axis and the sibling
5372        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
5373        // pin on the M0 `:kind` axis.
5374        let cases: &[(RestartStrategy, bool)] = &[
5375            (RestartStrategy::OneForOne, false),
5376            (RestartStrategy::OneForAll, false),
5377            (RestartStrategy::RestForOne, false),
5378            (RestartStrategy::SimpleOneForOne, true),
5379        ];
5380        for (variant, expected) in cases {
5381            assert_eq!(
5382                variant.is_simple_one_for_one(),
5383                *expected,
5384                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
5385                 return {expected} (partition invariant on the \
5386                 IsVariant-derived arm-discriminator predicate — every \
5387                 test-fixture site that partitions the `:children` slot \
5388                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
5389                 off this typed dispatch, so a derive regression must \
5390                 surface here rather than at the fixture-refusal site)"
5391            );
5392        }
5393    }
5394
5395    #[test]
5396    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
5397        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
5398        // fixture-shape partition against the pre-lift
5399        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
5400        // pattern-match every test-fixture builder site previously
5401        // coupled to inline. Asserts the two projections agree byte-for-
5402        // byte on every arm of the enum, so a future derive regression
5403        // that flipped either predicate's arm-set would surface here at
5404        // caixa-core test time rather than at the three fixture-builder
5405        // sites (`supervisor::tests::round_trip_all_strategies`,
5406        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
5407        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
5408        // far from the derive site. Same peer-shape byte-identity pin
5409        // every sibling `IsVariant`-derive-routed convergence carries on
5410        // the substrate's closed-set typed-enum surface (peer of
5411        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
5412        // on the M2 OTP-appup axis).
5413        for &strat in RestartStrategy::ALL {
5414            let via_predicate = strat.is_simple_one_for_one();
5415            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
5416            assert_eq!(
5417                via_predicate, via_matches,
5418                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
5419                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
5420                 the pre-lift open-coded pattern and the \
5421                 IsVariant-derived predicate are the same axis, \
5422                 one typed dispatch"
5423            );
5424        }
5425    }
5426
5427    #[test]
5428    fn duration_codec_round_trip_canonical_units() {
5429        // Note the canonical-form rule: durations serialize to the
5430        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
5431        // "60s" — but the round-trip preserves the underlying Duration.
5432        let cases = [
5433            ("30s", Duration::from_secs(30)),
5434            ("5m", Duration::from_secs(300)),
5435            ("1h", Duration::from_secs(3600)),
5436            ("500ms", Duration::from_millis(500)),
5437        ];
5438        for (lit, dur) in cases {
5439            let s = SupervisorSpec {
5440                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5441                restart_window: Some(dur),
5442                ..SupervisorSpec::default()
5443            };
5444            let json = serde_json::to_string(&s).unwrap();
5445            assert!(
5446                json.contains(&format!("\"{lit}\"")),
5447                "expected \"{lit}\" in {json}"
5448            );
5449            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5450            assert_eq!(back.restart_window, Some(dur));
5451        }
5452    }
5453
5454    #[test]
5455    fn duration_canonicalizes_to_largest_unit() {
5456        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
5457        // typed Duration still equals 60s on the way back.
5458        let s = SupervisorSpec {
5459            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5460            restart_window: Some(Duration::from_secs(60)),
5461            ..SupervisorSpec::default()
5462        };
5463        let json = serde_json::to_string(&s).unwrap();
5464        assert!(json.contains("\"1m\""), "{json}");
5465        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5466        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
5467    }
5468
5469    #[test]
5470    fn three_child_one_for_one_validates() {
5471        let s = SupervisorSpec {
5472            estrategia: RestartStrategy::OneForOne,
5473            max_restarts: 5,
5474            restart_window: Some(Duration::from_secs(60)),
5475            children: vec![
5476                child("worker", "^0.1", RestartPolicy::Permanent),
5477                child("cache", "^0.1", RestartPolicy::Transient),
5478                child("scratch", "^0.1", RestartPolicy::Temporary),
5479            ],
5480        };
5481        s.validate().unwrap();
5482    }
5483
5484    #[test]
5485    fn json_uses_pascal_case_for_strategy_and_policy() {
5486        // Variant names are PascalCase by default in serde, matching
5487        // tatara-lisp's enum convention (`:estrategia OneForOne`).
5488        let c = child("w", "^0.1", RestartPolicy::Permanent);
5489        let json = serde_json::to_string(&c).unwrap();
5490        assert!(json.contains("\"Permanent\""));
5491        assert!(!json.contains("\"permanent\""));
5492
5493        let s = SupervisorSpec {
5494            estrategia: RestartStrategy::OneForOne,
5495            children: vec![c],
5496            ..SupervisorSpec::default()
5497        };
5498        let json = serde_json::to_string(&s).unwrap();
5499        assert!(json.contains("\"estrategia\":\"OneForOne\""));
5500    }
5501
5502    // ── shared duration codec: integer-magnitude canonical-form gate ──
5503    //
5504    // The gate lifts the discipline `crate::limits::parse_duration`
5505    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
5506    // the shared codec backing the remaining three typed-duration
5507    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
5508    // `:politicas :circuit-breaker :window`. Every magnitude `render`
5509    // emits is a non-negative integer with no decimal point and no
5510    // leading sign, so the codec's accepted set must match for
5511    // serialize/deserialize to round-trip without canonical-form
5512    // drift.
5513
5514    #[test]
5515    fn parse_accepts_integer_canonical_units() {
5516        // Pin the happy-path: every canonical author shape `render`
5517        // ever emits parses to the same `Duration` value, so the
5518        // codec's accepted set is at least a superset of its emitted
5519        // set on the canonical-unit axis.
5520        for (lit, dur) in [
5521            ("30s", Duration::from_secs(30)),
5522            ("500ms", Duration::from_millis(500)),
5523            ("2m", Duration::from_secs(120)),
5524            ("1h", Duration::from_secs(3600)),
5525            ("0s", Duration::ZERO),
5526        ] {
5527            assert_eq!(
5528                duration_codec::parse(lit).unwrap(),
5529                dur,
5530                "parse({lit:?}) should be {dur:?}"
5531            );
5532        }
5533    }
5534
5535    #[test]
5536    fn parse_accepts_bare_integer_as_seconds() {
5537        // The `"s" | ""` arm: a bare integer with no unit is read as
5538        // seconds. Pin this so the unit-empty form keeps parsing (it
5539        // renders to `"<n>s"` on serialize — that's a unit-choice
5540        // drift the integer-magnitude gate does NOT close, matching
5541        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
5542        // the peer `:limits :memory` codec).
5543        assert_eq!(
5544            duration_codec::parse("30").unwrap(),
5545            Duration::from_secs(30)
5546        );
5547    }
5548
5549    #[test]
5550    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
5551        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
5552        // on first serialize — DRIFT. The integer-magnitude gate names
5553        // the offending `"1.5"` verbatim and points at the canonical
5554        // remediation `"1500ms"`.
5555        let err = duration_codec::parse("1.5s").unwrap_err();
5556        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
5557        assert!(
5558            err.contains("not a non-negative integer"),
5559            "missing canonical-form reason in {err:?}"
5560        );
5561        assert!(
5562            err.contains("\"1500ms\""),
5563            "missing canonical-form remediation in {err:?}"
5564        );
5565    }
5566
5567    #[test]
5568    fn parse_rejects_decimal_shaped_integer_seconds() {
5569        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
5570        // `1s` exactly, so the round-trip looks correct — but the
5571        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
5572        // decimal-shape-with-integer-value form so author intent is
5573        // never silently rewritten.
5574        let err = duration_codec::parse("1.0s").unwrap_err();
5575        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
5576        assert!(
5577            err.contains("not a non-negative integer"),
5578            "missing canonical-form reason in {err:?}"
5579        );
5580    }
5581
5582    #[test]
5583    fn parse_rejects_half_unit_minute() {
5584        // `"0.5m"` is the unit-fraction footgun — author writes a
5585        // human-readable half-minute, serde silently rewrites to
5586        // `"30s"` on next emit. The gate names the offending
5587        // magnitude `"0.5"` and points at the integer-in-smaller-unit
5588        // form.
5589        let err = duration_codec::parse("0.5m").unwrap_err();
5590        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
5591        assert!(
5592            err.contains("\"30s\""),
5593            "missing canonical-form remediation in {err:?}"
5594        );
5595    }
5596
5597    #[test]
5598    fn parse_rejects_leading_plus_sign() {
5599        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
5600        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
5601        // cleanly to 30s and round-tripped to `"30s"` on next emit
5602        // (DRIFT). The digit-only gate closes the leading-sign class
5603        // first; the diagnostic names `"+30"` verbatim.
5604        let err = duration_codec::parse("+30s").unwrap_err();
5605        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
5606        assert!(
5607            err.contains("not a non-negative integer"),
5608            "missing canonical-form reason in {err:?}"
5609        );
5610    }
5611
5612    #[test]
5613    fn parse_rejects_leading_minus_sign() {
5614        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
5615        // rejected with `"negative duration in \"-30s\""`. Under the
5616        // integer-magnitude gate the diagnostic is unified — `-30` is
5617        // non-digit-only, f64-numeric, and surfaces with the canonical-
5618        // form reason (no leading `+` / `-` sign) naming the offending
5619        // `"-30"` verbatim. Same diagnostic shape as every other
5620        // rejected non-integer magnitude.
5621        let err = duration_codec::parse("-30s").unwrap_err();
5622        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
5623        assert!(
5624            err.contains("not a non-negative integer"),
5625            "missing canonical-form reason in {err:?}"
5626        );
5627    }
5628
5629    #[test]
5630    fn parse_garbage_still_falls_through_to_bad_magnitude() {
5631        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
5632        // through to the narrower "bad duration magnitude" arm — the
5633        // canonical-form diagnostic is reserved for the parser-shape
5634        // footgun case, not the "not a number at all" case. Same
5635        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
5636        // the peer `:limits :memory` codec.
5637        let err = duration_codec::parse("--1s").unwrap_err();
5638        assert!(
5639            err.contains("bad duration magnitude"),
5640            "expected bad-magnitude wording in {err:?}"
5641        );
5642    }
5643
5644    #[test]
5645    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
5646        // The accepted set is now closed under `u64`-exact integer
5647        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
5648        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
5649        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
5650        // possible. Pin the integer-exact arms across the four unit
5651        // suffixes so a future refactor that reaches back for f64
5652        // (`from_secs_f64`, `mul_f64`) surfaces here.
5653        assert_eq!(
5654            duration_codec::parse("3600s").unwrap(),
5655            Duration::from_secs(3600)
5656        );
5657        assert_eq!(
5658            duration_codec::parse("60m").unwrap(),
5659            Duration::from_secs(3600)
5660        );
5661        assert_eq!(
5662            duration_codec::parse("1h").unwrap(),
5663            Duration::from_secs(3600)
5664        );
5665        assert_eq!(
5666            duration_codec::parse("999ms").unwrap(),
5667            Duration::from_millis(999)
5668        );
5669    }
5670
5671    #[test]
5672    fn restart_window_serde_rejects_fractional_seconds() {
5673        // The shared codec backs `SupervisorSpec::restart_window`
5674        // (`with = "duration_codec"`) — so the gate applies on serde
5675        // deserialize for the typed Supervisor slot. A
5676        // `{"restartWindow":"1.5s"}` payload that previously round-
5677        // tripped to a different canonical string on next serialize
5678        // is now refused at deserialize with the integer-magnitude
5679        // diagnostic.
5680        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5681            "restartWindow":"1.5s",
5682            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5683        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5684        let msg = err.to_string();
5685        assert!(
5686            msg.contains("not a non-negative integer"),
5687            "expected integer-magnitude diagnostic in {msg:?}"
5688        );
5689        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
5690    }
5691
5692    #[test]
5693    fn restart_window_serde_rejects_leading_plus() {
5694        // The `u64::from_str` leading-`+` permissiveness gap that
5695        // motivated the digit-only gate (the `f64`-side accepted
5696        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
5697        // is now closed on the shared codec — surfaces as a structured
5698        // diagnostic at the serde layer for every typed-duration slot.
5699        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5700            "restartWindow":"+30s",
5701            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5702        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5703        let msg = err.to_string();
5704        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
5705        assert!(
5706            msg.contains("not a non-negative integer"),
5707            "missing canonical-form reason in {msg:?}"
5708        );
5709    }
5710
5711    #[test]
5712    fn parse_rejects_leading_zero_magnitude() {
5713        // `"030s"` is digit-only, so the existing non-digit-only / sign
5714        // / fractional arm doesn't catch it — `u64::from_str("030")`
5715        // returns `Ok(30)`, so before this gate `"030s"` parsed to
5716        // `Duration::from_secs(30)` and round-tripped through `render`
5717        // to `"30s"` — a *different* canonical string on the next emit,
5718        // breaking the THEORY.md Part V render-determinism contract
5719        // exactly the way `"+30s"` did before the leading-`+` arm
5720        // landed. Peer with the `rate_limit_codec` leading-zero arm
5721        // (4f46830) on the same canonical-form-drift axis.
5722        let err = duration_codec::parse("030s").unwrap_err();
5723        assert!(
5724            err.contains("non-canonical leading zero"),
5725            "expected leading-zero diagnostic in {err:?}"
5726        );
5727        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5728        assert!(
5729            err.contains("\"30s\""),
5730            "missing canonical-form remediation in {err:?}"
5731        );
5732        assert!(
5733            err.contains("THEORY.md"),
5734            "missing render-determinism citation in {err:?}"
5735        );
5736    }
5737
5738    #[test]
5739    fn parse_rejects_multi_digit_zero_magnitude() {
5740        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
5741        // digit-only, parse losslessly to `Duration::ZERO`, but render
5742        // back to `"0s"` (the single-byte canonical form) on the next
5743        // emit. The leading-zero arm refuses the drift class at the
5744        // codec layer; the semantic-zero gate downstream
5745        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
5746        // the single-byte canonical form `"0s"` separately on the
5747        // typed-validate layer.
5748        let err = duration_codec::parse("00s").unwrap_err();
5749        assert!(
5750            err.contains("non-canonical leading zero"),
5751            "expected leading-zero diagnostic in {err:?}"
5752        );
5753        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
5754    }
5755
5756    #[test]
5757    fn parse_rejects_leading_zero_per_hour_window() {
5758        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
5759        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
5760        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
5761        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
5762        // `h` / bare-integer-as-seconds) inherits the same gate.
5763        let err = duration_codec::parse("01h").unwrap_err();
5764        assert!(
5765            err.contains("non-canonical leading zero"),
5766            "expected leading-zero diagnostic in {err:?}"
5767        );
5768        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
5769    }
5770
5771    #[test]
5772    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
5773        // The `parse_accepts_bare_integer_as_seconds` happy-path
5774        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
5775        // multi-byte starts-with-`0`, parses losslessly to
5776        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
5777        // bare-integer surface accepts permissive unit-empty
5778        // shorthand but still must reject leading-zero padding.
5779        let err = duration_codec::parse("030").unwrap_err();
5780        assert!(
5781            err.contains("non-canonical leading zero"),
5782            "expected leading-zero diagnostic in {err:?}"
5783        );
5784        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5785    }
5786
5787    #[test]
5788    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
5789        // The codec-layer / typed-validate-layer boundary: `"0s"` /
5790        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
5791        // each round-trips losslessly through `render`
5792        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
5793        // accepts them. The downstream semantic-zero gates
5794        // (`SupervisorError::ZeroRestartWindow`,
5795        // `AplicacaoError::PolicyTimeoutZero`,
5796        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
5797        // zero-magnitude authoring at the typed-validate layer above,
5798        // peer with the `rate_limit_codec` codec-layer / typed-
5799        // validate-layer partition for `"0/s"`.
5800        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
5801        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
5802        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
5803    }
5804
5805    #[test]
5806    fn parse_accepts_canonical_magnitude_with_leading_one() {
5807        // The complementary boundary: a future tightening cannot
5808        // drift into rejecting valid canonical magnitudes that
5809        // happen to start with `1` (or any digit `[1-9]`). Pin
5810        // every canonical-unit suffix so the leading-zero arm
5811        // remains strictly narrower than the digit-only arm.
5812        assert_eq!(
5813            duration_codec::parse("100ms").unwrap(),
5814            Duration::from_millis(100)
5815        );
5816        assert_eq!(
5817            duration_codec::parse("100s").unwrap(),
5818            Duration::from_secs(100)
5819        );
5820        assert_eq!(
5821            duration_codec::parse("10m").unwrap(),
5822            Duration::from_secs(600)
5823        );
5824        assert_eq!(
5825            duration_codec::parse("10h").unwrap(),
5826            Duration::from_secs(36_000)
5827        );
5828    }
5829
5830    #[test]
5831    fn restart_window_serde_rejects_leading_zero() {
5832        // The shared codec backs `SupervisorSpec::restart_window`
5833        // (`with = "duration_codec"`) — so the leading-zero arm
5834        // applies on serde deserialize for the typed Supervisor slot.
5835        // A `{"restartWindow":"030s"}` payload that previously round-
5836        // tripped to a different canonical string on next serialize
5837        // is now refused at deserialize with the leading-zero
5838        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
5839        // / `restart_window_serde_rejects_fractional_seconds` on the
5840        // same canonical-form-drift axis.
5841        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5842            "restartWindow":"030s",
5843            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5844        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5845        let msg = err.to_string();
5846        assert!(
5847            msg.contains("non-canonical leading zero"),
5848            "expected leading-zero diagnostic in {msg:?}"
5849        );
5850        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
5851    }
5852
5853    #[test]
5854    fn parse_rejects_leading_whitespace() {
5855        // `" 30s"` — the canonical paste-from-aligned-doc /
5856        // paste-from-YAML-quoted-plain-scalar footgun. Before this
5857        // gate the top-level `s.trim()` at parse entry silently ate
5858        // the leading space and parsed the value to
5859        // `Duration::from_secs(30)`, which then round-tripped through
5860        // `render` to `"30s"` (a *different* canonical string on the
5861        // next emit) — the exact canonical-form-drift class the
5862        // leading-`+` / leading-zero arms already close, extended
5863        // to the whitespace-byte class. Peer with the sibling
5864        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
5865        // the M3 `:politicas` axis.
5866        let err = duration_codec::parse(" 30s").unwrap_err();
5867        assert!(
5868            err.contains("contains whitespace byte"),
5869            "expected whitespace diagnostic in {err:?}"
5870        );
5871        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5872        assert!(
5873            err.contains("THEORY.md"),
5874            "missing render-determinism contract citation in {err:?}"
5875        );
5876    }
5877
5878    #[test]
5879    fn parse_rejects_trailing_whitespace() {
5880        // `"30s "` — the canonical shell-history / trailing-space
5881        // paste footgun. Before this gate the top-level `s.trim()`
5882        // silently ate the trailing space and parsed to
5883        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
5884        // next emit — same canonical-form drift as the leading-space
5885        // sibling, closed on the same whitespace-byte arm.
5886        let err = duration_codec::parse("30s ").unwrap_err();
5887        assert!(
5888            err.contains("contains whitespace byte"),
5889            "expected whitespace diagnostic in {err:?}"
5890        );
5891        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5892    }
5893
5894    #[test]
5895    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
5896        // `"30 s"` — the canonical typographically-spaced author
5897        // shape (the same idiom every prose reference to a duration
5898        // renders as, mistakenly retained when the value is pasted
5899        // into a codec-shaped slot). Before this gate the per-part
5900        // `num_part.trim()` / `unit.trim()` calls silently ate the
5901        // whitespace between the magnitude and the unit and parsed
5902        // the value to `Duration::from_secs(30)`, round-tripping to
5903        // `"30s"` — the codec's *internal* whitespace-tolerance
5904        // vector, orthogonal to the leading / trailing surface but
5905        // the same canonical-form-drift class. Pins the arm as
5906        // strictly stronger than the pre-existing top-level
5907        // `s.trim()` behavior: it fires on whitespace anywhere in
5908        // the value, not just at the string boundary.
5909        let err = duration_codec::parse("30 s").unwrap_err();
5910        assert!(
5911            err.contains("contains whitespace byte"),
5912            "expected whitespace diagnostic in {err:?}"
5913        );
5914        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5915    }
5916
5917    #[test]
5918    fn parse_rejects_tab_byte() {
5919        // `"\t30s"` — the canonical paste-from-indented-doc /
5920        // paste-from-YAML-block-scalar footgun where a tab byte leads
5921        // the magnitude. Pins that the gate covers tab (`0x09`) as
5922        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
5923        // members and both would be silently swallowed by `s.trim()`
5924        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
5925        // space alone to the full ASCII-whitespace set (space `0x20`,
5926        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
5927        // the tab arm as a representative of the non-space members.
5928        let err = duration_codec::parse("\t30s").unwrap_err();
5929        assert!(
5930            err.contains("contains whitespace byte"),
5931            "expected whitespace diagnostic in {err:?}"
5932        );
5933        assert!(
5934            err.contains("0x09"),
5935            "missing offending tab byte in {err:?}"
5936        );
5937    }
5938
5939    #[test]
5940    fn restart_window_serde_rejects_whitespace() {
5941        // The shared codec backs `SupervisorSpec::restart_window`
5942        // (`with = "duration_codec"`) — so the whitespace arm
5943        // applies on serde deserialize for the typed Supervisor slot.
5944        // A `{"restartWindow":" 30s"}` payload that previously round-
5945        // tripped to a different canonical string on next serialize
5946        // is now refused at deserialize with the whitespace-byte
5947        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
5948        // / `restart_window_serde_rejects_leading_plus` /
5949        // `restart_window_serde_rejects_fractional_seconds` on the
5950        // same canonical-form-drift axis.
5951        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5952            "restartWindow":" 30s",
5953            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5954        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5955        let msg = err.to_string();
5956        assert!(
5957            msg.contains("contains whitespace byte"),
5958            "expected whitespace diagnostic in {msg:?}"
5959        );
5960        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
5961    }
5962
5963    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
5964    //
5965    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
5966    // duration codec — closes the strictly-complementary class the
5967    // byte-scan cannot see, through the lifted
5968    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
5969    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
5970    // and `:politicas :circuit-breaker :window` simultaneously via
5971    // this shared codec.
5972
5973    #[test]
5974    fn duration_codec_parse_rejects_leading_nbsp() {
5975        // NBSP prefix — the strictly-complementary drift class the
5976        // ASCII byte-scan cannot see. `str::trim` strips it silently
5977        // and the value drifts to `"30s"` on next serialize.
5978        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
5979        assert!(
5980            err.contains("non-ASCII Unicode whitespace character"),
5981            "expected non-ASCII whitespace diagnostic in {err:?}"
5982        );
5983        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
5984    }
5985
5986    #[test]
5987    fn duration_codec_parse_rejects_trailing_line_separator() {
5988        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
5989        // footgun.
5990        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
5991        assert!(
5992            err.contains("non-ASCII Unicode whitespace character"),
5993            "expected non-ASCII whitespace diagnostic in {err:?}"
5994        );
5995        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
5996    }
5997
5998    #[test]
5999    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
6000        // Positive-control pin: every ASCII-only canonical form the
6001        // renderer emits stays accepted through the new arm.
6002        assert_eq!(
6003            duration_codec::parse("30s").unwrap(),
6004            Duration::from_secs(30)
6005        );
6006        assert_eq!(
6007            duration_codec::parse("500ms").unwrap(),
6008            Duration::from_millis(500)
6009        );
6010        assert_eq!(
6011            duration_codec::parse("1h").unwrap(),
6012            Duration::from_secs(3600)
6013        );
6014    }
6015
6016    #[test]
6017    fn restart_window_serde_rejects_non_ascii_whitespace() {
6018        // The shared codec backs `SupervisorSpec::restart_window` — so
6019        // the new non-ASCII Unicode whitespace arm applies on serde
6020        // deserialize for the typed Supervisor slot. A
6021        // `{"restartWindow":" 30s"}` payload that previously
6022        // survived the ASCII byte-scan (only ASCII whitespace was
6023        // refused) is now refused at deserialize with the
6024        // non-ASCII-whitespace-and-codepoint diagnostic.
6025        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
6026            \"restartWindow\":\"\u{00A0}30s\",\
6027            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
6028        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6029        let msg = err.to_string();
6030        assert!(
6031            msg.contains("non-ASCII Unicode whitespace character"),
6032            "expected non-ASCII whitespace diagnostic in {msg:?}"
6033        );
6034        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
6035    }
6036
6037    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
6038
6039    #[test]
6040    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
6041        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
6042        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
6043        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
6044        // name the exact camelCase JSON keys the
6045        // `#[serde(rename_all = "camelCase")]` attribute on
6046        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
6047        // field carries `Some(_)` / non-empty) and pin that each canonical
6048        // byte-sequence appears verbatim in the JSON — a future accidental
6049        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
6050        // name flip at the derive attribute (any of which would silently
6051        // break every downstream JSON consumer that reaches for one of the
6052        // four consts via `Value::get(...)`) surfaces here as a build-time
6053        // test failure at `supervisor.rs`, not as an apply-time
6054        // `.get(<stale-canonical-const>)` returning `None` far from the
6055        // derive-attr drift's commit. Peer with the sibling
6056        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
6057        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
6058        // M2 typed-slot family established, extended here to close the
6059        // top-level Supervisor axis.
6060        let spec = SupervisorSpec {
6061            estrategia: RestartStrategy::OneForOne,
6062            max_restarts: 5,
6063            restart_window: Some(Duration::from_secs(60)),
6064            children: vec![ChildSpec {
6065                caixa: "w".into(),
6066                versao: "^0.1".into(),
6067                restart: RestartPolicy::Permanent,
6068            }],
6069        };
6070        let json = serde_json::to_string(&spec).unwrap();
6071        for key in [
6072            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6073            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6074            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6075            crate::render::SUPERVISOR_KEY_CHILDREN,
6076        ] {
6077            let quoted = format!("\"{key}\"");
6078            assert!(
6079                json.contains(&quoted),
6080                "serialized SupervisorSpec must carry the lifted \
6081                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
6082                 the JSON emission (got: {json})",
6083            );
6084        }
6085    }
6086
6087    #[test]
6088    fn supervisor_key_consts_are_pairwise_distinct() {
6089        // Cross-axis drift-detection pin: a future collapse of two
6090        // canonical top-level byte-strings onto the same value (e.g. an
6091        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
6092        // also read `"estrategia"`) would silently reroute every
6093        // downstream probe on one axis onto the sibling axis's overlay
6094        // entry and pass every propagation-probe test that expected only
6095        // the stale axis's value. Peer of the sibling four-way distinct
6096        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
6097        let all = [
6098            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6099            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6100            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6101            crate::render::SUPERVISOR_KEY_CHILDREN,
6102        ];
6103        for (i, a) in all.iter().enumerate() {
6104            for b in all.iter().skip(i + 1) {
6105                assert_ne!(
6106                    a, b,
6107                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
6108                     canonical byte-sequences — got `{a}` == `{b}`",
6109                );
6110            }
6111        }
6112    }
6113
6114    #[test]
6115    fn supervisor_key_consts_are_lower_camel_case_shape() {
6116        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
6117        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6118        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6119        // capital, no whitespace / dots) — the canonical shape the
6120        // `#[serde(rename_all = "camelCase")]` derive produces on
6121        // `SupervisorSpec`. A future flip to a non-camelCase attribute
6122        // at the derive surfaces both here (this test fails on the
6123        // stale-constant shape) and at
6124        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6125        // (that test fails on the mismatch between const and derive).
6126        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
6127        // (d8b8b4f) on the sibling M2 `:limits` axis.
6128        for key in [
6129            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6130            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6131            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6132            crate::render::SUPERVISOR_KEY_CHILDREN,
6133        ] {
6134            assert!(
6135                !key.is_empty(),
6136                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
6137            );
6138            let first = key.chars().next().unwrap();
6139            assert!(
6140                first.is_ascii_lowercase(),
6141                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
6142                 (got {key:?}, leads with {first:?})",
6143            );
6144            assert!(
6145                key.chars().all(|c| c.is_ascii_alphanumeric()),
6146                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
6147                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6148            );
6149        }
6150    }
6151
6152    #[test]
6153    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
6154        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
6155        // (camelCase JSON keys, no leading colon) must never collide
6156        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
6157        // consts (kebab-case author-facing labels with leading colon)
6158        // that sit next to them at `caixa_core::render`. Both families
6159        // cover the same four typed Supervisor slots on two distinct
6160        // axes (author-side kebab vs renderer-side camelCase);
6161        // collapsing either family onto the other's byte-shape would
6162        // silently reroute the render-side probe onto the author-facing
6163        // surface, or vice versa. Peer of the byte-distinctness
6164        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
6165        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
6166        let pairs = [
6167            (
6168                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6169                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
6170            ),
6171            (
6172                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6173                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
6174            ),
6175            (
6176                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6177                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
6178            ),
6179            (
6180                crate::render::SUPERVISOR_KEY_CHILDREN,
6181                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
6182            ),
6183        ];
6184        for (json_key, author_key) in pairs {
6185            assert_ne!(
6186                json_key, author_key,
6187                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
6188                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
6189                 got JSON `{json_key}` == author `{author_key}`",
6190            );
6191        }
6192    }
6193
6194    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
6195
6196    #[test]
6197    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
6198        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
6199        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
6200        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
6201        // keys the `#[serde(rename_all = "camelCase")]` attribute on
6202        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
6203        // pin that each canonical byte-sequence appears verbatim in the
6204        // JSON — a future accidental `rename_all = "snake_case"` /
6205        // `"kebab-case"` / verbatim-field-name flip at the derive
6206        // attribute (any of which would silently break every downstream
6207        // JSON consumer that reaches for one of the three consts via
6208        // `Value::get(...)`) surfaces here as a build-time test failure at
6209        // `supervisor.rs`, not as an apply-time
6210        // `.get(<stale-canonical-const>)` returning `None` far from the
6211        // derive-attr drift's commit. Peer with the enclosing
6212        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6213        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
6214        // discipline the SupervisorSpec top-level lift established,
6215        // extended here to the sibling per-`:children` entry `ChildSpec`
6216        // derive so the last M2 typed-struct sub-block
6217        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
6218        // surface without a lifted serde-key peer joins the substrate's
6219        // "one canonical byte-string per typed serialized-key axis"
6220        // discipline.
6221        let c = ChildSpec {
6222            caixa: "worker".into(),
6223            versao: "^0.1".into(),
6224            restart: RestartPolicy::Permanent,
6225        };
6226        let json = serde_json::to_string(&c).unwrap();
6227        for key in [
6228            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6229            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6230            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6231        ] {
6232            let quoted = format!("\"{key}\"");
6233            assert!(
6234                json.contains(&quoted),
6235                "serialized ChildSpec must carry the lifted \
6236                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
6237                 in the JSON emission (got: {json})",
6238            );
6239        }
6240    }
6241
6242    #[test]
6243    fn supervisor_child_key_consts_are_pairwise_distinct() {
6244        // Cross-axis drift-detection pin: a future collapse of two
6245        // canonical `ChildSpec` per-entry byte-strings onto the same
6246        // value (e.g. an accidental copy-paste flip of
6247        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
6248        // silently reroute every downstream probe on one axis onto the
6249        // sibling axis's overlay entry and pass every propagation-probe
6250        // test that expected only the stale axis's value. Peer of the
6251        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
6252        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
6253        // pair (ce80ca0).
6254        let all = [
6255            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6256            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6257            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6258        ];
6259        for (i, a) in all.iter().enumerate() {
6260            for b in all.iter().skip(i + 1) {
6261                assert_ne!(
6262                    a, b,
6263                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
6264                     distinct canonical byte-sequences — got `{a}` == `{b}`",
6265                );
6266            }
6267        }
6268    }
6269
6270    #[test]
6271    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
6272        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
6273        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6274        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6275        // capital, no whitespace / dots) — the canonical shape the
6276        // `#[serde(rename_all = "camelCase")]` derive produces on
6277        // `ChildSpec`. A future flip to a non-camelCase attribute at the
6278        // derive surfaces both here (this test fails on the
6279        // stale-constant shape) and at
6280        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
6281        // (that test fails on the mismatch between const and derive).
6282        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
6283        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
6284        for key in [
6285            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6286            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6287            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6288        ] {
6289            assert!(
6290                !key.is_empty(),
6291                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
6292            );
6293            let first = key.chars().next().unwrap();
6294            assert!(
6295                first.is_ascii_lowercase(),
6296                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
6297                 byte (got {key:?}, leads with {first:?})",
6298            );
6299            assert!(
6300                key.chars().all(|c| c.is_ascii_alphanumeric()),
6301                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
6302                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6303            );
6304        }
6305    }
6306
6307    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
6308
6309    #[test]
6310    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
6311        // The fail-before-pass-after pin: pre-lift there was no
6312        // single-source binding between the [`RestartStrategy`] variant
6313        // name the un-`rename`d `Serialize` derive emits under
6314        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
6315        // every downstream cluster-side dispatcher (the future
6316        // wasm-operator's per-supervisor sibling-restart branch, the
6317        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
6318        // admission-time enum-arm bind, the `caixa-operator`'s
6319        // hierarchical reconciliation scheduler's per-strategy fan-out)
6320        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
6321        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
6322        // override, or a variant rename in the source — would silently
6323        // rebrand the emitted scalar under one spelling while every
6324        // downstream dispatcher still probed the other, with the failure
6325        // surfacing at the operator's reconcile posture (subtrees coming
6326        // up under the `default()` `OneForOne` arm rather than the typed
6327        // slot's declared strategy — a bad child would then only take
6328        // itself down instead of the sibling set the author intended, so
6329        // shared-state children fall out of sync) far from the source
6330        // rebrand commit and with no field naming the drift. Pinning the
6331        // two paths (the `Serialize` derive's serialized string AND the
6332        // [`RestartStrategy::as_str`] helper) to the same four lifted
6333        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
6334        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
6335        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
6336        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
6337        // byte-strings makes any future drift on either endpoint fail
6338        // here at caixa-core build time. Peer of the M3
6339        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
6340        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
6341        // three-path-convergence discipline, extended to close the
6342        // OTP-shaped per-supervisor sibling-restart axis.
6343        for (variant, expected) in [
6344            (
6345                RestartStrategy::OneForOne,
6346                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6347            ),
6348            (
6349                RestartStrategy::OneForAll,
6350                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6351            ),
6352            (
6353                RestartStrategy::RestForOne,
6354                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6355            ),
6356            (
6357                RestartStrategy::SimpleOneForOne,
6358                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6359            ),
6360        ] {
6361            let json = serde_json::to_string(&variant).unwrap();
6362            assert_eq!(
6363                json,
6364                format!("\"{expected}\""),
6365                "RestartStrategy::{variant:?} must serialize to {expected:?}"
6366            );
6367            assert_eq!(
6368                variant.as_str(),
6369                expected,
6370                "RestartStrategy::{variant:?}.as_str() must return the lifted \
6371                 SUPERVISOR_ESTRATEGIA_* constant"
6372            );
6373        }
6374    }
6375
6376    #[test]
6377    fn supervisor_estrategia_consts_are_pairwise_distinct() {
6378        // Cross-arm drift-detection pin: a future collapse of two
6379        // canonical variant byte-strings onto the same value (e.g. an
6380        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
6381        // to also read `"OneForOne"`) would silently reroute every
6382        // downstream operator's per-strategy dispatch onto the sibling
6383        // arm's reconcile branch and pass every propagation-probe test
6384        // that expected only the stale arm's value — the mis-strategied
6385        // subtree would come up with the wrong sibling-restart posture
6386        // on every subsequent failure. Peer of the sibling four-way
6387        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
6388        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
6389        let all = [
6390            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6391            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6392            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6393            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6394        ];
6395        for (i, a) in all.iter().enumerate() {
6396            for (j, b) in all.iter().enumerate() {
6397                if i != j {
6398                    assert_ne!(
6399                        a, b,
6400                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
6401                         — got duplicate {a:?} at indices {i} and {j}",
6402                    );
6403                }
6404            }
6405        }
6406    }
6407
6408    #[test]
6409    fn restart_strategy_display_routes_through_as_str_helper() {
6410        // The fail-before-pass-after pin on the first half of the
6411        // three-path convergence: pre-convergence the sibling
6412        // OTP-shape typed enum [`RestartStrategy`] carried a
6413        // [`std::fmt::Display`] surface via its
6414        // `#[discriminant(also_display)]` gen-platform derive route,
6415        // which arrived kebab-case as `"one-for-one"` /
6416        // `"one-for-all"` / `"rest-for-one"` /
6417        // `"simple-one-for-one"` while the wire format ran as
6418        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
6419        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
6420        // Every consumer reaching for a strategy byte-string past the
6421        // wire format had to pick between three paths
6422        // ([`RestartStrategy::as_str`], the `Serialize` derive's
6423        // serialized string, or `format!("{v}")` on the
6424        // discriminant-Display route), any two of which a future
6425        // variant rename or `#[serde(rename_all = "kebab-case")]`
6426        // attribute would silently desynchronize. Wiring
6427        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
6428        // closes the third path: every `format!("{v}")` call reaches
6429        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6430        // const the wire format and the [`RestartStrategy::as_str`]
6431        // helper already route through, so a future variant rename
6432        // lands at exactly one place. Pin the routing here so a future
6433        // `impl std::fmt::Display for RestartStrategy`
6434        // reimplementation that hand-rolls the arms instead of
6435        // delegating to [`RestartStrategy::as_str`] fails at
6436        // caixa-core build time. Peer of the M3
6437        // `placement_strategy_display_routes_through_as_str_helper`
6438        // (cc8f749) which the M3 axis converged first.
6439        for &variant in RestartStrategy::ALL {
6440            assert_eq!(
6441                variant.to_string(),
6442                variant.as_str(),
6443                "RestartStrategy::{variant:?} Display must route through \
6444                 RestartStrategy::as_str (single source of truth: the lifted \
6445                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
6446            );
6447        }
6448    }
6449
6450    #[test]
6451    fn restart_strategy_display_matches_serialized_wire_byte_string() {
6452        // The fail-before-pass-after pin on the second half of the
6453        // three-path convergence: `Display` (user-facing text) agrees
6454        // byte-for-byte with the `Serialize` derive's wire format
6455        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
6456        // scalar) on every variant. Pre-convergence the two paths
6457        // were structurally independent — a future
6458        // `#[serde(rename_all = "kebab-case")]` attribute on the
6459        // enum would silently rebrand the emitted wire scalar
6460        // (`one-for-one`, `one-for-all`, `rest-for-one`,
6461        // `simple-one-for-one`) while every consumer that
6462        // pretty-prints the strategy (the future wasm-operator's
6463        // per-supervisor sibling-restart-strategy diagnostic line,
6464        // the future `feira app graph` per-supervisor strategy line,
6465        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
6466        // materializer's admission-webhook rejection body) would
6467        // still emit the PascalCase form the `as_str` / `Display`
6468        // route returns, with the mismatch surfacing at consumer
6469        // parse time / operator dispatch time far from the source
6470        // rebrand commit. Pin the two paths byte-for-byte here so any
6471        // future serde-attribute or variant-rename drift is a
6472        // caixa-core-build-time test failure at this call, not a
6473        // silent per-consumer dispatch miss. Peer of the M3
6474        // `placement_strategy_display_matches_serialized_wire_byte_string`
6475        // (cc8f749) which the M3 axis converged first.
6476        for &variant in RestartStrategy::ALL {
6477            let wire = serde_json::to_string(&variant).unwrap();
6478            let unquoted = wire
6479                .strip_prefix('"')
6480                .and_then(|s| s.strip_suffix('"'))
6481                .expect("serialized RestartStrategy is a JSON string");
6482            assert_eq!(
6483                variant.to_string(),
6484                unquoted,
6485                "RestartStrategy::{variant:?} Display byte-string must match the \
6486                 Serialize derive's wire byte-string (three-path convergence: \
6487                 Display + as_str + Serialize all resolve to the same \
6488                 SUPERVISOR_ESTRATEGIA_* const)"
6489            );
6490        }
6491    }
6492
6493    #[test]
6494    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
6495        // Fail-before-pass-after byte-parity pin on the lifted
6496        // `impl AsRef<str> for RestartStrategy` — asserts the
6497        // standard-library trait impl and the substrate-primitive
6498        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
6499        // to the same `&str` per instance across the four-arm
6500        // closed set, so any future silent detour that routes the
6501        // impl through a divergent projection (a per-arm inline
6502        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
6503        // re-inlining that opens a compile-time link to the un-lifted
6504        // arm-literal, a swap onto the kebab-case
6505        // [`gen_platform::Discriminant`] catalog identity that would
6506        // collide the wire axis with the dispatcher-catalog axis) trips
6507        // at caixa-core test time under `PartialEq` rather than at a
6508        // downstream `impl AsRef<str>`-bound consumer's silent split.
6509        // Sweeps every one of the four arms
6510        // [`RestartStrategy::ALL`] carries so no arm's projection is
6511        // covered only by the sibling wire-format `Serialize` derive
6512        // path. Peer of the sibling
6513        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
6514        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
6515        // top-level `:versao` typed newtype — the two pins together
6516        // cover the substrate primitive's `AsRef<str>` projection axis
6517        // on the paired newtype + closed-set-typed-enum surface.
6518        for &variant in RestartStrategy::ALL {
6519            assert_eq!(
6520                <RestartStrategy as AsRef<str>>::as_ref(&variant),
6521                variant.as_str(),
6522                "AsRef<str> impl on RestartStrategy::{variant:?} must \
6523                 byte-equal RestartStrategy::as_str on the same instance \
6524                 — divergence signals a silent detour off the substrate-\
6525                 primitive accessor"
6526            );
6527        }
6528    }
6529
6530    #[test]
6531    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
6532        // Fail-before-pass-after byte-parity pin on the three-path
6533        // convergence discipline the M2 sibling-restart primitive now
6534        // carries on the `&str`-projection axis:
6535        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
6536        // lifted impl), `format!("{s}")` (the pre-existing
6537        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
6538        // primitive `pub const fn` accessor both trait impls delegate
6539        // through) must resolve to the same byte-string on every
6540        // instance across the four-arm closed set. Refuses any future
6541        // divergence between the two trait impls (a stray
6542        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
6543        // rather than delegating through the shared accessor; a
6544        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
6545        // literal cascade) that would silently split the two
6546        // projection paths of the same closed-set typed enum. Mirrors
6547        // the sibling three-path-convergence discipline the peer
6548        // [`crate::CaixaVersion`] typed newtype carries on its
6549        // `AsRef<str>` / `Display` / `as_str` triple
6550        // (version.rs pin
6551        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
6552        // 16d5c7e).
6553        for &variant in RestartStrategy::ALL {
6554            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
6555            let via_display: String = format!("{variant}");
6556            let via_accessor: &str = variant.as_str();
6557            assert_eq!(via_as_ref, via_accessor);
6558            assert_eq!(via_display, via_accessor);
6559            assert_eq!(via_as_ref, via_display.as_str());
6560        }
6561    }
6562
6563    #[test]
6564    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
6565        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
6566        // exhaustive-iteration surface: every variant appears exactly
6567        // once, and the slice length matches the arm count of the
6568        // closed set. Every consumer that walks the accepted-strategy
6569        // set (a future `feira supervisor --estrategia …` CLI-side
6570        // arg-parse's "did you mean" hint, a future M4 admission-
6571        // webhook's rejection body naming the accepted-`:estrategia`
6572        // list, the [`RestartStrategy::from_wire`] reverse-projection
6573        // consumers that iterate the accept-set for diagnostic
6574        // rendering) reads through this slice, so a future arm addition
6575        // that grows the enum but forgets to grow [`Self::ALL`]
6576        // silently truncates every downstream consumer's accept-set at
6577        // the same pre-addition boundary — this pin fails at caixa-core
6578        // build time on the pairwise-distinct + arm-count invariants.
6579        //
6580        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
6581        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
6582        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
6583        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6584        // pins on the peer closed-set typed-enum axes.
6585        let all: &[RestartStrategy] = RestartStrategy::ALL;
6586        assert_eq!(
6587            all.len(),
6588            4,
6589            "RestartStrategy::ALL must enumerate every variant of the \
6590             four-arm closed set (OneForOne, OneForAll, RestForOne, \
6591             SimpleOneForOne); got {all:?}"
6592        );
6593        for (i, a) in all.iter().enumerate() {
6594            for (j, b) in all.iter().enumerate() {
6595                if i != j {
6596                    assert_ne!(
6597                        a, b,
6598                        "RestartStrategy::ALL must carry every variant exactly \
6599                         once — got duplicate {a:?} at indices {i} and {j}"
6600                    );
6601                }
6602            }
6603        }
6604        for variant in [
6605            RestartStrategy::OneForOne,
6606            RestartStrategy::OneForAll,
6607            RestartStrategy::RestForOne,
6608            RestartStrategy::SimpleOneForOne,
6609        ] {
6610            assert!(
6611                all.contains(&variant),
6612                "RestartStrategy::ALL must contain {variant:?} — a future arm \
6613                 addition that grows the enum but forgets to grow the ALL slice \
6614                 silently truncates every downstream consumer's accept-set at \
6615                 the pre-addition boundary"
6616            );
6617        }
6618    }
6619
6620    #[test]
6621    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
6622        // Fail-before-pass-after pin on the forward accept-set of the
6623        // [`RestartStrategy::from_wire`] reverse projection: every
6624        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6625        // constant the [`RestartStrategy::as_str`] emitter walks parses
6626        // back to its paired variant. Any future arm addition that
6627        // grows the emitter's `as_str` match but forgets to grow the
6628        // parser's `from_wire` match silently splits the two halves of
6629        // the round-trip — the wire byte-string one non-serde consumer
6630        // parses from the one the emitter wrote — with the failure
6631        // surfacing at parse time far from the rebrand commit. Pinning
6632        // the four-arm accept-set here catches the drift at caixa-core
6633        // build time.
6634        //
6635        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
6636        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
6637        // accept-set pins on the peer closed-set typed-enum `str → Self`
6638        // axes.
6639        for (wire, expected) in [
6640            (
6641                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6642                RestartStrategy::OneForOne,
6643            ),
6644            (
6645                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6646                RestartStrategy::OneForAll,
6647            ),
6648            (
6649                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6650                RestartStrategy::RestForOne,
6651            ),
6652            (
6653                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6654                RestartStrategy::SimpleOneForOne,
6655            ),
6656        ] {
6657            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6658                panic!(
6659                    "RestartStrategy::from_wire({wire:?}) must accept every \
6660                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
6661                     lifted canonical byte-string that RestartStrategy::{expected:?} \
6662                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
6663                )
6664            });
6665            assert_eq!(
6666                parsed, expected,
6667                "RestartStrategy::from_wire({wire:?}) must return \
6668                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
6669            );
6670        }
6671    }
6672
6673    #[test]
6674    fn restart_strategy_from_wire_round_trips_through_as_str() {
6675        // Fail-before-pass-after pin on the closed round-trip between
6676        // the forward [`RestartStrategy::as_str`] emitter and the
6677        // reverse [`RestartStrategy::from_wire`] parser: for every
6678        // variant in [`RestartStrategy::ALL`], parsing the emitter's
6679        // output must return exactly the same variant. Any per-arm
6680        // divergence — a future arm added to `as_str` but not
6681        // `from_wire`, an accidental copy-paste flip in one but not
6682        // the other — silently splits the emit and parse halves and
6683        // the failure surfaces at consumer parse time far from the
6684        // drift site. The `ALL`-iterating shape means a future arm
6685        // addition picks up the coverage by construction.
6686        //
6687        // Peer of the sibling
6688        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
6689        // (18c7342) round-trip pin on
6690        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
6691        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
6692        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
6693        for &variant in RestartStrategy::ALL {
6694            let wire = variant.as_str();
6695            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6696                panic!(
6697                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6698                     must be Some({variant:?}) — the two halves of the round-trip \
6699                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
6700                     got None on wire byte-string {wire:?}"
6701                )
6702            });
6703            assert_eq!(
6704                parsed, variant,
6705                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6706                 must round-trip to the same variant; got {parsed:?}"
6707            );
6708        }
6709    }
6710
6711    #[test]
6712    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
6713        // Fail-before-pass-after pin on the closed-set refusal
6714        // discipline of [`RestartStrategy::from_wire`]: every
6715        // byte-string outside the four-arm accept-set returns `None`
6716        // rather than silently collapsing onto the [`Default`]
6717        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
6718        // exercised here sweeps the load-bearing drift shapes: the
6719        // empty string (a stripped serde-attribute drift), all-
6720        // whitespace strings (the canonical text-editor accidental
6721        // padding shape), the kebab-case dispatcher-catalog identities
6722        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
6723        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
6724        // derived [`std::str::FromStr`] accept-set, which parses the
6725        // *other* axis of this enum's two-axis split and must not leak
6726        // into the `from_wire` PascalCase-wire accept-set), the
6727        // lowercased single-word forms (`"oneforone"`), the padded
6728        // canonical scalar (`" OneForOne "`), the trailing-newline
6729        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
6730        // (`"AllForOne"` — the canonical typo direction).
6731        //
6732        // Peer of the sibling
6733        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
6734        // (2aa6d23) +
6735        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
6736        // (18c7342) refusal pins on the peer closed-set typed-enum
6737        // axes.
6738        for bad in [
6739            "",
6740            " ",
6741            "\n",
6742            "\t",
6743            "one-for-one",
6744            "one-for-all",
6745            "rest-for-one",
6746            "simple-one-for-one",
6747            "oneforone",
6748            "OneForOnes",
6749            "one_for_one",
6750            "one for one",
6751            "ONEFORONE",
6752            "OneForOne ",
6753            " OneForOne",
6754            " SimpleOneForOne ",
6755            "OneForOne\n",
6756            "restforone",
6757            "REST_FOR_ONE",
6758            "AllForOne",
6759            "Simple",
6760            "?",
6761        ] {
6762            assert!(
6763                RestartStrategy::from_wire(bad).is_none(),
6764                "RestartStrategy::from_wire({bad:?}) must return None — the \
6765                 parser's accept-set is exactly the four RestartStrategy::as_str \
6766                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
6767                 and this byte-string is outside that closed set"
6768            );
6769        }
6770    }
6771
6772    #[test]
6773    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
6774        // Fail-before-pass-after pin on the fourth path of the four-path
6775        // convergence: `from_wire` (the reverse projection) inverts the
6776        // `Serialize` derive's wire byte-string on every variant.
6777        // Together with the pre-existing three-path convergence
6778        // (`Display` + `as_str` + `Serialize` all resolve to the same
6779        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
6780        // pinned by
6781        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
6782        // this closes the round-trip: the wire byte-string the
6783        // `Serialize` derive emits parses back to the same variant
6784        // through `from_wire`, so any future serde-attribute or variant-
6785        // rename drift on the emit half now surfaces as a matched drift
6786        // on the parse half at caixa-core build time — the two halves
6787        // migrate as a unit through the lifted consts on any future
6788        // rename, and the round-trip cannot silently split.
6789        //
6790        // Peer of the sibling
6791        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6792        // (18c7342) wire-format pin on
6793        // [`crate::aplicacao::PlacementStrategy::from_wire`].
6794        for &variant in RestartStrategy::ALL {
6795            let wire = serde_json::to_string(&variant).unwrap();
6796            let unquoted = wire
6797                .strip_prefix('"')
6798                .and_then(|s| s.strip_suffix('"'))
6799                .expect("serialized RestartStrategy is a JSON string");
6800            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
6801                panic!(
6802                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
6803                     Serialize derive's wire byte-string for \
6804                     RestartStrategy::{variant:?} — the four-path convergence \
6805                     (Display + as_str + Serialize + from_wire) resolves through \
6806                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
6807                )
6808            });
6809            assert_eq!(
6810                parsed, variant,
6811                "RestartStrategy::from_wire of the Serialize derive's wire \
6812                 byte-string for RestartStrategy::{variant:?} must round-trip \
6813                 to the same variant; got {parsed:?}"
6814            );
6815        }
6816    }
6817
6818    #[test]
6819    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
6820        // Fail-before-pass-after byte-parity pin on the newly lifted
6821        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
6822        // library trait impl and the substrate-primitive
6823        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
6824        // the same four-arm accept-set across every arm the exhaustive
6825        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
6826        // detour that routes the trait impl through a divergent projection
6827        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
6828        // … }` re-inlining that opens a compile-time link to the un-
6829        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
6830        // attribute drift that silently splits the wire byte-string from
6831        // every consumer that reaches for this typed dispatch, an
6832        // accidental swap onto the kebab-case dispatcher-catalog axis the
6833        // pre-existing [`std::str::FromStr`] impl parses through and which
6834        // would collide the two-axis wire/catalog split the sibling
6835        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
6836        // trips at caixa-core test time under `assert_eq!` rather than at
6837        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
6838        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
6839        // carries so no arm's projection is covered only by the sibling
6840        // method-named `from_wire` path. Peer of the sibling
6841        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
6842        // (3c83606),
6843        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
6844        // (bf33136), and the M3
6845        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
6846        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
6847        // onto the first M2-OTP-shape closed-set typed enum on the caixa
6848        // surface.
6849        for &variant in RestartStrategy::ALL {
6850            let wire = variant.as_str();
6851            assert_eq!(
6852                <RestartStrategy as TryFrom<&str>>::try_from(wire),
6853                Ok(variant),
6854                "TryFrom<&str> impl on RestartStrategy must round-trip \
6855                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
6856                 Ok(RestartStrategy::{variant:?}) — divergence from \
6857                 RestartStrategy::from_wire signals a silent detour off \
6858                 the substrate-primitive accessor"
6859            );
6860            assert_eq!(
6861                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
6862                RestartStrategy::from_wire(wire),
6863                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
6864                 RestartStrategy::from_wire on the same input"
6865            );
6866        }
6867    }
6868
6869    #[test]
6870    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
6871        // Rejection witness on the `impl TryFrom<&str> for
6872        // RestartStrategy` — sweeps a candidate set of byte-strings
6873        // outside the four-arm PascalCase wire accept-set the sibling
6874        // [`RestartStrategy::as_str`] emits and asserts every one lands on
6875        // `Err(())`, so a future accidental widening of the trait impl's
6876        // accept-set (a stray additional
6877        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
6878        // path, a silent inclusion of the kebab-case dispatcher-catalog
6879        // byte-string the pre-existing [`std::str::FromStr`] impl the
6880        // [`gen_platform::FromStrKind`] derive installs parses onto the
6881        // wire axis — which would collide the two-axis
6882        // wire/dispatcher-catalog split the sibling
6883        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
6884        // an English-rebrand or plural-arm silent alias that would
6885        // widen the wire accept-set past the OTP-canonical four) trips at
6886        // caixa-core test time. The candidate set includes the empty
6887        // string, whitespace-only padding, the kebab-case dispatcher-
6888        // catalog byte-strings on the sibling axis (a caller who confuses
6889        // the two axes trips here rather than at a downstream consumer's
6890        // silent reject), a lowercase / uppercase / mixed-case fold of
6891        // each PascalCase arm (a caller who assumes case-fold acceptance
6892        // trips here), leading/trailing whitespace padding, the trailing-
6893        // newline shape, quote-wrapped candidates, and a residual set of
6894        // plausible-but-wrong English rebrand candidates. Peer of the
6895        // sibling
6896        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
6897        // (3c83606) and
6898        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
6899        // (6fd00cd) rejection witnesses.
6900        let rejected: &[&str] = &[
6901            "",
6902            " ",
6903            "\n",
6904            "\t",
6905            "one-for-one",
6906            "one-for-all",
6907            "rest-for-one",
6908            "simple-one-for-one",
6909            "oneforone",
6910            "one_for_one",
6911            "OneForOnes",
6912            "ONEFORONE",
6913            "oneforall",
6914            "restforone",
6915            "simpleoneforone",
6916            "OneForOne ",
6917            " OneForOne",
6918            " OneForAll ",
6919            "OneForOne\n",
6920            "RestForOne\t",
6921            "OneForEach",
6922            "AllForOne",
6923            "one for one",
6924            "\"OneForOne\"",
6925            "?",
6926        ];
6927        for &input in rejected {
6928            assert_eq!(
6929                <RestartStrategy as TryFrom<&str>>::try_from(input),
6930                Err(()),
6931                "TryFrom<&str> impl on RestartStrategy must reject the \
6932                 non-wire byte-string {input:?} — silent acceptance signals \
6933                 an accept-set widening off the paired \
6934                 RestartStrategy::from_wire resolver"
6935            );
6936        }
6937    }
6938
6939    #[test]
6940    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
6941        // Cross-axis partition pin: the paired `TryFrom<&str>` and
6942        // `from_wire` reverse projections must resolve identically on
6943        // *every* input, not just the ones [`RestartStrategy::ALL`]
6944        // enumerates. Sweeps a mixed candidate set spanning accepted
6945        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
6946        // dispatcher-catalog byte-strings, empty, whitespace-padded,
6947        // quoted, English-rebrand candidates) inputs and asserts the
6948        // trait's `Result::ok()` projection byte-equals the method-named
6949        // resolver's `Option<Self>` return-shape on each, locking the two
6950        // paths together by construction so any future detour (a stray
6951        // `try_from` special-case that widens or narrows the accept-set
6952        // outside the paired `from_wire` resolver, an accidental swap
6953        // onto the kebab-case [`std::str::FromStr`] impl the
6954        // [`gen_platform::FromStrKind`] derive installs on the sibling
6955        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
6956        // the sibling
6957        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
6958        // pin — extends the round-trip discipline onto the M2-OTP-shape
6959        // sibling-restart axis.
6960        let candidates: &[&str] = &[
6961            "OneForOne",
6962            "OneForAll",
6963            "RestForOne",
6964            "SimpleOneForOne",
6965            "",
6966            "one-for-one",
6967            "one-for-all",
6968            "rest-for-one",
6969            "simple-one-for-one",
6970            "oneforone",
6971            "unknown",
6972            "OneForOne ",
6973            " OneForOne",
6974            "\"OneForOne\"",
6975            "OneForEach",
6976            "?",
6977        ];
6978        for &input in candidates {
6979            let via_trait: Option<RestartStrategy> =
6980                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
6981            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
6982            assert_eq!(
6983                via_trait, via_method,
6984                "TryFrom<&str> and from_wire must resolve identically on \
6985                 input {input:?} — divergence signals the two reverse-\
6986                 projection paths have drifted onto different accept-sets"
6987            );
6988        }
6989    }
6990
6991    #[test]
6992    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
6993        // Fail-before-pass-after byte-parity pin on the newly lifted
6994        // `impl From<RestartStrategy> for &'static str` — asserts the
6995        // standard-library trait impl and the substrate-primitive
6996        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
6997        // the same four-arm emit-set across every arm the exhaustive
6998        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
6999        // detour that routes the trait impl through a divergent
7000        // projection (a per-arm inline `match strategy { OneForOne =>
7001        // "OneForOne", … }` re-inlining that opens a compile-time link to
7002        // the un-lifted arm-literal, an accidental swap onto the sibling
7003        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
7004        // would collide the two-axis wire/catalog split the sibling
7005        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
7006        // at caixa-core test time under `assert_eq!` rather than at a
7007        // downstream `impl Into<&'static str>`-bound consumer's silent
7008        // split. Sweeps every one of the four arms
7009        // [`RestartStrategy::ALL`] carries so no arm's projection is
7010        // covered only by the sibling method-named `as_str` /
7011        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
7012        // `<&'static str as From<RestartStrategy>>::from` output in a
7013        // `const`-shape binding to make the `'static` lifetime promise a
7014        // build-time invariant — a future accidental downgrade of any of
7015        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7016        // constants to a non-`&'static str` (a `String::leak()`-produced
7017        // return, a `Box::leak`-cast) trips at caixa-core build time
7018        // rather than at a downstream `'static`-bound consumer.
7019        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7020        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7021        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7022        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7023        for &variant in RestartStrategy::ALL {
7024            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7025            let via_method: &'static str = variant.as_str();
7026            assert_eq!(
7027                via_trait, via_method,
7028                "From<RestartStrategy> for &'static str impl must round-trip \
7029                 RestartStrategy::{variant:?} to the same lifted \
7030                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
7031                 divergence signals a silent detour off the substrate-primitive \
7032                 accessor"
7033            );
7034            let via_into: &'static str = variant.into();
7035            assert_eq!(
7036                via_into, via_method,
7037                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
7038                 byte-equal RestartStrategy::as_str on the same input — the \
7039                 blanket-derived Into shape must resolve to the same as_str \
7040                 dispatch as the explicit From impl"
7041            );
7042        }
7043        assert_eq!(
7044            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7045            [
7046                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7047                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7048                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7049                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7050            ],
7051            "const-context RestartStrategy::as_str must resolve to the four \
7052             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
7053             downgrade of any arm to a non-const or non-static byte-string \
7054             breaks the `&'static str`-lifetime promise the paired \
7055             From<RestartStrategy> for &'static str impl carries by \
7056             construction"
7057        );
7058    }
7059
7060    #[test]
7061    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
7062        // Cross-axis partition pin: the paired trait-idiomatic
7063        // `From<RestartStrategy> for &'static str` forward projection and
7064        // the method-named [`RestartStrategy::as_str`] forward projection
7065        // must resolve identically on *every* arm, not just the ones
7066        // named in the primary byte-parity pin above. Sweeps every
7067        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
7068        // output byte-equals the method-named accessor's return-value on
7069        // each, locking the two forward-projection paths together by
7070        // construction so any future detour (a stray `From` special-case
7071        // that lands on a divergent per-arm literal outside the paired
7072        // `as_str` dispatch, a hypothetical rebrand touching one axis
7073        // without the other) trips at caixa-core test time. Peer of the
7074        // sibling reverse-projection partition pin
7075        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7076        // — extends the round-trip discipline onto the trait-idiomatic
7077        // *forward* axis, closing the two-way `Self ↔ &'static str`
7078        // round-trip on the trait-idiomatic pair
7079        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
7080        // well as the pre-existing method-named pair
7081        // (`as_str` + `from_wire`).
7082        for &variant in RestartStrategy::ALL {
7083            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7084            let via_method: &'static str = variant.as_str();
7085            assert_eq!(
7086                via_trait, via_method,
7087                "From<RestartStrategy> for &'static str and \
7088                 RestartStrategy::as_str must resolve identically on \
7089                 RestartStrategy::{variant:?} — divergence signals the \
7090                 two forward-projection paths have drifted onto different \
7091                 emit-sets"
7092            );
7093        }
7094        // Round-trip witness: every arm's forward `From` output re-parses
7095        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
7096        // to the original variant. Closes the two-way `RestartStrategy ↔
7097        // &'static str` round-trip on the trait-idiomatic axis pair,
7098        // mirroring the pre-existing method-named `as_str` + `from_wire`
7099        // round-trip on the substrate-primitive axis pair.
7100        for &variant in RestartStrategy::ALL {
7101            let emitted: &'static str = variant.into();
7102            let re_parsed: Result<RestartStrategy, ()> =
7103                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7104            assert_eq!(
7105                re_parsed,
7106                Ok(variant),
7107                "trait-idiomatic axis pair must round-trip \
7108                 RestartStrategy::{variant:?} through `.into::<&'static \
7109                 str>()` and back through `TryFrom<&str>` — a break signals \
7110                 the forward-emit and reverse-parse axes have drifted onto \
7111                 different vocabularies"
7112            );
7113        }
7114    }
7115
7116    #[test]
7117    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
7118        // Fail-before-pass-after byte-parity pin on the newly lifted
7119        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
7120        // library trait impl and the substrate-primitive
7121        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
7122        // the same three-arm accept-set across every arm the exhaustive
7123        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
7124        // detour that routes the trait impl through a divergent
7125        // projection (a per-arm inline `match s { "Permanent" =>
7126        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
7127        // link to the un-lifted arm-literal, a hypothetical
7128        // `#[serde(rename_all = "…")]` attribute drift that silently
7129        // splits the wire byte-string from every consumer that reaches
7130        // for this typed dispatch, an accidental swap onto the kebab-case
7131        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
7132        // impl parses through and which would collide the two-axis
7133        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
7134        // doc block makes load-bearing) trips at caixa-core test time
7135        // under `assert_eq!` rather than at a downstream
7136        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
7137        // every one of the three arms [`RestartPolicy::ALL`] carries so
7138        // no arm's projection is covered only by the sibling method-
7139        // named `from_wire` path. Peer of the sibling
7140        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
7141        // (5b828ed) — extends the trait-idiomatic reverse-projection
7142        // axis onto the third and final M2-OTP-shape closed-set typed
7143        // enum on the caixa surface (the paired per-child restart-
7144        // decision-policy sibling on the same M2 `:supervisor` slot).
7145        for &variant in RestartPolicy::ALL {
7146            let wire = variant.as_str();
7147            assert_eq!(
7148                <RestartPolicy as TryFrom<&str>>::try_from(wire),
7149                Ok(variant),
7150                "TryFrom<&str> impl on RestartPolicy must round-trip \
7151                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
7152                 Ok(RestartPolicy::{variant:?}) — divergence from \
7153                 RestartPolicy::from_wire signals a silent detour off \
7154                 the substrate-primitive accessor"
7155            );
7156            assert_eq!(
7157                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
7158                RestartPolicy::from_wire(wire),
7159                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
7160                 equal RestartPolicy::from_wire on the same input"
7161            );
7162        }
7163    }
7164
7165    #[test]
7166    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
7167        // Rejection witness on the `impl TryFrom<&str> for
7168        // RestartPolicy` — sweeps a candidate set of byte-strings
7169        // outside the three-arm PascalCase wire accept-set the sibling
7170        // [`RestartPolicy::as_str`] emits and asserts every one lands on
7171        // `Err(())`, so a future accidental widening of the trait impl's
7172        // accept-set (a stray additional
7173        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
7174        // path, a silent inclusion of the kebab-case dispatcher-catalog
7175        // byte-string the pre-existing [`std::str::FromStr`] impl the
7176        // [`gen_platform::FromStrKind`] derive installs parses onto the
7177        // wire axis — which would collide the two-axis
7178        // wire/dispatcher-catalog split the sibling
7179        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
7180        // an English-rebrand or plural-arm silent alias that would widen
7181        // the wire accept-set past the OTP-canonical three) trips at
7182        // caixa-core test time. The candidate set includes the empty
7183        // string, whitespace-only padding, the kebab-case dispatcher-
7184        // catalog byte-strings on the sibling axis (a caller who
7185        // confuses the two axes trips here rather than at a downstream
7186        // consumer's silent reject), a lowercase / uppercase / mixed-case
7187        // fold of each PascalCase arm (a caller who assumes case-fold
7188        // acceptance trips here), leading/trailing whitespace padding,
7189        // the trailing-newline shape, quote-wrapped candidates, and a
7190        // residual set of plausible-but-wrong English rebrand
7191        // candidates. Peer of the sibling
7192        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
7193        // (5b828ed) rejection witness.
7194        let rejected: &[&str] = &[
7195            "",
7196            " ",
7197            "\n",
7198            "\t",
7199            "permanent",
7200            "temporary",
7201            "transient",
7202            "PERMANENT",
7203            "TEMPORARY",
7204            "TRANSIENT",
7205            "Permanents",
7206            "Permanent ",
7207            " Permanent",
7208            " Temporary ",
7209            "Permanent\n",
7210            "Transient\t",
7211            "\"Permanent\"",
7212            "Ephemeral",
7213            "Always",
7214            "Never",
7215            "OnAbnormalExit",
7216            "intrinsic",
7217            "?",
7218        ];
7219        for &input in rejected {
7220            assert_eq!(
7221                <RestartPolicy as TryFrom<&str>>::try_from(input),
7222                Err(()),
7223                "TryFrom<&str> impl on RestartPolicy must reject the \
7224                 non-wire byte-string {input:?} — silent acceptance \
7225                 signals an accept-set widening off the paired \
7226                 RestartPolicy::from_wire resolver"
7227            );
7228        }
7229    }
7230
7231    #[test]
7232    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
7233        // Cross-axis partition pin: the paired `TryFrom<&str>` and
7234        // `from_wire` reverse projections must resolve identically on
7235        // *every* input, not just the ones [`RestartPolicy::ALL`]
7236        // enumerates. Sweeps a mixed candidate set spanning accepted
7237        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
7238        // case dispatcher-catalog byte-strings, empty, whitespace-
7239        // padded, quoted, English-rebrand candidates) inputs and asserts
7240        // the trait's `Result::ok()` projection byte-equals the method-
7241        // named resolver's `Option<Self>` return-shape on each, locking
7242        // the two paths together by construction so any future detour
7243        // (a stray `try_from` special-case that widens or narrows the
7244        // accept-set outside the paired `from_wire` resolver, an
7245        // accidental swap onto the kebab-case [`std::str::FromStr`]
7246        // impl the [`gen_platform::FromStrKind`] derive installs on the
7247        // sibling dispatcher-catalog axis) trips at caixa-core test
7248        // time. Peer of the sibling
7249        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7250        // pin — extends the round-trip discipline onto the M2-OTP-shape
7251        // per-child restart-policy axis.
7252        let candidates: &[&str] = &[
7253            "Permanent",
7254            "Temporary",
7255            "Transient",
7256            "",
7257            "permanent",
7258            "temporary",
7259            "transient",
7260            "PERMANENT",
7261            "unknown",
7262            "Permanent ",
7263            " Permanent",
7264            "\"Permanent\"",
7265            "Ephemeral",
7266            "OnAbnormalExit",
7267            "?",
7268        ];
7269        for &input in candidates {
7270            let via_trait: Option<RestartPolicy> =
7271                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
7272            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
7273            assert_eq!(
7274                via_trait, via_method,
7275                "TryFrom<&str> and from_wire must resolve identically on \
7276                 input {input:?} — divergence signals the two reverse-\
7277                 projection paths have drifted onto different accept-sets"
7278            );
7279        }
7280    }
7281
7282    #[test]
7283    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
7284        // Fail-before-pass-after byte-parity pin on the newly lifted
7285        // `impl From<RestartPolicy> for &'static str` — asserts the
7286        // standard-library trait impl and the substrate-primitive
7287        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
7288        // the same three-arm emit-set across every arm the exhaustive
7289        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
7290        // detour that routes the trait impl through a divergent
7291        // projection (a per-arm inline `match policy { Permanent =>
7292        // "Permanent", … }` re-inlining that opens a compile-time link
7293        // to the un-lifted arm-literal, an accidental swap onto the
7294        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
7295        // axis that would collide the two-axis wire/catalog split the
7296        // sibling [`RestartPolicy::from_wire`] doc block makes
7297        // load-bearing) trips at caixa-core test time under
7298        // `assert_eq!` rather than at a downstream
7299        // `impl Into<&'static str>`-bound consumer's silent split.
7300        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
7301        // carries so no arm's projection is covered only by the sibling
7302        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
7303        // paths. Materializes the `<&'static str as
7304        // From<RestartPolicy>>::from` output in a `const`-shape binding
7305        // to make the `'static` lifetime promise a build-time invariant
7306        // — a future accidental downgrade of any of the three arms'
7307        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
7308        // non-`&'static str` (a `String::leak()`-produced return, a
7309        // `Box::leak`-cast) trips at caixa-core build time rather than
7310        // at a downstream `'static`-bound consumer. Peer of the sibling
7311        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
7312        // (523157d) — extends the trait-idiomatic forward-projection
7313        // axis onto the second (and second-of-two-in-M2) closed-set
7314        // typed enum on the caixa surface (the paired per-child
7315        // restart-decision-policy sibling on the same M2 `:supervisor`
7316        // slot).
7317        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
7318        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
7319        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
7320        for &variant in RestartPolicy::ALL {
7321            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
7322            let via_method: &'static str = variant.as_str();
7323            assert_eq!(
7324                via_trait, via_method,
7325                "From<RestartPolicy> for &'static str impl must round-trip \
7326                 RestartPolicy::{variant:?} to the same lifted \
7327                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
7328                 divergence signals a silent detour off the substrate-primitive \
7329                 accessor"
7330            );
7331            let via_into: &'static str = variant.into();
7332            assert_eq!(
7333                via_into, via_method,
7334                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
7335                 byte-equal RestartPolicy::as_str on the same input — the \
7336                 blanket-derived Into shape must resolve to the same as_str \
7337                 dispatch as the explicit From impl"
7338            );
7339        }
7340        assert_eq!(
7341            [PERMANENT, TEMPORARY, TRANSIENT],
7342            [
7343                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7344                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7345                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7346            ],
7347            "const-context RestartPolicy::as_str must resolve to the three \
7348             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
7349             downgrade of any arm to a non-const or non-static byte-string \
7350             breaks the `&'static str`-lifetime promise the paired \
7351             From<RestartPolicy> for &'static str impl carries by \
7352             construction"
7353        );
7354    }
7355
7356    #[test]
7357    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
7358        // Cross-axis partition pin: the paired trait-idiomatic
7359        // `From<RestartPolicy> for &'static str` forward projection and
7360        // the method-named [`RestartPolicy::as_str`] forward projection
7361        // must resolve identically on *every* arm, not just the ones
7362        // named in the primary byte-parity pin above. Sweeps every
7363        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
7364        // output byte-equals the method-named accessor's return-value on
7365        // each, locking the two forward-projection paths together by
7366        // construction so any future detour (a stray `From` special-case
7367        // that lands on a divergent per-arm literal outside the paired
7368        // `as_str` dispatch, a hypothetical rebrand touching one axis
7369        // without the other) trips at caixa-core test time. Peer of the
7370        // sibling forward-projection partition pin
7371        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
7372        // (523157d) — extends the round-trip discipline onto the
7373        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
7374        // surface, closing the two-way `Self ↔ &'static str` round-trip
7375        // on the trait-idiomatic pair (`From<Self> for &'static str` +
7376        // `TryFrom<&str> for Self`) as well as the pre-existing method-
7377        // named pair (`as_str` + `from_wire`).
7378        for &variant in RestartPolicy::ALL {
7379            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
7380            let via_method: &'static str = variant.as_str();
7381            assert_eq!(
7382                via_trait, via_method,
7383                "From<RestartPolicy> for &'static str and \
7384                 RestartPolicy::as_str must resolve identically on \
7385                 RestartPolicy::{variant:?} — divergence signals the \
7386                 two forward-projection paths have drifted onto different \
7387                 emit-sets"
7388            );
7389        }
7390        // Round-trip witness: every arm's forward `From` output re-parses
7391        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
7392        // to the original variant. Closes the two-way `RestartPolicy ↔
7393        // &'static str` round-trip on the trait-idiomatic axis pair,
7394        // mirroring the pre-existing method-named `as_str` + `from_wire`
7395        // round-trip on the substrate-primitive axis pair.
7396        for &variant in RestartPolicy::ALL {
7397            let emitted: &'static str = variant.into();
7398            let re_parsed: Result<RestartPolicy, ()> =
7399                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
7400            assert_eq!(
7401                re_parsed,
7402                Ok(variant),
7403                "trait-idiomatic axis pair must round-trip \
7404                 RestartPolicy::{variant:?} through `.into::<&'static \
7405                 str>()` and back through `TryFrom<&str>` — a break signals \
7406                 the forward-emit and reverse-parse axes have drifted onto \
7407                 different vocabularies"
7408            );
7409        }
7410    }
7411
7412    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
7413
7414    #[test]
7415    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
7416        // The fail-before-pass-after pin: pre-lift there was no
7417        // single-source binding between the [`RestartPolicy`] variant
7418        // name the un-`rename`d `Serialize` derive emits under
7419        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
7420        // byte-string every downstream cluster-side dispatcher (the
7421        // future wasm-operator's per-child post-exit restart-decision
7422        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7423        // materializer's admission-time enum-arm bind, the
7424        // `caixa-operator`'s hierarchical reconciliation scheduler's
7425        // per-child-policy fan-out) probes verbatim. A future
7426        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
7427        // or a per-variant `#[serde(rename = "…")]` override, or a
7428        // variant rename in the source — would silently rebrand the
7429        // emitted scalar under one spelling while every downstream
7430        // dispatcher still probed the other, with the failure surfacing
7431        // at the operator's reconcile posture (children coming up under
7432        // the `default()` `Permanent` arm rather than the typed slot's
7433        // declared policy — a `:temporary` `oneShot` child would be
7434        // restarted on clean exit, treating the successful-completion
7435        // signal as failure and re-running the completion-terminal
7436        // one-shot indefinitely; a `:transient` child that clean-exited
7437        // would be restarted, masking the clean-completion contract)
7438        // far from the source rebrand commit and with no field naming
7439        // the drift. Pinning the two paths (the `Serialize` derive's
7440        // serialized string AND the [`RestartPolicy::as_str`] helper)
7441        // to the same three lifted
7442        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
7443        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
7444        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
7445        // byte-strings makes any future drift on either endpoint fail
7446        // here at caixa-core build time. Peer of the sibling
7447        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
7448        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
7449        // and the M3
7450        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7451        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
7452        // same three-path-convergence discipline, extended to close the
7453        // third OTP-shaped closed-enum discriminator axis on the caixa
7454        // typed surface (per-child restart-decision policy).
7455        for (variant, expected) in [
7456            (
7457                RestartPolicy::Permanent,
7458                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7459            ),
7460            (
7461                RestartPolicy::Temporary,
7462                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7463            ),
7464            (
7465                RestartPolicy::Transient,
7466                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7467            ),
7468        ] {
7469            let json = serde_json::to_string(&variant).unwrap();
7470            assert_eq!(
7471                json,
7472                format!("\"{expected}\""),
7473                "RestartPolicy::{variant:?} must serialize to {expected:?}"
7474            );
7475            assert_eq!(
7476                variant.as_str(),
7477                expected,
7478                "RestartPolicy::{variant:?}.as_str() must return the lifted \
7479                 SUPERVISOR_CHILD_RESTART_* constant"
7480            );
7481        }
7482    }
7483
7484    #[test]
7485    fn supervisor_child_restart_consts_are_pairwise_distinct() {
7486        // Cross-arm drift-detection pin: a future collapse of two
7487        // canonical variant byte-strings onto the same value (e.g. an
7488        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
7489        // to also read `"Permanent"`) would silently reroute every
7490        // downstream operator's per-child-policy dispatch onto the
7491        // sibling arm's reconcile branch and pass every propagation-probe
7492        // test that expected only the stale arm's value — a `:transient`
7493        // child would come up under the `:permanent` restart-decision
7494        // posture on every subsequent clean exit, so a completion-terminal
7495        // child would be restarted indefinitely against its declared
7496        // policy. Peer of the sibling
7497        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
7498        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
7499        // and the four-way distinct pin
7500        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
7501        // top-level `SUPERVISOR_KEY_*` axis.
7502        let all = [
7503            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7504            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7505            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7506        ];
7507        for (i, a) in all.iter().enumerate() {
7508            for (j, b) in all.iter().enumerate() {
7509                if i != j {
7510                    assert_ne!(
7511                        a, b,
7512                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
7513                         — got duplicate {a:?} at indices {i} and {j}",
7514                    );
7515                }
7516            }
7517        }
7518    }
7519
7520    #[test]
7521    fn restart_policy_display_routes_through_as_str_helper() {
7522        // The fail-before-pass-after pin on the first half of the
7523        // three-path convergence: pre-convergence [`RestartPolicy`]
7524        // carried a [`std::fmt::Display`] surface via its
7525        // `#[discriminant(also_display)]` gen-platform derive route,
7526        // which arrived kebab-case as `"permanent"` / `"temporary"`
7527        // / `"transient"` on this three-arm enum (whose variant
7528        // names each collapse to their own lowercase form under the
7529        // kebab-case transform) while the wire format ran as
7530        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
7531        // through the un-`rename`d serde derive. Every consumer
7532        // reaching for a policy byte-string past the wire format had
7533        // to pick between three paths ([`RestartPolicy::as_str`],
7534        // the `Serialize` derive's serialized string, or
7535        // `format!("{v}")` on the discriminant-Display route), any
7536        // two of which a future variant rename or
7537        // `#[serde(rename_all = "kebab-case")]` attribute would
7538        // silently desynchronize. Wiring [`std::fmt::Display`]
7539        // through [`RestartPolicy::as_str`] closes the third path:
7540        // every `format!("{v}")` call reaches the same lifted
7541        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
7542        // wire format and the [`RestartPolicy::as_str`] helper
7543        // already route through, so a future variant rename lands at
7544        // exactly one place. Pin the routing here so a future
7545        // `impl std::fmt::Display for RestartPolicy`
7546        // reimplementation that hand-rolls the arms instead of
7547        // delegating to [`RestartPolicy::as_str`] fails at
7548        // caixa-core build time. Peer of the sibling
7549        // [`restart_strategy_display_routes_through_as_str_helper`]
7550        // on the per-supervisor sibling-restart-strategy axis and
7551        // the M3
7552        // `placement_strategy_display_routes_through_as_str_helper`
7553        // (cc8f749) — the third of three OTP-shape closed-enum
7554        // discriminator axes on the caixa typed surface now
7555        // converged onto the same three-path
7556        // (Display → as_str → lifted const) discipline.
7557        for variant in [
7558            RestartPolicy::Permanent,
7559            RestartPolicy::Temporary,
7560            RestartPolicy::Transient,
7561        ] {
7562            assert_eq!(
7563                variant.to_string(),
7564                variant.as_str(),
7565                "RestartPolicy::{variant:?} Display must route through \
7566                 RestartPolicy::as_str (single source of truth: the lifted \
7567                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
7568            );
7569        }
7570    }
7571
7572    #[test]
7573    fn restart_policy_display_matches_serialized_wire_byte_string() {
7574        // The fail-before-pass-after pin on the second half of the
7575        // three-path convergence: `Display` (user-facing text) agrees
7576        // byte-for-byte with the `Serialize` derive's wire format
7577        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
7578        // scalar) on every variant. Pre-convergence the two paths
7579        // were structurally independent — a future
7580        // `#[serde(rename_all = "kebab-case")]` attribute on the
7581        // enum would silently rebrand the emitted wire scalar
7582        // (`permanent`, `temporary`, `transient`) while every
7583        // consumer that pretty-prints the policy (the future
7584        // wasm-operator's per-child post-exit restart-decision
7585        // diagnostic line, the future `feira app graph` per-child
7586        // restart column, the future M4
7587        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7588        // per-child admission-webhook rejection body) would still
7589        // emit the PascalCase form the `as_str` / `Display` route
7590        // returns, with the mismatch surfacing at consumer parse
7591        // time / operator dispatch time far from the source rebrand
7592        // commit. Pin the two paths byte-for-byte here so any future
7593        // serde-attribute or variant-rename drift is a
7594        // caixa-core-build-time test failure at this call, not a
7595        // silent per-consumer dispatch miss. Peer of the sibling
7596        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
7597        // on the per-supervisor sibling-restart-strategy axis and
7598        // the M3
7599        // `placement_strategy_display_matches_serialized_wire_byte_string`
7600        // (cc8f749).
7601        for variant in [
7602            RestartPolicy::Permanent,
7603            RestartPolicy::Temporary,
7604            RestartPolicy::Transient,
7605        ] {
7606            let wire = serde_json::to_string(&variant).unwrap();
7607            let unquoted = wire
7608                .strip_prefix('"')
7609                .and_then(|s| s.strip_suffix('"'))
7610                .expect("serialized RestartPolicy is a JSON string");
7611            assert_eq!(
7612                variant.to_string(),
7613                unquoted,
7614                "RestartPolicy::{variant:?} Display byte-string must match the \
7615                 Serialize derive's wire byte-string (three-path convergence: \
7616                 Display + as_str + Serialize all resolve to the same \
7617                 SUPERVISOR_CHILD_RESTART_* const)"
7618            );
7619        }
7620    }
7621
7622    #[test]
7623    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
7624        // Fail-before-pass-after byte-parity pin on the lifted
7625        // `impl AsRef<str> for RestartPolicy` — asserts the
7626        // standard-library trait impl and the substrate-primitive
7627        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
7628        // to the same `&str` per instance across the three-arm
7629        // closed set, so any future silent detour that routes the
7630        // impl through a divergent projection (a per-arm inline
7631        // `match self { RestartPolicy::Permanent => "Permanent", … }`
7632        // re-inlining that opens a compile-time link to the un-lifted
7633        // arm-literal, a swap onto the kebab-case
7634        // [`gen_platform::Discriminant`] catalog identity that would
7635        // collide the wire axis with the dispatcher-catalog axis) trips
7636        // at caixa-core test time under `PartialEq` rather than at a
7637        // downstream `impl AsRef<str>`-bound consumer's silent split.
7638        // Sweeps every one of the three arms
7639        // [`RestartPolicy::ALL`] carries so no arm's projection is
7640        // covered only by the sibling wire-format `Serialize` derive
7641        // path. Peer of the sibling
7642        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
7643        // (63eb1a4) on the paired per-supervisor sibling-restart-
7644        // strategy axis and the [`crate::CaixaVersion`]
7645        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
7646        // top-level `:versao` typed newtype — the three pins together
7647        // cover the substrate primitive's `AsRef<str>` projection axis
7648        // on the paired newtype + M2 closed-set-typed-enum surface.
7649        for &variant in RestartPolicy::ALL {
7650            assert_eq!(
7651                <RestartPolicy as AsRef<str>>::as_ref(&variant),
7652                variant.as_str(),
7653                "AsRef<str> impl on RestartPolicy::{variant:?} must \
7654                 byte-equal RestartPolicy::as_str on the same instance \
7655                 — divergence signals a silent detour off the substrate-\
7656                 primitive accessor"
7657            );
7658        }
7659    }
7660
7661    #[test]
7662    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
7663        // Fail-before-pass-after byte-parity pin on the three-path
7664        // convergence discipline the M2 per-child-restart-policy
7665        // primitive now carries on the `&str`-projection axis:
7666        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
7667        // lifted impl), `format!("{v}")` (the pre-existing
7668        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
7669        // primitive `pub const fn` accessor both trait impls delegate
7670        // through) must resolve to the same byte-string on every
7671        // instance across the three-arm closed set. Refuses any future
7672        // divergence between the two trait impls (a stray
7673        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7674        // rather than delegating through the shared accessor; a
7675        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7676        // literal cascade) that would silently split the two
7677        // projection paths of the same closed-set typed enum. Mirrors
7678        // the sibling three-path-convergence discipline the peer
7679        // [`RestartStrategy`] typed enum carries on its
7680        // `AsRef<str>` / `Display` / `as_str` triple
7681        // (supervisor.rs pin
7682        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
7683        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
7684        // carries on the same triple (version.rs pin
7685        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7686        // 16d5c7e).
7687        for &variant in RestartPolicy::ALL {
7688            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
7689            let via_display: String = format!("{variant}");
7690            let via_accessor: &str = variant.as_str();
7691            assert_eq!(via_as_ref, via_accessor);
7692            assert_eq!(via_display, via_accessor);
7693            assert_eq!(via_as_ref, via_display.as_str());
7694        }
7695    }
7696
7697    #[test]
7698    fn restart_policy_all_enumerates_every_variant_exactly_once() {
7699        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
7700        // exhaustive-iteration surface: every variant appears exactly
7701        // once, and the slice length matches the arm count of the
7702        // closed set. Every consumer that walks the accepted-policy
7703        // set (a future `feira supervisor --restart …` CLI-side
7704        // arg-parse's "did you mean" hint, a future M4 admission-
7705        // webhook's per-child rejection body naming the accepted-
7706        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
7707        // projection consumers that iterate the accept-set for
7708        // diagnostic rendering) reads through this slice, so a future
7709        // arm addition that grows the enum but forgets to grow
7710        // [`Self::ALL`] silently truncates every downstream consumer's
7711        // accept-set at the same pre-addition boundary — this pin
7712        // fails at caixa-core build time on the pairwise-distinct +
7713        // arm-count invariants.
7714        //
7715        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
7716        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
7717        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7718        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7719        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7720        // pins on the peer closed-set typed-enum axes.
7721        let all: &[RestartPolicy] = RestartPolicy::ALL;
7722        assert_eq!(
7723            all.len(),
7724            3,
7725            "RestartPolicy::ALL must enumerate every variant of the \
7726             three-arm closed set (Permanent, Temporary, Transient); \
7727             got {all:?}"
7728        );
7729        for (i, a) in all.iter().enumerate() {
7730            for (j, b) in all.iter().enumerate() {
7731                if i != j {
7732                    assert_ne!(
7733                        a, b,
7734                        "RestartPolicy::ALL must carry every variant exactly \
7735                         once — got duplicate {a:?} at indices {i} and {j}"
7736                    );
7737                }
7738            }
7739        }
7740        for variant in [
7741            RestartPolicy::Permanent,
7742            RestartPolicy::Temporary,
7743            RestartPolicy::Transient,
7744        ] {
7745            assert!(
7746                all.contains(&variant),
7747                "RestartPolicy::ALL must contain {variant:?} — a future arm \
7748                 addition that grows the enum but forgets to grow the ALL slice \
7749                 silently truncates every downstream consumer's accept-set at \
7750                 the pre-addition boundary"
7751            );
7752        }
7753    }
7754
7755    #[test]
7756    fn restart_policy_from_wire_accepts_every_lifted_constant() {
7757        // Fail-before-pass-after pin on the forward accept-set of the
7758        // [`RestartPolicy::from_wire`] reverse projection: every
7759        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
7760        // constant the [`RestartPolicy::as_str`] emitter walks parses
7761        // back to its paired variant. Any future arm addition that
7762        // grows the emitter's `as_str` match but forgets to grow the
7763        // parser's `from_wire` match silently splits the two halves of
7764        // the round-trip — the wire byte-string one non-serde consumer
7765        // parses from the one the emitter wrote — with the failure
7766        // surfacing at the operator's reconcile posture (a `:temporary`
7767        // `oneShot` child restarted on clean exit, a `:transient` child
7768        // restarted after clean completion) far from the rebrand
7769        // commit. Pinning the three-arm accept-set here catches the
7770        // drift at caixa-core build time.
7771        //
7772        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
7773        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
7774        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
7775        // accept-set pins on the peer closed-set typed-enum `str → Self`
7776        // axes.
7777        for (wire, expected) in [
7778            (
7779                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7780                RestartPolicy::Permanent,
7781            ),
7782            (
7783                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7784                RestartPolicy::Temporary,
7785            ),
7786            (
7787                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7788                RestartPolicy::Transient,
7789            ),
7790        ] {
7791            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
7792                panic!(
7793                    "RestartPolicy::from_wire({wire:?}) must accept every \
7794                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
7795                     lifted canonical byte-string that RestartPolicy::{expected:?} \
7796                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
7797                )
7798            });
7799            assert_eq!(
7800                parsed, expected,
7801                "RestartPolicy::from_wire({wire:?}) must return \
7802                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
7803            );
7804        }
7805    }
7806
7807    #[test]
7808    fn restart_policy_from_wire_round_trips_through_as_str() {
7809        // Fail-before-pass-after pin on the closed round-trip between
7810        // the forward [`RestartPolicy::as_str`] emitter and the
7811        // reverse [`RestartPolicy::from_wire`] parser: for every
7812        // variant in [`RestartPolicy::ALL`], parsing the emitter's
7813        // output must return exactly the same variant. Any per-arm
7814        // divergence — a future arm added to `as_str` but not
7815        // `from_wire`, an accidental copy-paste flip in one but not
7816        // the other — silently splits the emit and parse halves and
7817        // the failure surfaces at consumer parse time far from the
7818        // drift site. The `ALL`-iterating shape means a future arm
7819        // addition picks up the coverage by construction.
7820        //
7821        // Peer of the sibling
7822        // [`restart_strategy_from_wire_round_trips_through_as_str`]
7823        // (4eec29c) round-trip pin on
7824        // [`RestartStrategy::from_wire`] and the M3
7825        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
7826        // (18c7342) round-trip pin on
7827        // [`crate::aplicacao::PlacementStrategy::from_wire`].
7828        for &variant in RestartPolicy::ALL {
7829            let wire = variant.as_str();
7830            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
7831                panic!(
7832                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
7833                     must be Some({variant:?}) — the two halves of the round-trip \
7834                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
7835                     got None on wire byte-string {wire:?}"
7836                )
7837            });
7838            assert_eq!(
7839                parsed, variant,
7840                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
7841                 must round-trip to the same variant; got {parsed:?}"
7842            );
7843        }
7844    }
7845
7846    #[test]
7847    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
7848        // Fail-before-pass-after pin on the closed-set refusal
7849        // discipline of [`RestartPolicy::from_wire`]: every
7850        // byte-string outside the three-arm accept-set returns `None`
7851        // rather than silently collapsing onto the [`Default`]
7852        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
7853        // exercised here sweeps the load-bearing drift shapes: the
7854        // empty string (a stripped serde-attribute drift), all-
7855        // whitespace strings (the canonical text-editor accidental
7856        // padding shape), the kebab-case dispatcher-catalog identities
7857        // (`"permanent"` / `"temporary"` / `"transient"` — the
7858        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
7859        // accept-set, which parses the *other* axis of this enum's
7860        // two-axis split and must not leak into the `from_wire`
7861        // PascalCase-wire accept-set — a lowercase leak here would
7862        // silently accept the operator's kebab-case
7863        // dispatcher-catalog probe under the wire-axis parser and mis-
7864        // route a `:permanent` intent), the padded canonical scalar
7865        // (`" Permanent "`), the trailing-newline shapes
7866        // (`"Permanent\n"`), the uppercase-single-word forms
7867        // (`"PERMANENT"`), and neighboring-but-unknown arms
7868        // (`"Restart"` — the canonical typo direction toward the
7869        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
7870        //
7871        // Peer of the sibling
7872        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
7873        // (4eec29c) +
7874        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
7875        // (2aa6d23) +
7876        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
7877        // (18c7342) refusal pins on the peer closed-set typed-enum
7878        // axes.
7879        for bad in [
7880            "",
7881            " ",
7882            "\n",
7883            "\t",
7884            "permanent",
7885            "temporary",
7886            "transient",
7887            "PERMANENT",
7888            "TEMPORARY",
7889            "TRANSIENT",
7890            "Permanents",
7891            "Permanent ",
7892            " Permanent",
7893            " Transient ",
7894            "Permanent\n",
7895            "perma",
7896            "Trans",
7897            "OneForOne",
7898            "Restart",
7899            "?",
7900        ] {
7901            assert!(
7902                RestartPolicy::from_wire(bad).is_none(),
7903                "RestartPolicy::from_wire({bad:?}) must return None — the \
7904                 parser's accept-set is exactly the three RestartPolicy::as_str \
7905                 outputs (Permanent, Temporary, Transient), and this \
7906                 byte-string is outside that closed set"
7907            );
7908        }
7909    }
7910
7911    #[test]
7912    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
7913        // Fail-before-pass-after pin on the fourth path of the four-path
7914        // convergence: `from_wire` (the reverse projection) inverts the
7915        // `Serialize` derive's wire byte-string on every variant.
7916        // Together with the pre-existing three-path convergence
7917        // (`Display` + `as_str` + `Serialize` all resolve to the same
7918        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
7919        // pinned by
7920        // [`restart_policy_display_matches_serialized_wire_byte_string`])
7921        // this closes the round-trip: the wire byte-string the
7922        // `Serialize` derive emits parses back to the same variant
7923        // through `from_wire`, so any future serde-attribute or variant-
7924        // rename drift on the emit half now surfaces as a matched drift
7925        // on the parse half at caixa-core build time — the two halves
7926        // migrate as a unit through the lifted consts on any future
7927        // rename, and the round-trip cannot silently split.
7928        //
7929        // Peer of the sibling
7930        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7931        // (4eec29c) wire-format pin on
7932        // [`RestartStrategy::from_wire`] and the M3
7933        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7934        // (18c7342) wire-format pin on
7935        // [`crate::aplicacao::PlacementStrategy::from_wire`].
7936        for &variant in RestartPolicy::ALL {
7937            let wire = serde_json::to_string(&variant).unwrap();
7938            let unquoted = wire
7939                .strip_prefix('"')
7940                .and_then(|s| s.strip_suffix('"'))
7941                .expect("serialized RestartPolicy is a JSON string");
7942            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
7943                panic!(
7944                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
7945                     Serialize derive's wire byte-string for \
7946                     RestartPolicy::{variant:?} — the four-path convergence \
7947                     (Display + as_str + Serialize + from_wire) resolves through \
7948                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
7949                )
7950            });
7951            assert_eq!(
7952                parsed, variant,
7953                "RestartPolicy::from_wire of the Serialize derive's wire \
7954                 byte-string for RestartPolicy::{variant:?} must round-trip \
7955                 to the same variant; got {parsed:?}"
7956            );
7957        }
7958    }
7959
7960    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
7961    //
7962    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
7963    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
7964    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
7965    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
7966    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
7967    // the peer per-`:upgrade-from :from` axis. The three pins jointly
7968    // brace the accessor against every future silent detour that would
7969    // desynchronize it from the raw `.caixa` field access every consumer
7970    // previously open-coded.
7971
7972    #[test]
7973    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
7974        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
7975        // [`ChildSpec::nome`] must return the `:children :caixa` field
7976        // byte-for-byte across every DNS-1123-label value the upstream
7977        // [`crate::render::require_valid_dns_1123_label`] gate at
7978        // `SupervisorSpec::validate` admits. Peer of the sibling
7979        // `membro_nome_returns_caixa_byte_equal_across_permutations`
7980        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
7981        // substrate-primitive accessor must byte-equal the raw field
7982        // access verbatim across every author-declared value" discipline
7983        // extended to the M2 supervisor-tree per-`:children` arm. Pins
7984        // against a future silent detour that re-normalized the child
7985        // identity (an accidental `.to_lowercase()` — every `:children
7986        // :caixa` is validated as a DNS-1123 label upstream, so any
7987        // re-normalization is redundant + a drift surface between the
7988        // validator and the accessor), a namespace-prefix rewrite (an
7989        // accidental `format!("{namespace}/{caixa}")` per-CR
7990        // fully-qualified rewrite that didn't land on the peer axes), or
7991        // a per-cluster alias stamp the future wasm-operator's
7992        // hierarchical reconciliation scheduler authors on one consumer
7993        // without the others. Five values sweep the accept-set the
7994        // DNS-1123 gate upstream admits (short single-word / dashed /
7995        // v-suffixed / mixed-digit child names).
7996        for name in [
7997            "worker",
7998            "cache-server",
7999            "scratch-job",
8000            "orders-v2",
8001            "session-8080",
8002        ] {
8003            let c = ChildSpec {
8004                caixa: name.into(),
8005                versao: "^0.1".into(),
8006                restart: RestartPolicy::Permanent,
8007            };
8008            assert_eq!(
8009                c.nome(),
8010                name,
8011                "ChildSpec::nome must return :children :caixa verbatim \
8012                 (got {:?}, expected {name:?})",
8013                c.nome(),
8014            );
8015            assert_eq!(
8016                c.nome(),
8017                c.caixa.as_str(),
8018                "ChildSpec::nome must byte-equal the .caixa field access",
8019            );
8020        }
8021    }
8022
8023    #[test]
8024    fn child_spec_nome_borrows_from_caixa_storage() {
8025        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
8026        // `&str` slice that borrows from the typed slot's own [`String`]
8027        // storage — same-address invariant with `c.caixa.as_str()`. Pins
8028        // against a future silent detour that allocated a fresh `String`
8029        // (`self.caixa.clone()` in the body would type-check but silently
8030        // drop the borrow, and every downstream consumer that assumed
8031        // the returned slice outlives `&self` would break on a stale-
8032        // reference use-after-free — the [`crate::render::insert_first_seen`]
8033        // dedup key at [`SupervisorSpec::validate`], the
8034        // [`validate_no_self_supervision`] equality check against the
8035        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
8036        // borrow — each would silently misbehave if this accessor
8037        // produced a detached copy). Peer of the sibling
8038        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
8039        // M3 per-`:membros` axis and the
8040        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
8041        // first M2 slot scalar accessor.
8042        let c = ChildSpec {
8043            caixa: "worker".into(),
8044            versao: "^0.1".into(),
8045            restart: RestartPolicy::Permanent,
8046        };
8047        let name = c.nome();
8048        let caixa_slice = c.caixa.as_str();
8049        assert_eq!(
8050            name.as_ptr(),
8051            caixa_slice.as_ptr(),
8052            "ChildSpec::nome must borrow from the .caixa String's backing \
8053             storage — a fresh allocation here means the accessor no \
8054             longer names the substrate-primitive typed dispatch and \
8055             every downstream consumer would silently carry a detached \
8056             copy",
8057        );
8058        assert_eq!(
8059            name.len(),
8060            caixa_slice.len(),
8061            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
8062             as well as in address",
8063        );
8064    }
8065
8066    #[test]
8067    fn validate_gates_child_nome_through_lifted_accessor() {
8068        // Bilateral coherence pin: every `:children :caixa` that
8069        // [`SupervisorSpec::validate`] accepts is one
8070        // [`crate::render::require_valid_dns_1123_label`] accepts on the
8071        // accessor-projected value, and vice versa on the reject side.
8072        // This closes the "the validator reads through the accessor"
8073        // contract structurally — a future silent detour that made the
8074        // accessor return a different byte-string than the validator
8075        // gates against would surface here as a coverage mismatch, not
8076        // as an apply-time DNS-1123 rejection at
8077        // `metadata.name: Invalid value` far from the caixa.lisp source.
8078        // Peer of the M2 sibling
8079        // `validate_parses_prior_versao_through_lifted_accessor`
8080        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
8081        // `validate_membros` peer discipline.
8082        //
8083        // Accept-set sweep: five DNS-1123-label values the upstream gate
8084        // admits.
8085        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
8086            let s = SupervisorSpec {
8087                children: vec![ChildSpec {
8088                    caixa: ok_name.into(),
8089                    versao: "^0.1".into(),
8090                    restart: RestartPolicy::Permanent,
8091                }],
8092                ..SupervisorSpec::default()
8093            };
8094            s.validate().unwrap_or_else(|e| {
8095                panic!(
8096                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
8097                     (upstream DNS-1123 gate accepts it): got {e:?}",
8098                );
8099            });
8100            let c = ChildSpec {
8101                caixa: ok_name.into(),
8102                versao: "^0.1".into(),
8103                restart: RestartPolicy::Permanent,
8104            };
8105            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
8106                .unwrap_or_else(|()| {
8107                    panic!(
8108                        "require_valid_dns_1123_label must accept the accessor-projected \
8109                     :children :caixa {ok_name:?}",
8110                    );
8111                });
8112        }
8113        // Reject-set sweep: five DNS-1123-label-violating shapes the
8114        // upstream gate refuses (empty / uppercase / underscore / dot /
8115        // leading-hyphen). Every rejection at the validator must
8116        // correspond to a rejection when the accessor's projected value
8117        // is fed back through the shared gate.
8118        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
8119            let s = SupervisorSpec {
8120                children: vec![ChildSpec {
8121                    caixa: bad_name.into(),
8122                    versao: "^0.1".into(),
8123                    restart: RestartPolicy::Permanent,
8124                }],
8125                ..SupervisorSpec::default()
8126            };
8127            let err = s.validate().unwrap_err();
8128            assert!(
8129                matches!(
8130                    err,
8131                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
8132                ),
8133                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
8134                 via the DNS-1123 gate: got {err:?}",
8135            );
8136            let c = ChildSpec {
8137                caixa: bad_name.into(),
8138                versao: "^0.1".into(),
8139                restart: RestartPolicy::Permanent,
8140            };
8141            assert!(
8142                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
8143                    .is_err(),
8144                "require_valid_dns_1123_label must reject the accessor-projected \
8145                 :children :caixa {bad_name:?}",
8146            );
8147        }
8148    }
8149
8150    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
8151    //
8152    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
8153    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
8154    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
8155    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
8156    // trio on the peer per-`:children` `String`-carry axis. The three pins
8157    // jointly brace the accessor against every future silent detour that
8158    // would desynchronize it from the raw `.versao` field access the
8159    // requirement gate + error carrier previously open-coded.
8160    //
8161    // Closes the last unlifted per-`:children` `String`-carry axis: the
8162    // pair (`nome`, `versao_requirement`) now jointly projects the
8163    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
8164    // consumer that fans on per-child identity + version pin reads,
8165    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
8166    // pair discipline verbatim.
8167    #[test]
8168    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
8169        // The canonical per-`:children` child-`:versao`-scalar pin:
8170        // [`ChildSpec::versao_requirement`] must return the `:children
8171        // :versao` field byte-for-byte across every Cargo-shaped semver
8172        // requirement value the upstream
8173        // [`crate::render::require_valid_versao_requirement`] gate admits.
8174        // Peer of the sibling
8175        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
8176        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
8177        // substrate-primitive accessor must byte-equal the raw field
8178        // access verbatim across every author-declared value" discipline
8179        // extended to the M2 supervisor-tree per-`:children` arm. Pins
8180        // against a future silent detour that re-canonicalized the
8181        // requirement (an accidental `.to_string()` via
8182        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
8183        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
8184        // silently drifted the error carrier's quoted requirement away
8185        // from the source `caixa.lisp`, an accidental whitespace trim on
8186        // `"^ 0.1"` that no consumer ever produced from the field-access
8187        // side, an accidental per-cluster lacre-projected concrete-version
8188        // rewrite that didn't land on the peer requirement-gate call).
8189        // Five values sweep the accept-set the shared
8190        // [`crate::render::require_valid_versao_requirement`] gate admits
8191        // (caret / tilde / exact / wildcard / bare-major).
8192        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
8193            let c = ChildSpec {
8194                caixa: "worker".into(),
8195                versao: req.into(),
8196                restart: RestartPolicy::Permanent,
8197            };
8198            assert_eq!(
8199                c.versao_requirement(),
8200                req,
8201                "ChildSpec::versao_requirement must return :children :versao \
8202                 verbatim (got {:?}, expected {req:?})",
8203                c.versao_requirement(),
8204            );
8205            assert_eq!(
8206                c.versao_requirement(),
8207                c.versao.as_str(),
8208                "ChildSpec::versao_requirement must byte-equal the .versao \
8209                 field access",
8210            );
8211        }
8212    }
8213
8214    #[test]
8215    fn child_spec_versao_requirement_borrows_from_versao_storage() {
8216        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
8217        // return a `&str` slice that borrows from the typed slot's own
8218        // [`String`] storage — same-address invariant with
8219        // `c.versao.as_str()`. Pins against a future silent detour that
8220        // allocated a fresh `String` (`self.versao.clone()` in the body
8221        // would type-check but silently drop the borrow, and every
8222        // downstream consumer that assumed the returned slice outlives
8223        // `&self` — the [`crate::render::require_valid_versao_requirement`]
8224        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
8225        // `.to_string()` carrier's byte-length assumption — would silently
8226        // misbehave if this accessor produced a detached copy). Peer of
8227        // the sibling `child_spec_nome_borrows_from_caixa_storage`
8228        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
8229        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
8230        // pin on the peer per-`:membros` `:versao` axis.
8231        let c = ChildSpec {
8232            caixa: "worker".into(),
8233            versao: "^0.1".into(),
8234            restart: RestartPolicy::Permanent,
8235        };
8236        let req = c.versao_requirement();
8237        let versao_slice = c.versao.as_str();
8238        assert_eq!(
8239            req.as_ptr(),
8240            versao_slice.as_ptr(),
8241            "ChildSpec::versao_requirement must borrow from the .versao \
8242             String's backing storage — a fresh allocation here means the \
8243             accessor no longer names the substrate-primitive typed \
8244             dispatch and every downstream consumer would silently carry \
8245             a detached copy",
8246        );
8247        assert_eq!(
8248            req.len(),
8249            versao_slice.len(),
8250            "ChildSpec::versao_requirement and .versao.as_str() must \
8251             byte-equal in length as well as in address",
8252        );
8253    }
8254
8255    #[test]
8256    fn validate_gates_child_versao_through_lifted_accessor() {
8257        // Bilateral coherence pin: every `:children :versao` that
8258        // [`SupervisorSpec::validate`] accepts is one
8259        // [`crate::render::require_valid_versao_requirement`] accepts on
8260        // the accessor-projected value, and vice versa on the reject side.
8261        // This closes the "the validator reads through the accessor"
8262        // contract structurally — a future silent detour that made the
8263        // accessor return a different byte-string than the validator gates
8264        // against would surface here as a coverage mismatch, not as a
8265        // resolver-time semver-parse rejection at lacre-closure time far
8266        // from the caixa.lisp source. Peer of the sibling
8267        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
8268        // the per-`:children :caixa` axis and the M2
8269        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
8270        // on the peer per-`:upgrade-from :from` axis.
8271        //
8272        // Accept-set sweep: five Cargo-shaped semver requirement values
8273        // the upstream gate admits (caret / tilde / exact / wildcard /
8274        // bare-major).
8275        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
8276            let s = SupervisorSpec {
8277                children: vec![ChildSpec {
8278                    caixa: "worker".into(),
8279                    versao: ok_req.into(),
8280                    restart: RestartPolicy::Permanent,
8281                }],
8282                ..SupervisorSpec::default()
8283            };
8284            s.validate().unwrap_or_else(|e| {
8285                panic!(
8286                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
8287                     (upstream versao-requirement gate accepts it): got {e:?}",
8288                );
8289            });
8290            let c = ChildSpec {
8291                caixa: "worker".into(),
8292                versao: ok_req.into(),
8293                restart: RestartPolicy::Permanent,
8294            };
8295            crate::render::require_valid_versao_requirement(
8296                c.versao_requirement(),
8297                || (),
8298                |_reason| (),
8299            )
8300            .unwrap_or_else(|()| {
8301                panic!(
8302                    "require_valid_versao_requirement must accept the accessor-projected \
8303                     :children :versao {ok_req:?}",
8304                );
8305            });
8306        }
8307        // Reject-set sweep: five requirement-violating shapes the upstream
8308        // gate refuses. The empty string closes the empty-first arm of the
8309        // shared [`crate::render::require_valid_versao_requirement`]
8310        // cascade; the four non-empty arms exercise distinct semver-parse
8311        // failure modes the M3 peer per-`:membros` reject-set already pins
8312        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
8313        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
8314        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
8315        // shared parser routing means the same reject-set must fail
8316        // identically at the M2 supervisor-tree per-`:children` accessor
8317        // arm here. Every rejection at the validator must correspond to a
8318        // rejection when the accessor's projected value is fed back
8319        // through the shared gate.
8320        //
8321        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
8322        // `"not-a-semver"` are intentionally *not* in the reject-set: the
8323        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
8324        // and the identifier-tail arm's grammar admits some non-canonical
8325        // shapes — matching what the M3 peer test suite already documents
8326        // as the shared parser's accept-set edges.)
8327        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
8328            let s = SupervisorSpec {
8329                children: vec![ChildSpec {
8330                    caixa: "worker".into(),
8331                    versao: bad_req.into(),
8332                    restart: RestartPolicy::Permanent,
8333                }],
8334                ..SupervisorSpec::default()
8335            };
8336            let err = s.validate().unwrap_err();
8337            assert!(
8338                matches!(
8339                    err,
8340                    SupervisorError::EmptyChildVersion { .. }
8341                        | SupervisorError::ChildVersaoInvalid { .. }
8342                ),
8343                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
8344                 via the versao-requirement gate: got {err:?}",
8345            );
8346            let c = ChildSpec {
8347                caixa: "worker".into(),
8348                versao: bad_req.into(),
8349                restart: RestartPolicy::Permanent,
8350            };
8351            assert!(
8352                crate::render::require_valid_versao_requirement(
8353                    c.versao_requirement(),
8354                    || (),
8355                    |_reason| (),
8356                )
8357                .is_err(),
8358                "require_valid_versao_requirement must reject the accessor-projected \
8359                 :children :versao {bad_req:?}",
8360            );
8361        }
8362    }
8363
8364    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
8365    //
8366    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
8367    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
8368    // already project the `String`-carry `(caixa, versao)` fields; the
8369    // `Copy`-composite-enum `restart` field is the third and final axis).
8370    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
8371    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
8372    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
8373    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
8374    // strategy scalar accessor — same "one typed dispatch on the substrate
8375    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
8376    // extended onto the M2 supervisor-slot per-`:children` restart-decision
8377    // axis. The pin below covers the accessor's byte-equal projection
8378    // against the raw field access across every variant in the closed
8379    // accept-set (`Permanent`, `Transient`, `Temporary`).
8380
8381    #[test]
8382    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
8383        // The canonical per-`:children` restart-decision-policy-scalar
8384        // pin: [`ChildSpec::restart`] must return the `:children :restart`
8385        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
8386        // typed slot's own [`RestartPolicy`] storage across every variant
8387        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
8388        // Pins against a future silent detour that re-derived the policy
8389        // from a peer axis (an accidental fallback to
8390        // `if is_supervisor_child { Permanent } else { Temporary }` that
8391        // collapsed the child's kind axis into the restart discriminator),
8392        // a variant remap the operator authors on one consumer without the
8393        // other, or a stale-derive detour that substituted
8394        // [`RestartPolicy::default`] when the field held any explicit
8395        // variant (which would silently collapse the distinction between
8396        // "author explicitly declared `:restart Permanent`" and "author
8397        // omitted the slot and inherited the default" the future
8398        // per-cluster restart-decision override slot depends on).
8399        //
8400        // Peer of the sibling per-`:supervisor`
8401        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
8402        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
8403        // axis and the M3
8404        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
8405        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
8406        // — same "the substrate-primitive accessor must byte-equal the raw
8407        // field access verbatim across every author-declared value"
8408        // discipline extended onto the M2 supervisor-slot per-`:children`
8409        // restart-decision-policy axis, closing the last unlifted axis on
8410        // the per-`:children` [`ChildSpec`] type.
8411        for restart in [
8412            RestartPolicy::Permanent,
8413            RestartPolicy::Transient,
8414            RestartPolicy::Temporary,
8415        ] {
8416            let c = ChildSpec {
8417                caixa: "worker".into(),
8418                versao: "^0.1".into(),
8419                restart,
8420            };
8421            assert_eq!(
8422                c.restart(),
8423                restart,
8424                "ChildSpec::restart must return :children :restart \
8425                 verbatim (got {:?}, expected {restart:?})",
8426                c.restart(),
8427            );
8428            assert_eq!(
8429                c.restart(),
8430                c.restart,
8431                "ChildSpec::restart accessor and .restart field access \
8432                 must byte-equal — the accessor is the substrate-primitive \
8433                 typed dispatch every downstream per-child restart-\
8434                 decision consumer must route through",
8435            );
8436        }
8437    }
8438
8439    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
8440    //
8441    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
8442    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
8443    // distribution-strategy accessor discipline onto the M2 supervisor-slot
8444    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
8445    // scalar axis. The two pins below cover (1) the accessor's byte-equal
8446    // projection against the raw field access across every variant in the
8447    // closed accept-set, and (2) the two-consumer coherence between the
8448    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
8449    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
8450    // carrier's `estrategia:` field — peer of the sibling M3
8451    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
8452    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
8453    // pair on the per-`:placement` distribution-strategy axis.
8454
8455    #[test]
8456    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
8457        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
8458        // pin: [`SupervisorSpec::estrategia`] must return the
8459        // `:supervisor :estrategia` field verbatim as a
8460        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
8461        // [`RestartStrategy`] storage across every variant in the closed
8462        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
8463        // `SimpleOneForOne`). Pins against a future silent detour that
8464        // re-derived the strategy from a peer axis (an accidental
8465        // fallback to `if children.is_empty() { SimpleOneForOne } else {
8466        // OneForOne }` collapse that read the children-count axis into
8467        // the strategy discriminator), a variant remap the operator
8468        // authors on one consumer without the other, or a stale-derive
8469        // detour that substituted [`RestartStrategy::default`] when the
8470        // field held any explicit variant (which would silently collapse
8471        // the distinction between "author explicitly declared
8472        // `:estrategia OneForOne`" and "author omitted the slot and
8473        // inherited the default" the future per-cluster strategy override
8474        // slot depends on). Peer of the sibling M3
8475        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
8476        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
8477        // axis — same "the substrate-primitive accessor must byte-equal
8478        // the raw field access verbatim across every author-declared
8479        // value" discipline extended onto the M2 supervisor-slot
8480        // per-`:supervisor` sibling-restart-strategy axis.
8481        for &estrategia in RestartStrategy::ALL {
8482            // `SimpleOneForOne` requires `children.is_empty()`; the peer
8483            // three strategies require a non-empty static children list.
8484            // Build each shape coherently so the pin's fixture would
8485            // itself pass [`SupervisorSpec::validate`] once fed through
8486            // the sibling coherence pin below — the byte-equal projection
8487            // asserted here is a strictly weaker property (a `Copy` field
8488            // read) that does not depend on `validate` running, but
8489            // keeping the fixture validate-clean means a future extension
8490            // of the pin to exercise `validate` end-to-end does not have
8491            // to re-author the children shape.
8492            //
8493            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
8494            // shape partition through the [`gen_platform::IsVariant`]
8495            // derive-generated
8496            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
8497            // than the raw `matches!(estrategia, RestartStrategy::
8498            // SimpleOneForOne)` open-coded pattern-match — same closed-
8499            // set-typed-enum arm-discriminator dispatch discipline the
8500            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
8501            // convergence (915a934) extended onto its two paired positive
8502            // / negated `matches!` sites and the peer
8503            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
8504            // predicate convergence (766ec63) extended onto the M3 mesh-
8505            // slot per-`:placement` distribution-strategy discriminator
8506            // axis. See the sibling `round_trip_all_strategies` and the
8507            // peer `manifest::tests::
8508            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
8509            // fixture for the two peer sites the same lift closes on.
8510            let children = if estrategia.is_simple_one_for_one() {
8511                Vec::new()
8512            } else {
8513                vec![ChildSpec {
8514                    caixa: "worker".into(),
8515                    versao: "^0.1".into(),
8516                    restart: RestartPolicy::Permanent,
8517                }]
8518            };
8519            let s = SupervisorSpec {
8520                estrategia,
8521                children,
8522                ..SupervisorSpec::default()
8523            };
8524            assert_eq!(
8525                s.estrategia(),
8526                estrategia,
8527                "SupervisorSpec::estrategia must return :supervisor :estrategia \
8528                 verbatim (got {:?}, expected {estrategia:?})",
8529                s.estrategia(),
8530            );
8531            assert_eq!(
8532                s.estrategia(),
8533                s.estrategia,
8534                "SupervisorSpec::estrategia accessor and .estrategia field \
8535                 access must byte-equal — the accessor is the substrate-\
8536                 primitive typed dispatch every downstream sibling-restart-\
8537                 strategy consumer must route through",
8538            );
8539        }
8540    }
8541
8542    #[test]
8543    fn validate_reads_through_lifted_estrategia_accessor() {
8544        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
8545        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
8546        // dispatch (which reads through [`SupervisorSpec::estrategia`]
8547        // to fan across the strategy-arm shape-gate cascades) and the
8548        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
8549        // error carrier's `estrategia:` field (which reads through
8550        // [`SupervisorSpec::estrategia`] to name the strategy the empty
8551        // `:children` list was declared against) must both key off the
8552        // lifted accessor, so any future rebrand on the typed slot's
8553        // reader shape lands at exactly one place. Pins the two-site
8554        // coherence by exercising the `NoChildren` error surface end-to-
8555        // end across every non-`SimpleOneForOne` variant and asserting
8556        // the surfaced `estrategia:` field byte-equals the accessor's
8557        // return. Peer of the sibling M3
8558        // `validate_placement_reads_through_lifted_estrategia_accessor`
8559        // (921fe1b) three-consumer coherence pin on the per-`:placement`
8560        // distribution-strategy axis.
8561        for estrategia in [
8562            RestartStrategy::OneForOne,
8563            RestartStrategy::OneForAll,
8564            RestartStrategy::RestForOne,
8565        ] {
8566            let s = SupervisorSpec {
8567                estrategia,
8568                children: Vec::new(),
8569                ..SupervisorSpec::default()
8570            };
8571            let err = s.validate().unwrap_err();
8572            match err {
8573                SupervisorError::NoChildren { estrategia: e } => {
8574                    assert_eq!(
8575                        e,
8576                        s.estrategia(),
8577                        "NoChildren.estrategia must byte-equal \
8578                         SupervisorSpec::estrategia() — the empty-`:children` \
8579                         refusal reads through the lifted accessor",
8580                    );
8581                    assert_eq!(
8582                        e, estrategia,
8583                        "NoChildren.estrategia must carry the author-declared \
8584                         :supervisor :estrategia variant verbatim (got {e:?}, \
8585                         expected {estrategia:?})",
8586                    );
8587                }
8588                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
8589            }
8590        }
8591    }
8592
8593    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
8594    //
8595    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
8596    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
8597    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
8598    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
8599    // The two pins below cover (1) the accessor's byte-equal projection
8600    // against the raw field access across every representative value in
8601    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
8602    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
8603    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
8604    // zero-floor / cap composition — the validate gate and the accessor
8605    // must route through the same substrate-primitive typed dispatch, so
8606    // any future silent detour that had the accessor perform a
8607    // bounds-collapsing clamp would fail here at caixa-core build time.
8608    // Peer of the sibling M3
8609    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
8610    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
8611
8612    #[test]
8613    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
8614        // The canonical per-`:supervisor` restart-budget-count scalar pin:
8615        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
8616        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
8617        // typed slot's own `u32` storage, byte-equal to the raw field
8618        // access across every representative value in the accept-set —
8619        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
8620        // accept-set the surrounding [`SupervisorSpec::validate`] gate
8621        // carves out on the sibling `ZeroMaxRestarts` refusal),
8622        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
8623        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
8624        // (a past-the-guard sentinel that pins the accessor doesn't
8625        // perform a silent bounds-collapse into `1` on the zero arm —
8626        // validate rejects zero but the accessor must ship the raw slot
8627        // verbatim so a validate-time gate regression surfaces at the
8628        // emit boundary rather than being silently absorbed), `u32::MAX`
8629        // (a past-the-guard sentinel that pins the accessor doesn't
8630        // perform a silent bounds-collapse through
8631        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
8632        //
8633        // Peer of the sibling M3
8634        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
8635        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
8636        // required-scalar axis — same "the substrate-primitive accessor
8637        // must byte-equal the raw field access verbatim across every
8638        // value in the `u32` accept-set" discipline extended onto the M2
8639        // supervisor-slot per-`:supervisor` restart-budget-count axis.
8640        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
8641            let s = SupervisorSpec {
8642                max_restarts,
8643                ..SupervisorSpec::default()
8644            };
8645            assert_eq!(
8646                s.max_restarts(),
8647                max_restarts,
8648                "SupervisorSpec::max_restarts must return :supervisor \
8649                 :max-restarts verbatim (got {}, expected {max_restarts})",
8650                s.max_restarts(),
8651            );
8652            assert_eq!(
8653                s.max_restarts(),
8654                s.max_restarts,
8655                "SupervisorSpec::max_restarts accessor and .max_restarts \
8656                 field access must byte-equal — the accessor is the \
8657                 substrate-primitive typed dispatch every downstream \
8658                 restart-budget-count consumer must route through",
8659            );
8660        }
8661    }
8662
8663    #[test]
8664    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
8665        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
8666        // zero-floor + upper-cap bracket must key off
8667        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
8668        // field access. Structurally: a `SupervisorSpec { max_restarts:
8669        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
8670        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
8671        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
8672        // (with the offending count carried verbatim from the accessor
8673        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
8674        // lower boundary of the accept-set) plus a `SupervisorSpec {
8675        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
8676        // boundary) must pass validate. The four together jointly pin the
8677        // accessor + validate-gate composition: any future silent detour
8678        // that had the accessor return a fresh `1` on the zero arm (a
8679        // `.max_restarts().max(1)` collapse) would silently absorb the
8680        // `ZeroMaxRestarts` refusal at the accessor boundary and the
8681        // validate gate would accept a struct-literal `SupervisorSpec {
8682        // max_restarts: 0, .. }` — the composition pin catches that at
8683        // caixa-core build time.
8684        //
8685        // Peer of the sibling M3
8686        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
8687        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
8688        // composition axis — same "the validate / shape-gate predicate
8689        // must route through the substrate-primitive typed dispatch"
8690        // discipline extended onto the peer M2 supervisor-slot
8691        // required-`u32` composition axis.
8692        let child = ChildSpec {
8693            caixa: "worker".into(),
8694            versao: "^0.1".into(),
8695            restart: RestartPolicy::Permanent,
8696        };
8697        // Zero-floor arm.
8698        let s = SupervisorSpec {
8699            max_restarts: 0,
8700            children: vec![child.clone()],
8701            ..SupervisorSpec::default()
8702        };
8703        assert_eq!(
8704            s.validate().unwrap_err(),
8705            SupervisorError::ZeroMaxRestarts,
8706            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
8707             — the accessor and the validate gate must route through the \
8708             same substrate-primitive typed dispatch on the zero-floor arm",
8709        );
8710        // Cap arm — the surfaced `max_restarts:` field must byte-equal
8711        // the accessor's return so a future rebrand on the accessor
8712        // lands in the diagnostic without a coordinated rewrite.
8713        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
8714        let s = SupervisorSpec {
8715            max_restarts: over_cap,
8716            children: vec![child.clone()],
8717            ..SupervisorSpec::default()
8718        };
8719        match s.validate().unwrap_err() {
8720            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
8721                assert_eq!(
8722                    max_restarts,
8723                    s.max_restarts(),
8724                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
8725                     SupervisorSpec::max_restarts() — the cap-arm refusal \
8726                     reads through the lifted accessor",
8727                );
8728                assert_eq!(
8729                    max_restarts, over_cap,
8730                    "MaxRestartsExceedsCap.max_restarts must carry the \
8731                     author-declared :supervisor :max-restarts value \
8732                     verbatim (got {max_restarts}, expected {over_cap})",
8733                );
8734            }
8735            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
8736        }
8737        // Lower + upper accept-set boundaries.
8738        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
8739            let s = SupervisorSpec {
8740                max_restarts,
8741                children: vec![child.clone()],
8742                ..SupervisorSpec::default()
8743            };
8744            assert!(
8745                s.validate().is_ok(),
8746                "validate must accept max_restarts == {max_restarts} \
8747                 (an accept-set boundary of \
8748                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
8749            );
8750        }
8751    }
8752
8753    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
8754    //
8755    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
8756    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
8757    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
8758    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
8759    // supervisor-slot per-`:supervisor` restart-intensity-denominator
8760    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
8761    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
8762    // per-`:supervisor` scalar-value axis. The three pins below cover
8763    // (1) the accessor's byte-equal projection against the raw field
8764    // access across every representative value in the `Option<Duration>`
8765    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
8766    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
8767    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
8768    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
8769    // `if let Some(w) = self.restart_window() { … }` bracket-arm
8770    // composition — the validate gate and the accessor must route through
8771    // the same substrate-primitive typed dispatch, so any future silent
8772    // detour that had the accessor perform a bounds-collapsing clamp
8773    // would fail here at caixa-core build time, and (3) the accessor's
8774    // by-copy idempotence pin — the returned `Option<Duration>` must
8775    // outlive `&self` and two successive calls must return byte-equal
8776    // values. Peer of the sibling M2
8777    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
8778    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
8779    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
8780    // (7073d0f) pin on the per-`:politicas :timeout` axis.
8781
8782    #[test]
8783    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
8784        // The canonical per-`:supervisor` restart-intensity-denominator
8785        // scalar pin: [`SupervisorSpec::restart_window`] must return the
8786        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
8787        // `Option<Duration>`, `Copy`-projected from the typed slot's own
8788        // `Option<Duration>` storage, byte-equal to the raw field access
8789        // across every representative value in the accept-set — `None`
8790        // (the "never reset — every restart across the supervisor's
8791        // lifetime counts against the sibling `:max-restarts` budget"
8792        // sentinel the field's own docstring names and the peer
8793        // `validate_accepts_none_restart_window` pin locks in on the
8794        // [`SupervisorSpec::validate`] entry-side),
8795        // `Some(Duration::from_millis(1))` (the structural minimum a
8796        // validated `:restart-window` may carry, the integer-millisecond
8797        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
8798        // everything sub-ms; `Duration::ZERO` is separately rejected by
8799        // [`SupervisorError::RestartWindowZero`]),
8800        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
8801        // surrounding [`SupervisorSpec::validate`] gate carves out on the
8802        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
8803        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
8804        // accessor doesn't perform a silent bounds-collapse into `None` on
8805        // the zero-Duration arm — validate rejects zero but the accessor
8806        // must ship the raw slot verbatim so a validate-time gate
8807        // regression surfaces at the emit boundary rather than being
8808        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
8809        // sentinel that pins the accessor doesn't perform a silent
8810        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
8811        // return path).
8812        //
8813        // Peer of the sibling M2
8814        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
8815        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
8816        // sibling M3
8817        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
8818        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
8819        // substrate-primitive accessor must byte-equal the raw field
8820        // access verbatim across every value in the `Option<Duration>`
8821        // accept-set" discipline extended onto the M2 supervisor-slot
8822        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
8823        // silent detour that re-derived the restart-window from a peer
8824        // axis (an accidental `.max_restarts.into()` collapse that read
8825        // the restart-budget-count as a duration — the two axes serve
8826        // different halves of the `MaxIntensity / Period` restart-
8827        // intensity ratio, and confusing them silently inverts the
8828        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
8829        // "zero means never reset" collapse (the canonical
8830        // `Option<Duration>` → `Duration` collapse footgun the
8831        // [`SupervisorError::RestartWindowZero`] validate arm guards on
8832        // the peer zero-floor axis; a zero period either trips on the
8833        // first failure or never trips depending on operator
8834        // interpretation, neither of which is the author's "never reset"
8835        // intent that `None` expresses structurally), or a per-arm
8836        // variant swap that landed on one consumer without the other.
8837        for restart_window in [
8838            None,
8839            Some(Duration::from_millis(1)),
8840            Some(SUPERVISOR_RESTART_WINDOW_MAX),
8841            Some(Duration::ZERO),
8842            Some(Duration::MAX),
8843        ] {
8844            let s = SupervisorSpec {
8845                restart_window,
8846                ..SupervisorSpec::default()
8847            };
8848            assert_eq!(
8849                s.restart_window(),
8850                restart_window,
8851                "SupervisorSpec::restart_window must return :supervisor \
8852                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
8853                s.restart_window(),
8854            );
8855            assert_eq!(
8856                s.restart_window(),
8857                s.restart_window,
8858                "SupervisorSpec::restart_window accessor and \
8859                 .restart_window field access must byte-equal — the \
8860                 accessor is the substrate-primitive typed dispatch every \
8861                 downstream restart-intensity-denominator consumer must \
8862                 route through",
8863            );
8864        }
8865    }
8866
8867    #[test]
8868    fn validate_restart_window_bracket_arm_routes_through_accessor() {
8869        // Composition pin: [`SupervisorSpec::validate`]'s
8870        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
8871        // zero-floor + integer-millisecond canonical-form + upper-cap
8872        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
8873        // the raw `.restart_window` field access. Structurally: a
8874        // `SupervisorSpec { restart_window: None, .. }` must pass the
8875        // arm gate structurally (the `if let Some(_)` shape returns
8876        // early on the `None` arm — the accessor and the validate gate
8877        // must agree on `None → skip the bracket cascade` so an authored
8878        // `:restart-window ()` structurally routes through the "never
8879        // reset" sentinel path), a `SupervisorSpec { restart_window:
8880        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
8881        // refusal exactly, a `SupervisorSpec { restart_window:
8882        // Some(Duration::from_micros(1500)), .. }` must surface the
8883        // `RestartWindowNotCanonical` refusal exactly (with the offending
8884        // duration carried verbatim from the accessor return), a
8885        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
8886        // + Duration::from_millis(1)), .. }` must surface the
8887        // `RestartWindowExceedsCap` refusal exactly (with the offending
8888        // duration carried verbatim from the accessor return), and a
8889        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
8890        // .. }` (the lower boundary of the accept-set) plus a
8891        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
8892        // .. }` (the upper boundary) must pass validate. The six together
8893        // jointly pin the accessor + validate-gate composition: any future
8894        // silent detour that had the accessor return a fresh `None` on any
8895        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
8896        // collapse) would silently absorb the `RestartWindowZero` refusal
8897        // at the accessor boundary and the validate gate would accept a
8898        // struct-literal `SupervisorSpec { restart_window:
8899        // Some(Duration::ZERO), .. }` — the composition pin catches that
8900        // at caixa-core build time.
8901        //
8902        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
8903        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
8904        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
8905        // accessor-composition pin on the per-`:politicas :timeout` axis —
8906        // same "the validate / shape-gate predicate must route through
8907        // the substrate-primitive typed dispatch" discipline extended
8908        // onto the peer M2 supervisor-slot optional-`Duration` axis.
8909        let child = ChildSpec {
8910            caixa: "worker".into(),
8911            versao: "^0.1".into(),
8912            restart: RestartPolicy::Permanent,
8913        };
8914        // None arm — must not surface any :restart-window-shaped refusal;
8915        // the `if let Some(_)` bracket returns early on `None` structurally.
8916        let s = SupervisorSpec {
8917            restart_window: None,
8918            children: vec![child.clone()],
8919            ..SupervisorSpec::default()
8920        };
8921        assert!(
8922            s.validate().is_ok(),
8923            "validate must accept restart_window: None (the never-reset \
8924             sentinel) — the `if let Some(_)` bracket returns early on \
8925             the None arm and the accessor must agree",
8926        );
8927        // Zero-floor arm.
8928        let s = SupervisorSpec {
8929            restart_window: Some(Duration::ZERO),
8930            children: vec![child.clone()],
8931            ..SupervisorSpec::default()
8932        };
8933        assert_eq!(
8934            s.validate().unwrap_err(),
8935            SupervisorError::RestartWindowZero,
8936            "validate must reject restart_window == Some(Duration::ZERO) \
8937             with RestartWindowZero — the accessor and the validate gate \
8938             must route through the same substrate-primitive typed \
8939             dispatch on the zero-floor arm",
8940        );
8941        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
8942        // byte-equal the accessor's return so a future rebrand on the
8943        // accessor lands in the diagnostic without a coordinated rewrite.
8944        let sub_ms = Duration::from_micros(1500);
8945        let s = SupervisorSpec {
8946            restart_window: Some(sub_ms),
8947            children: vec![child.clone()],
8948            ..SupervisorSpec::default()
8949        };
8950        match s.validate().unwrap_err() {
8951            SupervisorError::RestartWindowNotCanonical { window } => {
8952                assert_eq!(
8953                    Some(window),
8954                    s.restart_window(),
8955                    "RestartWindowNotCanonical.window must byte-equal \
8956                     SupervisorSpec::restart_window().unwrap() — the \
8957                     non-canonical-arm refusal reads through the lifted \
8958                     accessor",
8959                );
8960                assert_eq!(
8961                    window, sub_ms,
8962                    "RestartWindowNotCanonical.window must carry the \
8963                     author-declared :supervisor :restart-window value \
8964                     verbatim (got {window:?}, expected {sub_ms:?})",
8965                );
8966            }
8967            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
8968        }
8969        // Cap arm — the surfaced `window:` field must byte-equal the
8970        // accessor's return.
8971        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
8972        let s = SupervisorSpec {
8973            restart_window: Some(over_cap),
8974            children: vec![child.clone()],
8975            ..SupervisorSpec::default()
8976        };
8977        match s.validate().unwrap_err() {
8978            SupervisorError::RestartWindowExceedsCap { window } => {
8979                assert_eq!(
8980                    Some(window),
8981                    s.restart_window(),
8982                    "RestartWindowExceedsCap.window must byte-equal \
8983                     SupervisorSpec::restart_window().unwrap() — the \
8984                     cap-arm refusal reads through the lifted accessor",
8985                );
8986                assert_eq!(
8987                    window, over_cap,
8988                    "RestartWindowExceedsCap.window must carry the \
8989                     author-declared :supervisor :restart-window value \
8990                     verbatim (got {window:?}, expected {over_cap:?})",
8991                );
8992            }
8993            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
8994        }
8995        // Lower + upper accept-set boundaries.
8996        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
8997            let s = SupervisorSpec {
8998                restart_window: Some(restart_window),
8999                children: vec![child.clone()],
9000                ..SupervisorSpec::default()
9001            };
9002            assert!(
9003                s.validate().is_ok(),
9004                "validate must accept restart_window == Some({restart_window:?}) \
9005                 (an accept-set boundary of \
9006                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
9007            );
9008        }
9009    }
9010
9011    #[test]
9012    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
9013        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
9014        // `Option<Duration>` by copy — `Duration` is `Copy` (so
9015        // `Option<Duration>` is `Copy`) and the accessor must return by
9016        // value, not by reference. Peer of the sibling M2
9017        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
9018        // per-`:limits :wall-clock` axis and the sibling M3
9019        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
9020        // per-`:politicas :timeout` axis, extended onto the peer M2
9021        // supervisor-slot `Option<Duration>` copy-invariant shape — the
9022        // accessor's returned `Option<Duration>` must outlive `&self`
9023        // (multiple calls must return equal values from a dropped-`&self`
9024        // copy, since the returned Option carries no borrow), and calling
9025        // the accessor twice on the same SupervisorSpec must yield the
9026        // same `Option<Duration>` verbatim (idempotent, no side effects
9027        // on `&self`).
9028        //
9029        // Pins against a future silent detour that returned
9030        // `Option<&Duration>` (which would type-check but silently break
9031        // every downstream caller — the future wasm-operator's
9032        // per-supervisor restart-intensity counter consumes `Duration` by
9033        // value and `&Duration` would fold to a detached copy at the call
9034        // site), an accidental `Option::as_ref()` projection
9035        // (`self.restart_window.as_ref()` would also type-check but
9036        // return `Option<&Duration>`), or a one-arm-only accessor that
9037        // reads `Some(*w)` in the Some arm but reads a fresh
9038        // `Default::default()` (which would collapse to `Duration::ZERO`,
9039        // not `None`) in the None arm — a footgun the
9040        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
9041        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
9042        // requires `Period > 0` and `None` structurally expresses "never
9043        // reset" instead.
9044        for restart_window in [
9045            None,
9046            Some(Duration::from_millis(1)),
9047            Some(Duration::from_secs(60)),
9048            Some(SUPERVISOR_RESTART_WINDOW_MAX),
9049        ] {
9050            let s = SupervisorSpec {
9051                restart_window,
9052                ..SupervisorSpec::default()
9053            };
9054            let first = s.restart_window();
9055            let second = s.restart_window();
9056            assert_eq!(
9057                first, second,
9058                "SupervisorSpec::restart_window must be idempotent — two \
9059                 successive calls on the same &self must return the \
9060                 same Option<Duration>",
9061            );
9062            assert_eq!(
9063                first, restart_window,
9064                "SupervisorSpec::restart_window must return :supervisor \
9065                 :restart-window verbatim by copy — got {first:?}, \
9066                 expected {restart_window:?}",
9067            );
9068        }
9069    }
9070
9071    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
9072    //
9073    // The [`SupervisorSpec::children`] accessor lift is the seed of the
9074    // slice-return (`&[T]`) accessor discipline on the substrate — the four
9075    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
9076    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
9077    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
9078    // access at the time of this seed, and inherit this pin family's
9079    // discipline as future compounding runs migrate their consumers. The
9080    // three pins below cover (1) the accessor's byte-equal projection
9081    // against the raw field access across the empty / singleton / cohort
9082    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
9083    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
9084    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
9085    // consumer routing through the accessor on both arms, and (3) the
9086    // per-child validate loop's traversal reading the same slice-view the
9087    // accessor projects. Peer of the sibling M2
9088    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
9089    // two-consumer coherence pin on the per-`:supervisor`
9090    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
9091    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
9092
9093    #[test]
9094    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
9095        // The canonical per-`:supervisor` static-child-list scalar-shape
9096        // pin: [`SupervisorSpec::children`] must return the `:supervisor
9097        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
9098        // slice-view over the same backing buffer the raw
9099        // `self.children.as_slice()` field access borrows from, byte-
9100        // equal across every representative fixture in the accept-set —
9101        // the empty slice (the `SimpleOneForOne`-arm sentinel),
9102        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
9103        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
9104        // with the peer three restart-policy variants in play).
9105        //
9106        // Pins against a future silent detour that returned
9107        // `&Vec<ChildSpec>` (which would type-check but leak the
9108        // storage-side `Vec`'s grow/push/reserve surface no consumer of
9109        // the typed view reaches for), a fresh-allocated
9110        // `Vec<ChildSpec>` copy (which would type-check via a coercion
9111        // but silently break every downstream caller that relied on the
9112        // slice sharing the backing buffer's identity), or an
9113        // out-of-order or length-drifted projection (which would silently
9114        // split the per-child validate loop's traversal input from the
9115        // paired partition-dispatch `.is_empty()` probe's input).
9116        //
9117        // Peer of the sibling
9118        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
9119        // (eafb619) `Copy`-composite-enum byte-equal pin on the
9120        // per-`:supervisor` sibling-restart-strategy axis, extended onto
9121        // the per-`:supervisor` static-child-list `Vec`-carry axis.
9122        let fixtures: Vec<Vec<ChildSpec>> = vec![
9123            Vec::new(),
9124            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
9125            vec![
9126                child("worker", "^0.1", RestartPolicy::Permanent),
9127                child("cache-server", "^0.1", RestartPolicy::Transient),
9128            ],
9129            vec![
9130                child("worker", "^0.1", RestartPolicy::Permanent),
9131                child("cache-server", "^0.1", RestartPolicy::Transient),
9132                child("scratch-job", "^0.1", RestartPolicy::Temporary),
9133            ],
9134        ];
9135        for children in fixtures {
9136            let s = SupervisorSpec {
9137                children: children.clone(),
9138                ..SupervisorSpec::default()
9139            };
9140            assert_eq!(
9141                s.children(),
9142                children.as_slice(),
9143                "SupervisorSpec::children must return :supervisor \
9144                 :children verbatim (got {:?}, expected {:?})",
9145                s.children(),
9146                children.as_slice(),
9147            );
9148            assert_eq!(
9149                s.children(),
9150                s.children.as_slice(),
9151                "SupervisorSpec::children accessor and \
9152                 .children.as_slice() field access must byte-equal — \
9153                 the accessor is the substrate-primitive typed \
9154                 dispatch every downstream static-child-list consumer \
9155                 must route through",
9156            );
9157            assert_eq!(
9158                s.children().len(),
9159                s.children.len(),
9160                "SupervisorSpec::children().len() must byte-equal \
9161                 self.children.len() — a length-drift would silently \
9162                 split the paired partition-dispatch `.is_empty()` \
9163                 probe input from the per-child validate loop's \
9164                 traversal input",
9165            );
9166        }
9167    }
9168
9169    #[test]
9170    fn validate_reads_through_lifted_children_accessor() {
9171        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
9172        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
9173        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
9174        // when the accessor projects a non-empty slice under a
9175        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
9176        // `self.children().is_empty()` refusal probe (which must trip
9177        // [`SupervisorError::NoChildren`] when the accessor projects the
9178        // empty slice under any peer estrategia), and the per-child
9179        // validate loop's `for child in self.children()` traversal
9180        // (which must reach every entry in the same order the accessor
9181        // projects) must all key off the lifted accessor, so any future
9182        // rebrand on the typed slot's reader shape lands at exactly one
9183        // place. Pins the three-site coherence by exercising each
9184        // production consumer end-to-end: (1) the
9185        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
9186        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
9187        // refusal under the empty slice + non-`SimpleOneForOne`
9188        // estrategia across every peer variant, and (3) the per-child
9189        // duplicate-detection surface fires on the second entry of a
9190        // two-child cohort that shares a `:caixa` name (which requires
9191        // the loop to reach both entries — a first-entry-only projection
9192        // would silently pass since the dedup HashSet has room for the
9193        // first insert).
9194        //
9195        // Peer of the sibling M2
9196        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
9197        // two-consumer coherence pin on the per-`:supervisor`
9198        // sibling-restart-strategy axis, extended onto the
9199        // per-`:supervisor` static-child-list `Vec`-carry axis.
9200
9201        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
9202        // `SimpleOneForOne` estrategia must trip
9203        // `SimpleOneForOneWithStaticChildren`.
9204        let s = SupervisorSpec {
9205            estrategia: RestartStrategy::SimpleOneForOne,
9206            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
9207            ..SupervisorSpec::default()
9208        };
9209        assert_eq!(
9210            s.validate().unwrap_err(),
9211            SupervisorError::SimpleOneForOneWithStaticChildren,
9212            "SimpleOneForOne + non-empty children must trip \
9213             SimpleOneForOneWithStaticChildren — the accessor projects \
9214             a non-empty slice, and the SimpleOneForOne-arm refusal \
9215             probe reads through the lifted accessor",
9216        );
9217        assert!(
9218            !s.children().is_empty(),
9219            "the SimpleOneForOne-arm refusal input must be a non-empty \
9220             slice per the accessor's projection",
9221        );
9222
9223        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
9224        // under any peer estrategia must trip `NoChildren`.
9225        for estrategia in [
9226            RestartStrategy::OneForOne,
9227            RestartStrategy::OneForAll,
9228            RestartStrategy::RestForOne,
9229        ] {
9230            let s = SupervisorSpec {
9231                estrategia,
9232                children: Vec::new(),
9233                ..SupervisorSpec::default()
9234            };
9235            match s.validate().unwrap_err() {
9236                SupervisorError::NoChildren { estrategia: e } => {
9237                    assert_eq!(
9238                        e, estrategia,
9239                        "NoChildren.estrategia must carry the author-\
9240                         declared :supervisor :estrategia variant \
9241                         verbatim (got {e:?}, expected {estrategia:?})",
9242                    );
9243                }
9244                other => panic!(
9245                    "expected NoChildren, got {other:?} for \
9246                     estrategia={estrategia:?}"
9247                ),
9248            }
9249            assert!(
9250                s.children().is_empty(),
9251                "the non-SimpleOneForOne-arm refusal input must be the \
9252                 empty slice per the accessor's projection",
9253            );
9254        }
9255
9256        // (3) Per-child validate loop: a two-child cohort that shares a
9257        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
9258        // reach both entries through the accessor.
9259        let s = SupervisorSpec {
9260            estrategia: RestartStrategy::OneForOne,
9261            children: vec![
9262                child("worker", "^0.1", RestartPolicy::Permanent),
9263                child("worker", "^0.2", RestartPolicy::Transient),
9264            ],
9265            ..SupervisorSpec::default()
9266        };
9267        match s.validate().unwrap_err() {
9268            SupervisorError::DuplicateChildCaixa { caixa } => {
9269                assert_eq!(
9270                    caixa, "worker",
9271                    "DuplicateChildCaixa.caixa must carry the shared \
9272                     child `:caixa` name verbatim",
9273                );
9274            }
9275            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
9276        }
9277        assert_eq!(
9278            s.children().len(),
9279            2,
9280            "the per-child validate loop's traversal input must be a \
9281             two-element slice per the accessor's projection",
9282        );
9283    }
9284
9285    // Shared helper for the M2 per-`:children` per-slot-gate ≡
9286    // `validate` equivalence pins: builds an `OneForOne`-estrategia
9287    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
9288    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
9289    // bracket all pass cleanly so the sole failing surface is the
9290    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
9291    // pins the two-altitude equivalence on the paired probe.
9292    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
9293        let s = SupervisorSpec {
9294            estrategia: RestartStrategy::OneForOne,
9295            children,
9296            ..SupervisorSpec::default()
9297        };
9298        let via_gate = s.validate_children().unwrap_err();
9299        let via_validate = s.validate().unwrap_err();
9300        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
9301        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
9302        assert_eq!(
9303            via_gate, via_validate,
9304            "per-slot gate ≡ validate() must discriminate the same \
9305             refusal shape",
9306        );
9307    }
9308
9309    #[test]
9310    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
9311        // Fail-before-pass-after equivalence pin on the M2
9312        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
9313        // convergence — sibling of the M3 mesh-slot
9314        // `validate_membros_*` / `validate_contratos_*` /
9315        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
9316        // peer per-entry axes. Sweeps four of the five refusal shapes
9317        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
9318        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
9319        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
9320        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
9321        // duplicate-`:caixa` fan-out. Companion pin
9322        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
9323        // covers `ChildVersaoInvalid` (whose parser-owned reason string
9324        // needs pattern-matching, not equality) and the clean-pass
9325        // canonical fixture; together the two pins guarantee the
9326        // per-slot gate and `validate` discriminate the same set on
9327        // every per-child-covered input.
9328        assert_validate_children_matches_gate(
9329            vec![child("", "^0.1", RestartPolicy::Permanent)],
9330            &SupervisorError::EmptyChildName,
9331        );
9332        assert_validate_children_matches_gate(
9333            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
9334            &SupervisorError::ChildCaixaInvalid {
9335                caixa: "Worker".into(),
9336                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
9337            },
9338        );
9339        assert_validate_children_matches_gate(
9340            vec![child("worker", "", RestartPolicy::Permanent)],
9341            &SupervisorError::EmptyChildVersion {
9342                caixa: "worker".into(),
9343            },
9344        );
9345        assert_validate_children_matches_gate(
9346            vec![
9347                child("worker", "^0.1", RestartPolicy::Permanent),
9348                child("worker", "^0.2", RestartPolicy::Transient),
9349            ],
9350            &SupervisorError::DuplicateChildCaixa {
9351                caixa: "worker".into(),
9352            },
9353        );
9354    }
9355
9356    #[test]
9357    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
9358        // Second half of the two-altitude equivalence pin — covers the
9359        // one refusal shape whose reason string is parser-owned
9360        // (`ChildVersaoInvalid`, whose reason comes from the shared
9361        // [`crate::version::parse_requirement`] impl and may drift) and
9362        // the clean-pass canonical fixture. Sibling pin
9363        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
9364        // covers the four equality-comparable refusal shapes.
9365        let s_bad_versao = SupervisorSpec {
9366            estrategia: RestartStrategy::OneForOne,
9367            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
9368            ..SupervisorSpec::default()
9369        };
9370        let via_gate = s_bad_versao.validate_children().unwrap_err();
9371        let via_validate = s_bad_versao.validate().unwrap_err();
9372        match (&via_gate, &via_validate) {
9373            (
9374                SupervisorError::ChildVersaoInvalid {
9375                    caixa: cg,
9376                    versao: vg,
9377                    ..
9378                },
9379                SupervisorError::ChildVersaoInvalid {
9380                    caixa: cv,
9381                    versao: vv,
9382                    ..
9383                },
9384            ) => {
9385                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
9386                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
9387                assert_eq!(cv, "worker", "validate() :caixa carrier");
9388                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
9389            }
9390            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
9391        }
9392        assert_eq!(
9393            via_gate, via_validate,
9394            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
9395        );
9396
9397        let s_ok = SupervisorSpec {
9398            estrategia: RestartStrategy::OneForOne,
9399            children: vec![
9400                child("worker-a", "^0.1", RestartPolicy::Permanent),
9401                child("worker-b", "~0.2.3", RestartPolicy::Transient),
9402                child("collector", "*", RestartPolicy::Temporary),
9403            ],
9404            ..SupervisorSpec::default()
9405        };
9406        s_ok.validate_children()
9407            .expect("per-slot gate must accept the clean-pass fixture");
9408        s_ok.validate()
9409            .expect("validate() must accept the clean-pass fixture");
9410    }
9411
9412    #[test]
9413    fn validate_children_is_self_contained_on_children_slot() {
9414        // Self-containment pin: [`SupervisorSpec::validate_children`]
9415        // resolves the per-child cascade against `&self` alone, without
9416        // depending on the peer `:estrategia`/`:max-restarts`/
9417        // `:restart-window` gates having run first — same posture the M3
9418        // peer per-slot gates carry (`validate_membros`,
9419        // `validate_contratos`, `validate_entrada`, `validate_placement`,
9420        // routing through their own oracles rather than borrowing state
9421        // threaded down from `validate`). A future consumer that reaches
9422        // the per-slot gate directly on a spec whose peer slots would
9423        // fail `validate` still surfaces the per-child refusal, not the
9424        // peer refusal.
9425        //
9426        // Construct a spec whose `:max-restarts` is `0` (which would
9427        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
9428        // the partition-dispatch) and whose `:children` carries a
9429        // `DuplicateChildCaixa` shape: the per-slot gate called directly
9430        // must surface `DuplicateChildCaixa`, proving it does not depend
9431        // on the peer `:max-restarts` gate running first.
9432        let s = SupervisorSpec {
9433            estrategia: RestartStrategy::OneForOne,
9434            max_restarts: 0,
9435            restart_window: Some(Duration::from_secs(60)),
9436            children: vec![
9437                child("worker", "^0.1", RestartPolicy::Permanent),
9438                child("worker", "^0.2", RestartPolicy::Transient),
9439            ],
9440        };
9441        assert_eq!(
9442            s.validate_children().unwrap_err(),
9443            SupervisorError::DuplicateChildCaixa {
9444                caixa: "worker".into(),
9445            },
9446            "per-slot gate must resolve per-child refusal directly against \
9447             `&self` — a dependency on the peer `:max-restarts` gate \
9448             running first would surface ZeroMaxRestarts here instead",
9449        );
9450        // The peer gate is still the surface `validate` reaches — pin
9451        // the ordering to establish that `validate_children` truly runs
9452        // last in `validate`'s dispatch, so a direct call bypasses the
9453        // peer gates on any spec whose per-child cascade would fail.
9454        assert_eq!(
9455            s.validate().unwrap_err(),
9456            SupervisorError::ZeroMaxRestarts,
9457            "validate() must surface the peer `:max-restarts` gate before \
9458             reaching the per-child cascade — this pins the dispatch \
9459             ordering the per-slot gate's self-containment complements",
9460        );
9461    }
9462
9463    #[test]
9464    fn child_spec_restart_accessor_is_const_fn() {
9465        // The [`ChildSpec::restart`] per-`:children` restart-decision-
9466        // policy `Copy`-return scalar accessor is declared
9467        // `#[must_use] pub const fn` — matching the sibling M2
9468        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
9469        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
9470        // both converted in this commit), the sibling M2
9471        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
9472        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
9473        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
9474        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
9475        // `Copy`-return `pub const fn` scalar accessors on the sibling
9476        // M3 surface. Pin the `const`-eval posture here so a future
9477        // accidental downgrade to non-`const` (an added runtime helper
9478        // reachable only from a non-`const` context, an
9479        // `Option<RestartPolicy>`-shape migration on the per-child
9480        // restart-decision axis once heterogeneous per-cluster
9481        // restart-policy overlays land that would silently drop the
9482        // `const` qualifier, a manual hand-rolled shadow) trips at
9483        // caixa-core build time rather than surfacing as a downstream
9484        // `const`-context regression far from the declaration.
9485        //
9486        // Same shape as the sibling M3
9487        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
9488        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
9489        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
9490        // accessor axis — the load-bearing witness lives in the
9491        // module-scope `const fn` wrapper `restart_via_const_fn` below:
9492        // a body that calls [`ChildSpec::restart`] under a `const fn`
9493        // signature is well-formed only when the callee is itself
9494        // `const fn`, so any future accidental downgrade of
9495        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
9496        // build time (const-eval E0015 `cannot call non-const method`),
9497        // strictly stronger than a runtime `assert!(CONST)` and
9498        // side-stepping the destructor-in-const restriction that
9499        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
9500        // items on `ChildSpec`'s `String` carriers.
9501        //
9502        // The runtime body sweeps every closed-set [`RestartPolicy`]
9503        // arm and asserts the wrapped and direct dispatches agree.
9504        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
9505            c.restart()
9506        }
9507        for restart in [
9508            RestartPolicy::Permanent,
9509            RestartPolicy::Transient,
9510            RestartPolicy::Temporary,
9511        ] {
9512            let c = ChildSpec {
9513                caixa: "worker".into(),
9514                versao: "^0.1".into(),
9515                restart,
9516            };
9517            assert_eq!(
9518                restart_via_const_fn(&c),
9519                c.restart(),
9520                "const-fn-wrapped and direct dispatch on \
9521                 ChildSpec::restart must agree for {restart:?}",
9522            );
9523            assert_eq!(
9524                c.restart(),
9525                restart,
9526                "ChildSpec::restart must return the storage-side \
9527                 RestartPolicy verbatim for {restart:?} (a violation \
9528                 means the accessor stopped being a raw field-return \
9529                 copy)",
9530            );
9531        }
9532    }
9533
9534    #[test]
9535    fn supervisor_spec_estrategia_accessor_is_const_fn() {
9536        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
9537        // sibling-restart-strategy `Copy`-return scalar accessor is
9538        // declared `#[must_use] pub const fn` — matching the sibling M2
9539        // per-`:children` [`ChildSpec::restart`] (pinned by
9540        // [`child_spec_restart_accessor_is_const_fn`] above, both
9541        // converted in this commit), the sibling M2 per-`:supervisor`
9542        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
9543        // accessor already `pub const fn`, and mirroring the peer M3
9544        // mesh-slot per-`:placement`
9545        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
9546        // `pub const fn` scalar accessor whose method-name discipline
9547        // the [`SupervisorSpec::estrategia`] method was authored to
9548        // match. Pin the `const`-eval posture here so a future
9549        // accidental downgrade to non-`const` (an added runtime helper
9550        // reachable only from a non-`const` context, an
9551        // `Option<RestartStrategy>`-shape migration once the substrate
9552        // grows per-cluster strategy overlays that would silently drop
9553        // the `const` qualifier, a manual hand-rolled shadow) trips at
9554        // caixa-core build time rather than surfacing as a downstream
9555        // `const`-context regression far from the declaration.
9556        //
9557        // Same shape as the sibling
9558        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
9559        // load-bearing witness lives in the module-scope `const fn`
9560        // wrapper `estrategia_via_const_fn` below: a body that calls
9561        // [`SupervisorSpec::estrategia`] under a `const fn` signature
9562        // is well-formed only when the callee is itself `const fn`,
9563        // side-stepping the destructor-in-const restriction that would
9564        // otherwise block a direct
9565        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
9566        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
9567        // carriers.
9568        //
9569        // The runtime body sweeps every closed-set [`RestartStrategy`]
9570        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
9571        // direct dispatches agree.
9572        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
9573            s.estrategia()
9574        }
9575        for &estrategia in RestartStrategy::ALL {
9576            let s = SupervisorSpec {
9577                estrategia,
9578                max_restarts: 5,
9579                restart_window: Some(Duration::from_secs(60)),
9580                children: Vec::new(),
9581            };
9582            assert_eq!(
9583                estrategia_via_const_fn(&s),
9584                s.estrategia(),
9585                "const-fn-wrapped and direct dispatch on \
9586                 SupervisorSpec::estrategia must agree for {estrategia:?}",
9587            );
9588            assert_eq!(
9589                s.estrategia(),
9590                estrategia,
9591                "SupervisorSpec::estrategia must return the storage-side \
9592                 RestartStrategy verbatim for {estrategia:?} (a violation \
9593                 means the accessor stopped being a raw field-return \
9594                 copy)",
9595            );
9596        }
9597    }
9598
9599    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
9600    // macro definition (see the paired doc-block above the macro
9601    // definition) — every generated `<ctor>(caixa: &str) -> Self`
9602    // constructor folds the uniform `Self::<Variant> { caixa:
9603    // caixa.to_string() }` one-field struct-literal onto one substrate
9604    // primitive. The three per-variant equivalence pins below
9605    // (fail-before-pass-after by construction — a byte-mismatched macro
9606    // arm would trip its equivalence pin first) lock each generated
9607    // constructor to its struct-literal peer under `PartialEq`, so
9608    // every wire-up in [`SupervisorSpec::validate_children`] and
9609    // [`validate_no_self_supervision`] on that variant produces a
9610    // byte-equal `SupervisorError` to the pre-lift open-coded
9611    // struct-literal. The cross-axis pin that follows (non-default
9612    // caixa name) routes the sole constructor input axis through
9613    // `.to_string()`, so the fold does not silently collapse onto a
9614    // fixed name.
9615    //
9616    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
9617    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
9618    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
9619    // `missing_entry_ctor_matches_struct_literal_wrap` /
9620    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
9621    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
9622    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
9623    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
9624    // on the six sibling ctor families the recent trajectory closed
9625    // on the peer `LayoutError` / `AplicacaoError` envelopes.
9626
9627    #[test]
9628    fn empty_child_version_ctor_matches_struct_literal_wrap() {
9629        assert_eq!(
9630            SupervisorError::empty_child_version("worker"),
9631            SupervisorError::EmptyChildVersion {
9632                caixa: "worker".to_string(),
9633            },
9634            "generated empty_child_version ctor must produce byte-equal \
9635             SupervisorError to the open-coded struct-literal wrap on the \
9636             same &str fixture",
9637        );
9638    }
9639
9640    #[test]
9641    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
9642        assert_eq!(
9643            SupervisorError::duplicate_child_caixa("worker"),
9644            SupervisorError::DuplicateChildCaixa {
9645                caixa: "worker".to_string(),
9646            },
9647            "generated duplicate_child_caixa ctor must produce byte-equal \
9648             SupervisorError to the open-coded struct-literal wrap on the \
9649             same &str fixture",
9650        );
9651    }
9652
9653    #[test]
9654    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
9655        assert_eq!(
9656            SupervisorError::child_supervises_self("orquestra"),
9657            SupervisorError::ChildSupervisesSelf {
9658                caixa: "orquestra".to_string(),
9659            },
9660            "generated child_supervises_self ctor must produce byte-equal \
9661             SupervisorError to the open-coded struct-literal wrap on the \
9662             same &str fixture",
9663        );
9664    }
9665
9666    // Per-variant equivalence pins for the two lifted
9667    // [`SupervisorError::child_caixa_invalid`] /
9668    // [`SupervisorError::child_versao_invalid`] inherent constructors
9669    // (fail-before-pass-after by construction — a byte-mismatched ctor body
9670    // would trip its equivalence pin first). Each pins the ctor output to
9671    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
9672    // in [`SupervisorSpec::validate_children`] on the two variants
9673    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
9674    // struct-literal on the same scalar fixtures. Peers of the sibling
9675    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
9676    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
9677    // the peer `AplicacaoError` envelope's
9678    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
9679
9680    #[test]
9681    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
9682        let caixa = "Worker";
9683        let reason = "sample reason text";
9684        assert_eq!(
9685            SupervisorError::child_caixa_invalid(caixa, reason),
9686            SupervisorError::ChildCaixaInvalid {
9687                caixa: caixa.to_string(),
9688                reason: reason.to_string(),
9689            },
9690            "lifted child_caixa_invalid ctor must produce byte-equal \
9691             SupervisorError to the open-coded struct-literal wrap on the \
9692             same (&str, reason) fixture",
9693        );
9694    }
9695
9696    #[test]
9697    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
9698        let caixa = "worker";
9699        let versao = "not-a-req";
9700        let reason = "sample reason text";
9701        assert_eq!(
9702            SupervisorError::child_versao_invalid(caixa, versao, reason),
9703            SupervisorError::ChildVersaoInvalid {
9704                caixa: caixa.to_string(),
9705                versao: versao.to_string(),
9706                reason: reason.to_string(),
9707            },
9708            "lifted child_versao_invalid ctor must produce byte-equal \
9709             SupervisorError to the open-coded struct-literal wrap on the \
9710             same (&str, &str, reason) fixture",
9711        );
9712    }
9713
9714    #[test]
9715    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
9716        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
9717        // against a `&str`-literal vs. `format!(…)` reason input to pin
9718        // both constructors accept the `impl Into<String>` bound
9719        // uniformly, so neither wire-up site drifts under a per-arm
9720        // wrapper transformation on the caller-side `reason` axis. Peer
9721        // of the sibling
9722        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
9723        // sweep on the peer `AplicacaoError` envelope.
9724        let via_literal = "literal reason text";
9725        let via_format = format!("{} reason text", "literal");
9726        assert_eq!(
9727            SupervisorError::child_caixa_invalid("Worker", via_literal),
9728            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
9729        );
9730        assert_eq!(
9731            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
9732            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
9733        );
9734    }
9735
9736    #[test]
9737    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
9738        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
9739        // &str`) through a non-default fixture name against every
9740        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
9741        // so any wrapper-side lowercase / trim / truncate / re-order on
9742        // the `caixa.to_string()` sole-field construction surfaces
9743        // here rather than at a downstream diagnostic-shape mismatch.
9744        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
9745        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
9746        // through_to_string` / `contrato_target_ctors_route_edge_
9747        // triple_through_verbatim` / `contrato_empty_pair_ctors_
9748        // route_edge_pair_through_verbatim` cross-axis routing pins on
9749        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
9750        // here onto the `SupervisorError` `{ caixa: String }` envelope
9751        // so every substrate-primitive ctor family in caixa-core
9752        // guarantees the sole-field construction routes the caller's
9753        // `&str` through `.to_string()` verbatim.
9754        let name = "cache-v2";
9755        assert_eq!(
9756            SupervisorError::empty_child_version(name),
9757            SupervisorError::EmptyChildVersion {
9758                caixa: name.to_string(),
9759            },
9760        );
9761        assert_eq!(
9762            SupervisorError::duplicate_child_caixa(name),
9763            SupervisorError::DuplicateChildCaixa {
9764                caixa: name.to_string(),
9765            },
9766        );
9767        assert_eq!(
9768            SupervisorError::child_supervises_self(name),
9769            SupervisorError::ChildSupervisesSelf {
9770                caixa: name.to_string(),
9771            },
9772        );
9773    }
9774
9775    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
9776    //
9777    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
9778    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
9779    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
9780    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
9781    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
9782    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
9783    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
9784    // / silent constant-substitution on any one variant surfaces here rather
9785    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
9786    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
9787    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
9788    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
9789    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
9790    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
9791    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
9792    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
9793    #[test]
9794    fn no_children_ctor_matches_struct_literal_wrap() {
9795        let estrategia = RestartStrategy::OneForAll;
9796        assert_eq!(
9797            SupervisorError::no_children(estrategia),
9798            SupervisorError::NoChildren { estrategia },
9799            "generated no_children ctor must produce byte-equal \
9800             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
9801             on the same `Copy`-`RestartStrategy` fixture",
9802        );
9803    }
9804
9805    #[test]
9806    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
9807        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
9808        assert_eq!(
9809            SupervisorError::max_restarts_exceeds_cap(max_restarts),
9810            SupervisorError::MaxRestartsExceedsCap { max_restarts },
9811            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
9812             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
9813             struct-literal wrap on the same `Copy`-`u32` fixture",
9814        );
9815    }
9816
9817    #[test]
9818    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
9819        let window = Duration::from_micros(1_500);
9820        assert_eq!(
9821            SupervisorError::restart_window_not_canonical(window),
9822            SupervisorError::RestartWindowNotCanonical { window },
9823            "generated restart_window_not_canonical ctor must produce \
9824             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
9825             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
9826        );
9827    }
9828
9829    #[test]
9830    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
9831        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
9832        assert_eq!(
9833            SupervisorError::restart_window_exceeds_cap(window),
9834            SupervisorError::RestartWindowExceedsCap { window },
9835            "generated restart_window_exceeds_cap ctor must produce \
9836             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
9837             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
9838        );
9839    }
9840
9841    #[test]
9842    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
9843        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
9844        // constructor input axis through a non-default `Copy` fixture against
9845        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
9846        // side silent `.into()` / silent constant-substitution / silent field
9847        // re-name away from the canonical `estrategia | max_restarts | window`
9848        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
9849        // axis silently rerouted through some other `Copy` coercion, surfaces
9850        // here rather than at a downstream per-`:supervisor` diagnostic-shape
9851        // drift. Peer of the sibling
9852        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
9853        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
9854        // envelope's per-`:politicas` per-axis ctor family, extended here onto
9855        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
9856        // variant family folded onto a substrate primitive.
9857        //
9858        // Fixtures picked out of each variant's accept-set boundary rather
9859        // than the default value so a silent constant-substitution to a per-
9860        // variant sentinel surfaces here on the structural-equality assertion.
9861        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
9862        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
9863        // isn't the `SimpleOneForOne` arm the sibling
9864        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
9865        // `max_restarts` fixture picks an above-cap magnitude the cap arm
9866        // rejects; the two `Duration` fixtures pick the sub-millisecond and
9867        // above-cap ends of the `:restart-window` canonical-form + cap
9868        // bracket respectively.
9869        let estrategia = RestartStrategy::RestForOne;
9870        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
9871        let sub_ms = Duration::from_micros(1_500);
9872        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
9873        assert_eq!(
9874            SupervisorError::no_children(estrategia),
9875            SupervisorError::NoChildren { estrategia },
9876        );
9877        assert_eq!(
9878            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
9879            SupervisorError::MaxRestartsExceedsCap {
9880                max_restarts: above_cap_restarts,
9881            },
9882        );
9883        assert_eq!(
9884            SupervisorError::restart_window_not_canonical(sub_ms),
9885            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
9886        );
9887        assert_eq!(
9888            SupervisorError::restart_window_exceeds_cap(above_hour),
9889            SupervisorError::RestartWindowExceedsCap { window: above_hour },
9890        );
9891    }
9892
9893    #[test]
9894    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
9895        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
9896        // generated ctor `const fn` so a caller can pin a `SupervisorError`
9897        // at compile time — the same zero-runtime-work property the pre-lift
9898        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
9899        // its `Copy`-pass-through construction path (no `.to_string()` /
9900        // `.into()` allocation, no branching). If any future edit silently
9901        // drops the `const` qualifier from the macro body the per-arm `const`
9902        // bindings below fail to compile, which surfaces the regression at
9903        // the substrate-primitive definition rather than at some downstream
9904        // consumer that had come to rely on the `const`-constructibility.
9905        // Peer of the sibling
9906        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
9907        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
9908        // per-`:politicas` per-axis ctor family.
9909        const NO_CHILDREN: SupervisorError =
9910            SupervisorError::no_children(RestartStrategy::OneForAll);
9911        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
9912        const WINDOW_NC: SupervisorError =
9913            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
9914        const WINDOW_CAP: SupervisorError =
9915            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
9916        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
9917        assert!(matches!(
9918            MAX_RESTARTS_CAP,
9919            SupervisorError::MaxRestartsExceedsCap { .. }
9920        ));
9921        assert!(matches!(
9922            WINDOW_NC,
9923            SupervisorError::RestartWindowNotCanonical { .. }
9924        ));
9925        assert!(matches!(
9926            WINDOW_CAP,
9927            SupervisorError::RestartWindowExceedsCap { .. }
9928        ));
9929    }
9930}