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// Fleet-wide dispatcher-catalog registrations for caixa's OTP
962// supervisor surface — two more typed shadows over Erlang/OTP
963// primitives the substrate now mechanically tracks (see
964// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
965// theory/TYPED-ABSORPTION.md for the absorption arc).
966gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
967gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
968
969/// One child entry in the supervisor's `:children` list.
970///
971/// Every child references another caixa by `:caixa <nome>` + version
972/// constraint. The supervisor materializes one ComputeUnit per entry.
973#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
974#[serde(rename_all = "camelCase")]
975pub struct ChildSpec {
976    /// The child caixa's `:nome`. Must resolve via the same dependency
977    /// resolution path as `:deps` (caixa-resolver).
978    pub caixa: String,
979
980    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
981    /// [`crate::dep::Dep::versao`].
982    pub versao: String,
983
984    /// Restart policy — an author-omitted slot degrades onto the
985    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
986    /// (`permanent`, the Erlang/OTP worker-child default) through the
987    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
988    /// to.
989    #[serde(default)]
990    pub restart: RestartPolicy,
991}
992
993impl ChildSpec {
994    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
995    /// accessor every consumer that reads the OTP-shape supervised
996    /// child's identity keys off — returns the author-declared
997    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
998    /// from the typed slot's own [`String`] storage.
999    ///
1000    /// The `:children :caixa` slot carries the DNS-1123 label — the
1001    /// child caixa's `:nome` — that every emitted cluster artifact
1002    /// derives its `metadata.name` from verbatim: the rendered
1003    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
1004    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
1005    /// identity, and the per-child K8s Service `metadata.name` the
1006    /// future wasm-operator (M3) provisions for inter-child supervision-
1007    /// tree wiring. Every downstream consumer that fans on the child's
1008    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
1009    /// per-child DNS-1123 gate at
1010    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
1011    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
1012    /// [`validate_no_self_supervision`] cross-slot equality check
1013    /// against the parent's `:nome`, every `SupervisorError` variant
1014    /// carrying the offending child caixa verbatim for `feira lint`
1015    /// rendering, the future wasm-operator's hierarchical reconciliation
1016    /// scheduler's per-child ComputeUnit-name projection, the future M4
1017    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1018    /// admission webhook).
1019    ///
1020    /// Prior to this lift the `.caixa` byte-string was accessed inline
1021    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
1022    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
1023    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
1024    /// carriers' `child.caixa.clone()`, the dedup key's
1025    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
1026    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
1027    /// field-accesses that expressed no compile-time link back to the
1028    /// typed slot. A future extension of the `:children :caixa` axis to
1029    /// a richer author surface (a per-cluster alias table the operator
1030    /// pins through a future `:placement`-scoped slot on the supervisor
1031    /// tree, a namespace-qualified rewrite the M4 CR materializer
1032    /// applies per-CR, a per-child overlay from the future `:children
1033    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1034    /// acknowledges) would have had to be threaded through every
1035    /// open-coded copy in lockstep or one consumer would silently
1036    /// disagree with the peers on which caixa a given child resolves to
1037    /// — a child-set lookup that treated the name as `"cart-worker"`
1038    /// while the peer duplicate-detector treated it as
1039    /// `"tenant-a/cart-worker"` would silently split the
1040    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
1041    /// self-supervision detector's parent-equality check, a two-consumer
1042    /// split at the validator far from the source `caixa.lisp` with no
1043    /// field naming the identity-drift root cause. Lifting the resolution
1044    /// rule to a typed method on the substrate primitive means every
1045    /// downstream consumer of the Supervisor's per-`:children` identity
1046    /// surface reaches for exactly one typed dispatch — the resolver's
1047    /// accept-set migrates as a unit on any future axis addition.
1048    ///
1049    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
1050    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
1051    /// mesh-slot surface — same "one typed dispatch on the substrate
1052    /// primitive, thin projections at each consumer" discipline extended
1053    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
1054    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
1055    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
1056    /// accessor discipline for the shared substrate concept "another
1057    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
1058    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
1059    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
1060    /// slot family's typed-accessor discipline now spans both the
1061    /// upgrade axis (`:upgrade-from`) and the supervision axis
1062    /// (`:children`), matching the closed M3 mesh-slot accessor family's
1063    /// shape. Named `nome()` to match the tatara-lisp author-surface
1064    /// term the field's docstring already reaches for ("The child
1065    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
1066    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
1067    /// discipline the substrate already carries — the accessor's name
1068    /// maps directly onto the canonical caixa-identity vocabulary rather
1069    /// than shadowing the field's storage-side `caixa` label.
1070    #[must_use]
1071    pub const fn nome(&self) -> &str {
1072        self.caixa.as_str()
1073    }
1074
1075    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
1076    /// requirement scalar accessor every consumer that reads the OTP-shape
1077    /// supervised child's version pin keys off — returns the author-declared
1078    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
1079    /// the typed slot's own [`String`] storage.
1080    ///
1081    /// The `:children :versao` slot carries the Cargo-shaped semver
1082    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
1083    /// which release of the supervised child caixa the OTP-shape supervisor
1084    /// tree materializes against — the same requirement grammar the peer
1085    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
1086    /// shared [`crate::render::require_valid_versao_requirement`] cascade
1087    /// and the shared [`crate::version::parse_requirement`] parser. Every
1088    /// downstream consumer that fans on the child's version pin keys off
1089    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
1090    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
1091    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
1092    /// for `feira lint` rendering, every future per-cluster version-lock
1093    /// overlay the caixa-operator's hierarchical reconciliation scheduler
1094    /// pins through a future `:placement`-scoped supervisor-tree slot, the
1095    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1096    /// per-child version resolver, the future wasm-operator's per-child
1097    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
1098    ///
1099    /// Prior to this lift the `.versao` byte-string was accessed inline at
1100    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
1101    /// [`SupervisorSpec::validate`] requirement-gate call
1102    /// `require_valid_versao_requirement(&child.versao, …)` and the
1103    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
1104    /// `versao: child.versao.clone()` — two open-coded field-accesses that
1105    /// expressed no compile-time link back to the typed slot. A future
1106    /// extension of the `:children :versao` axis to a richer author surface
1107    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1108    /// flow, a lacre-projected concrete-version rewrite the operator
1109    /// materializes at CR-admission time, a future `:children :versao-lock`
1110    /// per-cluster override slot the wasm-operator's hierarchical
1111    /// reconciliation scheduler authors per-CR) would have had to be
1112    /// threaded through both open-coded copies in lockstep or one consumer
1113    /// would silently disagree with the peer on which release constraint a
1114    /// given child resolves to — the requirement-gate call reading
1115    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
1116    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
1117    /// the actual gate rejection input, a two-consumer split at the
1118    /// validator far from the source `caixa.lisp` with no field naming the
1119    /// version-pin drift root cause. Lifting the resolution rule to a typed
1120    /// method on the substrate primitive means every downstream
1121    /// requirement-facing consumer of the Supervisor's per-`:children`
1122    /// version-pin surface reaches for exactly one typed dispatch — the
1123    /// resolver's accept-set migrates as a unit on any future axis addition.
1124    ///
1125    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
1126    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
1127    /// surface — same "one typed dispatch on the substrate primitive, thin
1128    /// projections at each consumer" discipline extended onto the M2
1129    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
1130    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
1131    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
1132    /// one accessor discipline for the shared substrate concept "another
1133    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
1134    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
1135    /// `:nome` scalar accessor — the pair
1136    /// `(nome(), versao_requirement())` jointly projects the
1137    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
1138    /// that fans on per-child identity + version pin keys off, closing the
1139    /// last unlifted per-`:children` `String`-carry axis so every downstream
1140    /// per-`:children` reader now routes through a typed dispatch on the
1141    /// substrate primitive. Named `versao_requirement()` rather than
1142    /// `versao()` because the field's storage-side `.versao` label is
1143    /// already the author-surface term (`:versao`); the accessor's name
1144    /// carries the semantic role — the semver *requirement* string the
1145    /// shared [`crate::version::parse_requirement`] entry-point consumes —
1146    /// so a raw field access and a typed dispatch read differently at every
1147    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
1148    /// naming discipline verbatim.
1149    #[must_use]
1150    pub const fn versao_requirement(&self) -> &str {
1151        self.versao.as_str()
1152    }
1153
1154    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
1155    /// per-child post-exit restart-decision policy scalar accessor every
1156    /// consumer that dispatches on the supervised child's post-exit
1157    /// reconcile posture keys off — returns the author-declared
1158    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
1159    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
1160    /// storage.
1161    ///
1162    /// The `:children :restart` slot carries the closed-set OTP-shaped
1163    /// per-child restart-decision policy discriminator
1164    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
1165    /// worker-child default; [`RestartPolicy::Transient`] — restart only
1166    /// on abnormal exit, the OTP `transient` clean-completion-aware
1167    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
1168    /// `temporary` one-shot default) that every downstream consumer of
1169    /// the Supervisor's per-child post-exit reconcile branch keys off.
1170    /// Every future downstream consumer that fans on the per-child
1171    /// restart-decision keys off this scalar (the future `feira app
1172    /// graph` per-child restart column, the future wasm-operator's
1173    /// per-child post-exit restart-decision branch, the future M4
1174    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1175    /// admission webhook, the `caixa-operator`'s hierarchical
1176    /// reconciliation scheduler's per-child post-exit reconcile branch,
1177    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
1178    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1179    /// pin threads through).
1180    ///
1181    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
1182    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
1183    /// scalar accessor and the M3 mesh-slot
1184    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
1185    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
1186    /// — same "one typed dispatch on the substrate primitive,
1187    /// `Copy`-projected closed-set enum-arm discriminator that partitions
1188    /// the downstream renderer's per-arm fan-out" discipline extended
1189    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
1190    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
1191    /// [`ChildSpec`] type — companion to the sibling per-`:children`
1192    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
1193    /// and the per-`:children` [`ChildSpec::versao_requirement`]
1194    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
1195    /// on the sibling `String`-carry axes. The triple
1196    /// `(nome(), versao_requirement(), restart())` jointly projects the
1197    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
1198    /// tree consumer that fans on per-child identity + version pin +
1199    /// restart-decision keys off, closing the last unlifted per-`:children`
1200    /// axis so every downstream per-`:children` reader now routes through
1201    /// a typed dispatch on the substrate primitive. Named `restart()` to
1202    /// match the storage field's name and the author-surface
1203    /// `:children :restart` slot term verbatim; the accessor's identity
1204    /// name maps onto the canonical OTP-shape per-child restart-decision-
1205    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
1206    /// carries.
1207    ///
1208    /// Declared `pub const fn` to close the last non-`const`
1209    /// `Copy`-return raw-field-getter posture on the M2
1210    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
1211    /// of the sibling M2 per-`:supervisor`
1212    /// [`SupervisorSpec::estrategia`] (converted in this commit)
1213    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
1214    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1215    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
1216    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
1217    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
1218    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
1219    /// downstream substrate-side `const`-context consumer of the
1220    /// per-`:children` restart-decision-policy scalar (a future
1221    /// module-scope `const _:() = assert!(matches!(child.restart(),
1222    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
1223    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1224    /// admission-webhook `const fn` per-child restart-decision floor
1225    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
1226    /// composer over the substrate primitive that fans on the per-child
1227    /// restart-decision policy at compile time) now reaches through the
1228    /// same typed dispatch on the substrate primitive at const-eval
1229    /// time as at runtime. A future non-`Copy`-return promotion of the
1230    /// scalar (an `Option<RestartPolicy>`-shape migration on the
1231    /// per-child restart-decision axis once heterogeneous per-cluster
1232    /// restart-policy overlays land, a per-tenant restart-policy-alias
1233    /// table the M4 CR materializer resolves per-CR) that would drop
1234    /// the `const` qualifier fails the fail-before-pass-after pin
1235    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
1236    /// build time rather than surfacing as a downstream consumer
1237    /// regression.
1238    #[must_use]
1239    pub const fn restart(&self) -> RestartPolicy {
1240        self.restart
1241    }
1242}
1243
1244/// Supervisor-typed slots that live alongside the standard Caixa
1245/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
1246/// the manifest stays a single typed form; this struct exists for
1247/// validation + conversion.
1248#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1249#[serde(rename_all = "camelCase")]
1250pub struct SupervisorSpec {
1251    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
1252    #[serde(default)]
1253    pub estrategia: RestartStrategy,
1254
1255    /// Max restarts within [`Self::restart_window`] before the
1256    /// supervisor itself terminates (and its parent supervisor decides
1257    /// what to do). Default 5.
1258    #[serde(default = "default_max_restarts")]
1259    pub max_restarts: u32,
1260
1261    /// Sliding window for `max_restarts`. Authored as a duration
1262    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
1263    /// is rejected by [`Self::validate`] — Erlang/OTP's
1264    /// `MaxIntensity / Period` invariant requires a positive window
1265    /// (a zero-period supervisor either trips on the first failure or
1266    /// never trips, depending on operator interpretation, neither of
1267    /// which is the author's intent). Omit the slot to express "no
1268    /// reset"; carry a positive duration to express the sliding window.
1269    #[serde(
1270        default,
1271        skip_serializing_if = "Option::is_none",
1272        with = "duration_codec"
1273    )]
1274    pub restart_window: Option<Duration>,
1275
1276    /// Static children. Empty for `SimpleOneForOne` (children added
1277    /// dynamically); required for the other three strategies.
1278    #[serde(default)]
1279    pub children: Vec<ChildSpec>,
1280}
1281
1282const fn default_max_restarts() -> u32 {
1283    // Route the private serde-`#[serde(default = "…")]` helper through
1284    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
1285    // `pub const` rather than the raw `5` literal — one source of truth
1286    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
1287    // default across the two production consumers that currently
1288    // dispatch on it (this helper via `#[serde(default = "…")]` on
1289    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
1290    // impl at line 962). Pinned by
1291    // `default_max_restarts_helper_routes_through_lifted_default` +
1292    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
1293    // in the tests module; peer of the sibling caixa-core
1294    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
1295    // that now routes its author-omitted `:max-restarts` arm through
1296    // the same lifted constant.
1297    SUPERVISOR_MAX_RESTARTS_DEFAULT
1298}
1299
1300/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
1301/// count default for the `:supervisor :max-restarts` axis — the
1302/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
1303/// Erlang's worker-supervisor default, extracted as a typed `pub const`
1304/// so every substrate-side consumer that resolves "what
1305/// [`SupervisorSpec::max_restarts`] value does an author-omitted
1306/// `:max-restarts` slot degrade onto?" reaches for exactly one
1307/// substrate-primitive `u32`.
1308///
1309/// The `:max-restarts` default axis has two production consumers on the
1310/// substrate side today (both prior to this lift folded onto raw `5`
1311/// literals with no compile-time link back to a shared truth): the
1312/// serde-`#[serde(default = "default_max_restarts")]` helper on
1313/// [`SupervisorSpec::max_restarts`] that every author-omitted
1314/// `:supervisor :max-restarts` slot lands in past the derive-macro's
1315/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
1316/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
1317/// the composed [`SupervisorSpec`] altitude reaches through
1318/// (`feira app graph`, the future wasm-operator's per-supervisor
1319/// restart-intensity counter, the future M4
1320/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1321/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
1322/// A pair of open-coded `5`s across two files that expressed no
1323/// compile-time link back to the shared OTP-canonical default — a
1324/// future rebrand of the default (a tightening to Elixir's
1325/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
1326/// the operator pins through a future
1327/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
1328/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1329/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
1330/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
1331/// per-child-cohort roadmap lands) would have had to be threaded
1332/// through both open-coded copies in lockstep or the wire-format
1333/// author-omitted arm and the view-construction author-omitted arm
1334/// would silently disagree on which restart-budget an omitted
1335/// `:max-restarts` resolves to (an author writing `:supervisor
1336/// (:max-restarts ())` would round-trip through serde with the new
1337/// default while `supervisor_view` silently continued to compose the
1338/// stale `5`, or vice versa), a two-consumer split at the composition
1339/// boundary far from the source `caixa.lisp` with no field naming the
1340/// default-drift root cause. Lifting the resolution rule to a typed
1341/// `pub const` on the substrate primitive means every downstream
1342/// consumer of the per-Supervisor default-restart-budget-count surface
1343/// reaches for exactly one substrate-primitive `u32` — the resolver's
1344/// accepted value migrates as a unit on any future axis change.
1345///
1346/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1347/// worker-supervisor default (the closest canonical OTP-shape
1348/// production reference the substrate carries, matching the sibling
1349/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
1350/// this constant with on the paired sliding-window axis). Two orders of
1351/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
1352/// (the upper bracket on the same axis, sibling of this lower default;
1353/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
1354/// axis and now share one accessor discipline on the substrate) and
1355/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
1356/// restart floor — the "one restart, then escalate" default is
1357/// deliberately loose enough to absorb a short burst of transient
1358/// child failures without escalating past the supervisor's parent
1359/// while remaining tight enough to trip the `MaxIntensity / Period`
1360/// ratio's escalation on a genuinely-stuck child within the sibling
1361/// `60s` sliding window.
1362///
1363/// Lifted as a typed `pub const` so the bound has exactly one source
1364/// of truth — the serde-side wire-format author-omitted arm at
1365/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
1366/// struct-literal default field, and the caixa-core
1367/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
1368/// arm all read from one place. Same shape every other typed default
1369/// in this crate carries (the sibling
1370/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
1371/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
1372/// sibling `:restart-window` axis, and the peer
1373/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1374/// per-renderer defaults on the caixa-flux / caixa-helm rendering
1375/// axes).
1376pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
1377
1378/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
1379/// validated [`SupervisorSpec::max_restarts`] past
1380/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
1381///
1382/// The typed field is `u32` (the zero-floor arm
1383/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
1384/// so a programmatic struct literal
1385/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
1386/// author-surface form (`:max-restarts 4294967295` or any
1387/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
1388/// cleanly through serde — a structurally unbounded `u32` ceiling. The
1389/// runtime substrate consuming the value (Erlang/OTP's
1390/// `MaxIntensity / Period` ratio, the future wasm-operator's
1391/// per-supervisor restart-intensity counter, the M4
1392/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
1393/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
1394/// escalation threshold is structurally so high that no realistic
1395/// restarts-per-`:restart-window` traffic shape can reach it, the
1396/// supervisor never escalates to its parent, and a bad child can loop
1397/// inside the window indefinitely with the parent supervisor structurally
1398/// never receiving the "this subtree has exceeded its restart budget"
1399/// signal the typed slot is meant to express — the canonical
1400/// "supervisor intensity declared, no escalation" footgun, exactly the
1401/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
1402/// on the `:politicas :circuit-breaker :max-failures` axis (both are
1403/// "trip the next-higher protection layer after N events in a rolling
1404/// window" counters with identical degenerate-at-the-high-end shape).
1405///
1406/// The `1000` ceiling matches the sibling
1407/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
1408/// peer — same "events-per-window trip threshold" semantics, same `u32`
1409/// type, same no-op-at-the-high-end failure mode) so the M4
1410/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
1411/// and the future wasm-operator's per-supervisor restart-intensity
1412/// counter reach for either field knowing the value is in `1..=1000`
1413/// without re-validating at the reconciler layer. The cap sits two
1414/// orders of magnitude above every documented Erlang/OTP production
1415/// playbook recommendation (Learn You Some Erlang's
1416/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
1417/// `max_restarts: 3` default, OTP's `supervisor` callback module
1418/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
1419/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
1420/// default) and below the clearly-pathological "effectively no
1421/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
1422/// author can plausibly want at hyperscale (a long-running supervisor
1423/// over a very-flaky pool tolerating thousands of transient restarts
1424/// before escalating), but a hard wall above which the typed policy is
1425/// structurally a no-op carried verbatim on every emitted child-restart
1426/// reconciliation contract.
1427///
1428/// Lifted as a typed `pub const` so the bound has exactly one source of
1429/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1430/// materializer's admission webhook and the wasm-operator-side
1431/// per-supervisor restart-intensity reconciler read from one place. Same
1432/// shape every other typed upper bound in this crate carries
1433/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1434/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1435/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1436/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1437/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1438/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1439pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
1440
1441/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
1442/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
1443/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
1444/// (inclusive on both ends, integer-millisecond magnitudes by the
1445/// canonical-form gate immediately preceding).
1446///
1447/// The typed field is `Option<Duration>` (the zero-floor arm
1448/// [`SupervisorError::RestartWindowZero`] already rejects
1449/// `Some(Duration::ZERO)`, and the canonical-form arm
1450/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
1451/// sub-millisecond residue), so a programmatic struct literal
1452/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
1453/// .. }` — 24h) and the equivalent author-surface form
1454/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
1455/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
1456/// cleanly through serde — a structurally unbounded `Duration` ceiling.
1457/// A `:restart-window` value far above the documented Erlang/OTP
1458/// `MaxIntensity / Period` production-playbook band (Learn You Some
1459/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
1460/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
1461/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
1462/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
1463/// degenerates the supervisor's restart-intensity counter into a
1464/// lifetime counter: the rolling failure-counting window is structurally
1465/// so long that transient restarts are never forgotten, so the
1466/// `MaxIntensity / Period` ratio degenerates from "trip the parent
1467/// supervisor when the child has exceeded its restart budget *within
1468/// the recent window*" to "trip the parent when the child has exceeded
1469/// its restart budget *over its lifetime*" — every transient restart
1470/// counts against the budget forever, the supervisor's reset semantic
1471/// never reaches the child, and the typed `:restart-window` slot
1472/// becomes a no-op rolling window carried on every emitted hierarchical
1473/// reconciliation contract. The canonical
1474/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
1475/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
1476/// `:politicas :circuit-breaker :window` axis with identical shape (both
1477/// are "rolling failure-counting window with a per-`Period` reset" Duration
1478/// axes whose lifetime-counter degenerate at the high end is the same
1479/// "the reset semantic never fires" CSE invariant violation).
1480///
1481/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
1482/// the shared duration codec emits (`"<n>h"` for any integer-hour
1483/// magnitude) — every value in the canonical authoring form's
1484/// `<integer><unit>` grammar at or below this cap renders to a clean
1485/// canonical string — and matches the three sibling typed-`Duration`
1486/// caps already lifted to this surface
1487/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1488/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
1489/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
1490/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
1491/// per-supervisor `:supervisor :restart-window` — now share a single
1492/// uniform top edge at the codec's largest emitted unit so the next
1493/// typed-slot wiring (the future wasm-operator's per-supervisor
1494/// `MaxIntensity / Period` reconciler, the M4
1495/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1496/// webhook, the `caixa-operator`'s hierarchical reconciliation
1497/// scheduler) reaches for any of the four knowing the value is in
1498/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
1499/// two orders of magnitude above every documented Erlang/OTP / Elixir /
1500/// Riak Core / RabbitMQ production-playbook recommendation band
1501/// (`5s..=300s`) and below the clearly-pathological "rolling window
1502/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
1503/// a value the author can plausibly want for a very-low-traffic
1504/// long-tail failure-restart window over a hyperscale-flaky child pool,
1505/// but a hard wall above which the rolling-window contract is
1506/// structurally a lifetime-counter contract.
1507///
1508/// Lifted as a typed `pub const` so the bound has exactly one source
1509/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1510/// materializer's admission webhook, the wasm-operator-side
1511/// per-supervisor `MaxIntensity / Period` reconciler, and the
1512/// `caixa-operator`'s hierarchical reconciliation scheduler all read
1513/// from one place. Same shape every other typed upper bound in this
1514/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
1515/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1516/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1517/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1518/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1519/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1520/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
1521/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1522/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1523pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
1524
1525/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
1526/// default for the `:supervisor :restart-window` axis — the canonical
1527/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
1528/// worker-supervisor default, extracted as a typed `pub const` so every
1529/// substrate-side consumer that resolves "what
1530/// [`SupervisorSpec::restart_window`] value does an author-omitted
1531/// `:restart-window` slot degrade onto?" reaches for exactly one
1532/// substrate-primitive [`Duration`].
1533///
1534/// The `:restart-window` default axis has one production consumer on the
1535/// substrate side today: the [`Default for SupervisorSpec`] impl's
1536/// struct-literal `restart_window` field, which prior to this lift folded
1537/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
1538/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
1539/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
1540/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
1541/// *not* fall back to this default on the sibling `:restart-window` axis
1542/// — an author-omitted `:supervisor :restart-window` composes to
1543/// `restart_window: None` (the shared codec's soft-swallow shape),
1544/// keeping author-declared intent ("no reset — never escalate on rolling
1545/// window") distinct from the [`Default for SupervisorSpec`] "canonical
1546/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
1547/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
1548/// default was split across two files with no compile-time link between
1549/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
1550/// `MaxIntensity` half at the substrate primitive while the `Period`
1551/// half rode as an open-coded literal at the composition site, so a
1552/// future coherent rebrand of the paired canonical (a tightening to
1553/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
1554/// per-cluster overlay the operator pins through a future
1555/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
1556/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1557/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
1558/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
1559/// roadmap lands) would have had to migrate the `MaxIntensity` half
1560/// through the lifted constant and the `Period` half through a raw
1561/// literal in lockstep or the two halves of the same OTP-canonical
1562/// default would silently drift out of pairing. Lifting the resolution
1563/// rule to a typed `pub const` on the substrate primitive means the
1564/// paired OTP-canonical default migrates as one unit on any future
1565/// axis change.
1566///
1567/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1568/// worker-supervisor default (the closest canonical OTP-shape
1569/// production reference the substrate carries, matching the paired
1570/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
1571/// constant is the `Period` denominator of on the same
1572/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
1573/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
1574/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
1575/// this lower default; both are typed [`Duration`] const bounds on the
1576/// `:supervisor :restart-window` axis and now share one accessor
1577/// discipline on the substrate) and above the OTP-`supervisor`
1578/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
1579/// rolling window" default is deliberately loose enough to absorb a
1580/// short burst of transient child failures without escalating past the
1581/// supervisor's parent while remaining tight enough for the paired
1582/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
1583/// stuck child within a human-scale observation window.
1584///
1585/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1586/// exactly one source of truth on each half — the sibling
1587/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
1588/// `Period` `60s` half now share the same substrate-primitive lift
1589/// discipline. Same shape every other typed default in this crate
1590/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
1591/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
1592/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
1593/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
1594/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
1595/// caixa-flux / caixa-helm rendering axes).
1596pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
1597
1598/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
1599/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
1600/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
1601/// worker-supervisor default, extracted as a typed `pub const` so every
1602/// substrate-side consumer that resolves "what
1603/// [`SupervisorSpec::estrategia`] variant does an author-omitted
1604/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
1605/// primitive [`RestartStrategy`].
1606///
1607/// The `:estrategia` default axis has three production consumers on the
1608/// substrate side today: the [`Default for RestartStrategy`] impl's
1609/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
1610/// `estrategia` field, and the
1611/// [`crate::manifest::Caixa::supervisor_view`] fold's
1612/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
1613/// collapse arm — three entry points onto the same OTP-canonical
1614/// `one_for_one` value that prior to this lift folded onto a raw
1615/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
1616/// implicit `RestartStrategy::default()` routes at the sibling consumers,
1617/// with no compile-time link back to the paired
1618/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
1619/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
1620/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
1621/// triple was split across three altitudes with no compile-time link
1622/// between the halves: the `MaxIntensity` half rode through the lifted
1623/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
1624/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1625/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
1626/// discriminator at the [`Default for RestartStrategy`] impl, so a future
1627/// coherent rebrand of the triple (Elixir's `{:one_for_one,
1628/// max_restarts: 3, max_seconds: 5}` — same strategy, different
1629/// intensity/period; an OTP `rest_for_one` widening once the substrate
1630/// discovers startup-order-coupled child cohorts as the more common
1631/// worker-supervisor default; a per-cluster overlay the operator pins
1632/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
1633/// §III.2 supervision-canary roadmap acknowledges) would have had to
1634/// migrate the `MaxIntensity` + `Period` halves through the lifted
1635/// constants and the `one_for_one` half through an open-coded arm in
1636/// lockstep or the three halves of the same OTP-canonical default would
1637/// silently drift out of pairing. Lifting the resolution rule to a typed
1638/// `pub const` on the substrate primitive means the paired OTP-canonical
1639/// worker-supervisor default migrates as one unit on any future axis
1640/// change.
1641///
1642/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
1643/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
1644/// closest canonical OTP-shape production reference the substrate
1645/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
1646/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1647/// `60s` `Period` half). The `one_for_one` strategy — restart only the
1648/// failed child, leaving siblings untouched — is the default for tree-of-
1649/// independent-workers use cases the substrate's [`RestartStrategy`]
1650/// discriminator's own docstring already carries as the default arm; it
1651/// composes with the `{5, 60}` restart-intensity ratio to name the same
1652/// substrate-canonical "canonical worker-supervisor" shape the paired
1653/// halves close on their respective axes.
1654///
1655/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1656/// exactly one source of truth on each of its three halves — the sibling
1657/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
1658/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
1659/// this `one_for_one` strategy half now share the same substrate-
1660/// primitive lift discipline. Same shape every other typed default in
1661/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
1662/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
1663/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
1664/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
1665/// upper caps on the paired sibling axes, and the peer
1666/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1667/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
1668pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
1669
1670/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
1671/// default for the `:children :restart` axis — the OTP `permanent`
1672/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
1673/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
1674/// `pub const` so every substrate-side consumer that resolves "what
1675/// [`ChildSpec::restart`] variant does an author-omitted `:children
1676/// :restart` slot degrade onto?" reaches for exactly one substrate-
1677/// primitive [`RestartPolicy`].
1678///
1679/// Completes the OTP-shape supervisor-tree default set at the substrate
1680/// primitive. The per-`:supervisor` axis already carries all three of its
1681/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1682/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
1683/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1684/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
1685/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
1686/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
1687/// the M2 `:supervisor` slot family. The split mattered because the two
1688/// axes resolve *together* on every author-omitted supervisor: a
1689/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
1690/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
1691/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
1692/// `permanent` through an open-coded enum arm, so a future coherent
1693/// rebrand of the OTP-shape default set (an Elixir-shaped
1694/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
1695/// per-cluster overlay the operator pins through the MESH-COMPOSITION
1696/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
1697/// once the substrate discovers clean-completion-aware children as the
1698/// more common child shape) would have had to migrate three halves
1699/// through typed constants and the fourth through a raw enum arm in
1700/// lockstep or the supervisor-level and child-level defaults would
1701/// silently drift apart.
1702///
1703/// The `:children :restart` default axis has two production consumers on
1704/// the substrate side today: the [`Default for RestartPolicy`] impl's
1705/// return arm, and the serde-side `#[serde(default)]` on
1706/// [`ChildSpec::restart`] that resolves an author-omitted `:children
1707/// :restart` slot through that same impl. Both now key off this one
1708/// substrate primitive, so the future wasm-operator's per-child post-exit
1709/// restart-decision branch, the future M4
1710/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1711/// admission webhook, and the `caixa-operator`'s hierarchical
1712/// reconciliation scheduler's per-child fan-out all reach for one typed
1713/// identifier when they resolve an omitted per-child restart posture.
1714///
1715/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
1716/// worker-child restart type — always restart the child regardless of how
1717/// it died, the canonical posture for long-running services that must
1718/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1719/// `one_for_one` tree-of-independent-workers strategy this constant pairs
1720/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
1721/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
1722/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
1723/// [`RestartPolicy::Temporary`] — never restart) express deliberate
1724/// one-shot / clean-completion-aware postures an author declares
1725/// explicitly, never a posture an omitted slot should silently assume.
1726pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
1727
1728/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
1729/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
1730/// `pub const fn` constructor rather than a struct-literal cascade over
1731/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
1732/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1733/// lifted consts — one source of truth for the Erlang/OTP-canonical
1734/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
1735/// paths every downstream consumer already reaches through (the
1736/// hand-authored-until-now [`Default::default`] the
1737/// `..SupervisorSpec::default()` struct-update-syntax on every
1738/// one-axis-under-test fixture in this crate's test module rests on,
1739/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
1740/// every `const`-context consumer reaches through).
1741///
1742/// Extends the [`Default`]-through-const-ctor fold discipline the
1743/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
1744/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
1745/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
1746/// and [`crate::BehaviorSpec`]
1747/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
1748/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
1749/// typed-slot spec family — extended here onto the M2 supervisor-slot
1750/// [`SupervisorSpec`] whose canonical baseline is not "everything
1751/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
1752/// supervisor triple. The `empty()` peer's naming did not fit
1753/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
1754/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
1755/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
1756/// the sibling `Option`-only slots fold to), so this peer is named
1757/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
1758/// existing per-arm pin tests
1759/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
1760/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
1761/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
1762/// already reach for. Pinned load-bearing by
1763/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
1764/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
1765/// [`PartialEq`], sharpening the sibling
1766/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
1767/// pins from a per-field lift into a whole-struct one-source-of-truth
1768/// pin — the derived-until-now [`Default::default`] and the
1769/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
1770/// construction, not by coincidence).
1771impl Default for SupervisorSpec {
1772    #[inline]
1773    fn default() -> Self {
1774        Self::otp_canonical()
1775    }
1776}
1777
1778impl SupervisorSpec {
1779    /// `const`-context peer of the [`Default for SupervisorSpec`]
1780    /// impl (which routes through this constructor) — returns the
1781    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
1782    /// baseline this crate reaches for in every fixture-builder
1783    /// `..SupervisorSpec::default()` struct-update expression and
1784    /// every downstream `SupervisorSpec::default()` seed.
1785    ///
1786    /// Each field routes through the same substrate-canonical
1787    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
1788    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
1789    /// per-arm pin tests
1790    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
1791    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
1792    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
1793    /// already assert, so a future coherent rebrand of the OTP-canonical
1794    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
1795    /// cluster overlay via a future `:restart-window-overrides` slot, a
1796    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
1797    /// absorption roadmap acknowledges) migrates through three typed
1798    /// constants in lockstep, and the paired [`Default`] impl inherits
1799    /// every future extension by construction.
1800    ///
1801    /// `pub const fn` rather than the derived-style `Default::default`
1802    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
1803    /// [`Default::default`] is not `const` on stable Rust, and
1804    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
1805    /// every consumer through a [`Clone::clone`]. The `pub const fn`
1806    /// discipline lets `const`-context callers construct the OTP-
1807    /// canonical baseline at compile time without runtime dispatch on
1808    /// the derived [`Default::default`], the same posture the sibling
1809    /// [`crate::LimitsSpec::empty`] (9739971) /
1810    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
1811    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
1812    /// spec `pub const fn` constructors carry on the sibling
1813    /// "everything `None`" baseline axis.
1814    ///
1815    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
1816    /// of the derived-style [`Default`]" family — sibling of the
1817    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
1818    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
1819    /// baseline" trio, extended here onto the M2 supervisor-slot
1820    /// [`SupervisorSpec`] whose canonical baseline is not "everything
1821    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
1822    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
1823    /// than `empty()` to name the actual invariant the return value
1824    /// pins — the same phrasing already used in the per-arm pin tests
1825    /// on this file. Pinned load-bearing by
1826    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
1827    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
1828    #[must_use]
1829    pub const fn otp_canonical() -> Self {
1830        Self {
1831            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
1832            max_restarts: default_max_restarts(),
1833            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
1834            children: Vec::new(),
1835        }
1836    }
1837
1838    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
1839    /// sibling-restart-strategy scalar accessor every consumer that
1840    /// dispatches on the supervisor's per-sibling restart-decision shape
1841    /// keys off — returns the author-declared `:supervisor :estrategia`
1842    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
1843    /// the typed slot's own [`RestartStrategy`] storage.
1844    ///
1845    /// The `:supervisor :estrategia` slot carries the closed-set
1846    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
1847    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
1848    /// [`RestartStrategy::OneForAll`] — restart every child on any child
1849    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
1850    /// [`RestartStrategy::RestForOne`] — restart the failed child and
1851    /// every child started after it, the Erlang/OTP `rest_for_one`
1852    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
1853    /// dynamic children of the same shape, the Erlang/OTP
1854    /// `simple_one_for_one` per-session default) that every downstream
1855    /// consumer of the Supervisor's per-sibling restart-decision fan-out
1856    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
1857    /// paired coherently with the sibling `:children` axis
1858    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
1859    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
1860    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
1861    /// downstream consumer that reads the strategy keys off this scalar
1862    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
1863    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
1864    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
1865    /// `estrategia:` field, the future `feira app graph` per-Supervisor
1866    /// strategy print line, the future wasm-operator's per-supervisor
1867    /// sibling-restart-strategy branch, the future M4
1868    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
1869    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
1870    /// reconciliation scheduler's per-strategy fan-out).
1871    ///
1872    /// Prior to this lift the `.estrategia` field was accessed inline at
1873    /// two production sites in `caixa-core/src/supervisor.rs` — the
1874    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
1875    /// `match self.estrategia { … }` partition dispatch, and the
1876    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
1877    /// carrier at `estrategia: self.estrategia` — two open-coded
1878    /// field-accesses that expressed no compile-time link back to the
1879    /// typed slot. A future extension of the `:supervisor :estrategia`
1880    /// axis to a richer author surface (a per-cluster strategy override
1881    /// the operator pins through a future `:supervisor :estrategia-overrides`
1882    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
1883    /// acknowledges, a per-tenant strategy-alias table the M4 CR
1884    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
1885    /// derivation the future adaptive-supervision engine computes from
1886    /// child-failure-history topology, a per-child-cohort strategy split
1887    /// the future `RestForCohort` extension acknowledged by the
1888    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
1889    /// would have had to be threaded through every open-coded copy in
1890    /// lockstep — one consumer reading the raw variant while a peer read
1891    /// the operator-resolved variant would silently split the
1892    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
1893    /// the actual partition-dispatch input the empty-children refusal
1894    /// arm reached under, a two-consumer split at the validator far from
1895    /// the source `caixa.lisp` with no field naming the strategy-drift
1896    /// root cause. Lifting the resolution rule to a typed method on the
1897    /// substrate primitive means every downstream consumer of the
1898    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
1899    /// reaches for exactly one typed dispatch — the resolver's accept-set
1900    /// migrates as a unit on any future axis addition.
1901    ///
1902    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
1903    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
1904    /// per-`:placement` distribution-strategy axis — same "one typed
1905    /// dispatch on the substrate primitive, thin projections at each
1906    /// consumer" discipline extended onto the M2 supervisor-slot
1907    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
1908    /// scalar axis. The two typed axes (`Placement::estrategia` on the
1909    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
1910    /// Supervisor side) now share one accessor discipline for the shared
1911    /// substrate concept "a `Copy`-projected closed-set enum-arm
1912    /// discriminator that partitions the downstream renderer's per-arm
1913    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
1914    /// `SupervisorSpec` type — companion to the sibling per-`:children`
1915    /// [`crate::ChildSpec::nome`] (57c61d0) /
1916    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
1917    /// scalar accessors on the sibling per-`:children` `String`-carry
1918    /// axes. Named `estrategia()` to match the storage field's name and
1919    /// the peer [`crate::Placement::estrategia`] method-name discipline
1920    /// verbatim; the accessor's identity name maps onto the canonical
1921    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
1922    /// docstring already carries.
1923    ///
1924    /// Declared `pub const fn` to close the M2 supervisor-slot
1925    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
1926    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
1927    /// (converted in this commit) `Copy`-composite-enum accessor, peer
1928    /// of the sibling M2 per-`:supervisor`
1929    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1930    /// already lifted, and mirror of the peer M3 mesh-slot
1931    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
1932    /// `Copy`-return `pub const fn` scalar accessor whose method-name
1933    /// discipline this accessor was authored to match. Every downstream
1934    /// substrate-side `const`-context consumer of the per-`:supervisor`
1935    /// sibling-restart-strategy scalar (a future module-scope `const
1936    /// _:() = assert!(matches!(sup.estrategia(),
1937    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
1938    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1939    /// admission-webhook `const fn` per-supervisor strategy-arm floor
1940    /// over a typed [`SupervisorSpec`], any future `const fn`
1941    /// supervisor-tree composer over the substrate primitive that fans
1942    /// on the sibling-restart-strategy at compile time) now reaches
1943    /// through the same typed dispatch on the substrate primitive at
1944    /// const-eval time as at runtime. A future non-`Copy`-return
1945    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
1946    /// migration once the substrate grows per-cluster strategy overlays
1947    /// the [`SupervisorSpec`] docstring already anticipates, a
1948    /// per-tenant strategy-alias table the M4 CR materializer resolves
1949    /// per-CR) that would drop the `const` qualifier fails the
1950    /// fail-before-pass-after pin
1951    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
1952    /// caixa-core build time rather than surfacing as a downstream
1953    /// consumer regression.
1954    #[must_use]
1955    pub const fn estrategia(&self) -> RestartStrategy {
1956        self.estrategia
1957    }
1958
1959    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
1960    /// `MaxIntensity` restart-budget scalar accessor every consumer that
1961    /// reads the supervisor's per-`:restart-window` restart-budget count
1962    /// keys off — returns the author-declared `:supervisor :max-restarts`
1963    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
1964    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
1965    /// borrow of `&self` past the call). Non-optional (the `u32` field
1966    /// carries the restart-budget count as a required axis with a
1967    /// [`default_max_restarts`]-supplied default; the zero-floor arm
1968    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
1969    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
1970    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
1971    ///
1972    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
1973    /// `MaxIntensity` restart-budget count that pairs with the sibling
1974    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
1975    /// restart-intensity ratio the supervisor trips its own escalation on
1976    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
1977    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
1978    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
1979    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
1980    /// upper-cap bracket at
1981    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
1982    /// wasm-operator's per-supervisor restart-intensity counter's
1983    /// budget-vs-count comparator, the future M4
1984    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1985    /// webhook, the `caixa-operator`'s hierarchical reconciliation
1986    /// scheduler's per-supervisor escalation-decision branch, every
1987    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
1988    /// offending count verbatim for `feira lint` rendering).
1989    ///
1990    /// Prior to this lift the `.max_restarts` field was accessed inline at
1991    /// one production site in `caixa-core/src/supervisor.rs` — the
1992    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
1993    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
1994    /// that expressed no compile-time link back to the typed slot. A
1995    /// future extension of the `:max-restarts` axis to a richer author
1996    /// surface (a per-cluster restart-budget override the operator pins
1997    /// through a future `:supervisor :max-restarts-overrides` slot the
1998    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
1999    /// a per-tenant restart-budget-alias table the M4 CR materializer
2000    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
2001    /// the future adaptive-supervision engine computes from child-failure-
2002    /// history topology, a promotion of the plain `u32` count to a richer
2003    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
2004    /// budget-partition slot comes into scope) would have had to be
2005    /// threaded through every open-coded copy in lockstep or the validate
2006    /// gate and the future M4 emit path would silently disagree on which
2007    /// restart-budget count a given supervisor resolves to — an author's
2008    /// `:max-restarts 5` would satisfy validate while the emit path
2009    /// silently read a drifted other value (a `:max-restarts 10000`
2010    /// no-op supervisor at the emit boundary would carry the author's
2011    /// declared `5` verbatim in `feira lint` output while the future
2012    /// wasm-operator's restart-intensity counter operated under the
2013    /// drifted count), a two-consumer split at the validator far from the
2014    /// source `caixa.lisp` with no field naming the restart-budget-drift
2015    /// root cause. Lifting the resolution rule to a typed method on the
2016    /// substrate primitive means every downstream consumer of the
2017    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
2018    /// for exactly one typed dispatch — the resolver's accept-set migrates
2019    /// as a unit on any future axis addition.
2020    ///
2021    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
2022    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
2023    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
2024    /// outlier-detection trip-threshold axis — same "one typed dispatch on
2025    /// the substrate primitive, thin projections at each consumer"
2026    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
2027    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
2028    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
2029    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
2030    /// one accessor discipline for the shared substrate concept "a
2031    /// `Copy`-projected required `u32` count that trips the next-higher
2032    /// protection layer after N events in a rolling window" — both are
2033    /// counters with identical degenerate-at-the-high-end shape and share
2034    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
2035    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
2036    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
2037    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
2038    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
2039    /// the storage field's name verbatim and the peer
2040    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
2041    /// accessor's identity maps onto the canonical OTP-shape supervision
2042    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
2043    /// already carries.
2044    #[must_use]
2045    pub const fn max_restarts(&self) -> u32 {
2046        self.max_restarts
2047    }
2048
2049    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
2050    /// `Period` sliding-window scalar accessor every consumer of the
2051    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
2052    /// keys off — returns the author-declared `:supervisor :restart-window`
2053    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
2054    /// the typed slot's own `Option<Duration>` storage (`Duration` is
2055    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
2056    /// value; no borrow of `&self` past the call). `None` when the slot is
2057    /// absent (the canonical "never reset — every restart across the
2058    /// supervisor's lifetime counts against the sibling `:max-restarts`
2059    /// budget" sentinel the field's own docstring names and the peer
2060    /// `validate_accepts_none_restart_window` pin locks in on the
2061    /// [`SupervisorSpec::validate`] entry-side).
2062    ///
2063    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
2064    /// `Period` sliding-observation-interval that pairs with the sibling
2065    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
2066    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
2067    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
2068    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
2069    /// default). The typed slot's `Option<Duration>` accept-set —
2070    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
2071    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
2072    /// `Period > 0`; a zero period either trips on the first failure or
2073    /// never trips depending on operator interpretation, neither of which
2074    /// is the author's intent — omit the slot to express "no reset";
2075    /// carry a positive duration to express the sliding window),
2076    /// integer-millisecond canonical form enforced through
2077    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
2078    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
2079    /// future wasm-operator's per-supervisor restart-intensity counter
2080    /// quantizes at milliseconds), upper-bounded by
2081    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
2082    /// supervisor rolling window any operationally-reachable supervisor
2083    /// can honor without spanning multiple scheduler epochs the
2084    /// hierarchical-reconciliation scheduler treats as independent) —
2085    /// maps onto the future wasm-operator (M3) per-supervisor
2086    /// restart-intensity counter's rolling-observation-interval, the
2087    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2088    /// per-`spec.restartWindow` admission webhook, and the sibling
2089    /// `duration_codec`-serialized wire scalar every downstream consumer
2090    /// of the supervisor's per-`:supervisor` restart-intensity denominator
2091    /// keys off.
2092    ///
2093    /// Prior to this lift the `.restart_window` field was accessed inline
2094    /// at one production site in `caixa-core/src/supervisor.rs` — the
2095    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
2096    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
2097    /// open-coded field-access that expressed no compile-time link back to
2098    /// the typed slot. A future extension of the `:restart-window` axis to
2099    /// a richer author surface (a per-cluster restart-window override the
2100    /// operator pins through a future `:supervisor :restart-window-overrides`
2101    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2102    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
2103    /// materializer resolves per-CR, a per-supervisor dynamic
2104    /// restart-window derivation the future adaptive-supervision engine
2105    /// computes from child-failure-history topology, a promotion of the
2106    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
2107    /// pair once Erlang/OTP's per-child-cohort observation-interval-
2108    /// partition slot comes into scope) would have had to be threaded
2109    /// through every open-coded copy in lockstep or the validate gate and
2110    /// the future M4 emit path would silently disagree on which
2111    /// restart-window a given supervisor resolves to — an author's
2112    /// `:restart-window "60s"` would satisfy validate while the emit path
2113    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
2114    /// authored slot at the emit boundary would carry the author's
2115    /// declared window verbatim in `feira lint` output while the future
2116    /// wasm-operator's restart-intensity counter operated under a
2117    /// drifted window, or vice versa: an author's `:restart-window ()`
2118    /// would carry the "never reset" sentinel through validate while the
2119    /// emit path silently substituted a default sliding window), a
2120    /// two-consumer split at the validator far from the source
2121    /// `caixa.lisp` with no field naming the restart-window-drift root
2122    /// cause. Lifting the resolution rule to a typed method on the
2123    /// substrate primitive means every downstream consumer of the
2124    /// Supervisor's per-`:supervisor` restart-intensity-denominator
2125    /// surface reaches for exactly one typed dispatch — the resolver's
2126    /// accept-set migrates as a unit on any future axis addition.
2127    ///
2128    /// Third `Copy`-return accessor on the M2 supervisor-slot
2129    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
2130    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
2131    /// payload rather than a `Copy`-scalar, and the per-`:children`
2132    /// [`crate::ChildSpec::nome`] (57c61d0) /
2133    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2134    /// scalar accessors already close the per-element `String`-carry
2135    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
2136    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
2137    /// per-outermost-call wall-clock-deadline axis and the peer M3
2138    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
2139    /// accessor on the `:politicas` slot's per-call-deadline axis — all
2140    /// three share the shared substrate concept "a `Copy`-projected
2141    /// optional `Duration` that carries a positive integer-millisecond
2142    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
2143    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
2144    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
2145    /// bracket-helper the three axes each route through. Named
2146    /// `restart_window()` to match the storage field's name verbatim and
2147    /// the peer [`crate::LimitsSpec::wall_clock`] /
2148    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
2149    /// accessor's identity maps onto the canonical OTP-shape supervision
2150    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
2151    /// already carries.
2152    #[must_use]
2153    pub const fn restart_window(&self) -> Option<Duration> {
2154        self.restart_window
2155    }
2156
2157    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
2158    /// static-child-list slice accessor every consumer that walks the
2159    /// supervisor's declared child set keys off — returns the author-
2160    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
2161    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
2162    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
2163    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
2164    /// through). Non-optional: an empty slice is the load-bearing
2165    /// "author declared `:children ()`" sentinel every consumer of the
2166    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
2167    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
2168    /// three strategies require a non-empty slice — the paired
2169    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
2170    /// [`SupervisorError::NoChildren`] refusal cascade pins the
2171    /// partition on both arms).
2172    ///
2173    /// The `:supervisor :children` slot carries the OTP-shaped static
2174    /// child list the supervisor materializes one ComputeUnit per
2175    /// entry from — the Erlang/OTP `supervisor:init/1`'s
2176    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
2177    /// through the tatara-lisp `:children` author surface onto a typed
2178    /// `Vec<ChildSpec>` whose per-element `(nome(),
2179    /// versao_requirement(), restart)` triple the per-child
2180    /// [`SupervisorSpec::validate`] loop already gates through the
2181    /// lifted [`ChildSpec::nome`] (57c61d0) /
2182    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
2183    /// Every downstream consumer that fans on the static child list
2184    /// keys off this slice (the [`SupervisorSpec::validate`]
2185    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
2186    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
2187    /// per-child DNS-1123 / semver-requirement / duplicate-detection
2188    /// fan-out loop, every future wasm-operator (M3) per-supervisor
2189    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
2190    /// materialization loop, the future M4
2191    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2192    /// admission-webhook fan-out, the future `feira app graph`
2193    /// per-supervisor tree-print traversal).
2194    ///
2195    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
2196    /// inline at three production sites in `caixa-core/src/supervisor.rs`
2197    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
2198    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
2199    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
2200    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
2201    /// validate loop's `for child in &self.children` traversal head —
2202    /// three open-coded field-accesses that expressed no compile-time
2203    /// link back to the typed slot. A future extension of the
2204    /// `:supervisor :children` axis to a richer author surface (a
2205    /// per-cluster child-set overlay the operator pins through a future
2206    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
2207    /// supervision-canary roadmap acknowledges, a per-tenant
2208    /// child-set-alias table the M4 CR materializer resolves per-CR,
2209    /// a per-supervisor dynamic-child derivation the future adaptive-
2210    /// supervision engine computes from child-failure-history topology,
2211    /// a promotion of the plain `Vec<ChildSpec>` to a richer
2212    /// `{static, dynamic}` partition once Erlang/OTP's
2213    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
2214    /// would have had to be threaded through all three open-coded copies
2215    /// in lockstep or one consumer would silently disagree with the
2216    /// peers on which child-set a given supervisor resolves to — the
2217    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
2218    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
2219    /// would silently split the partition-dispatch's two-arm coherence
2220    /// (a supervisor that satisfies neither arm's precondition, or that
2221    /// satisfies both, at the cost of the paired
2222    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
2223    /// silently drifting from the per-child validate loop's actual
2224    /// traversal input), a three-consumer split at the validator far
2225    /// from the source `caixa.lisp` with no field naming the
2226    /// child-set-drift root cause. Lifting the resolution rule to a
2227    /// typed method on the substrate primitive means every downstream
2228    /// consumer of the Supervisor's per-`:supervisor` static-child-list
2229    /// surface reaches for exactly one typed dispatch — the resolver's
2230    /// accept-set migrates as a unit on any future axis addition.
2231    ///
2232    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
2233    /// — the seed for the same "one typed dispatch on the substrate
2234    /// primitive, thin projections at each consumer" discipline the
2235    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
2236    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
2237    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
2238    /// onto the first `Vec`-carry axis on the substrate. The four peer
2239    /// `Vec`-carry axes still unlifted at the time of this seed —
2240    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
2241    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
2242    /// (`Vec<Membro>` per-Aplicacao member list),
2243    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
2244    /// per-Aplicacao WIT-typed edge list),
2245    /// [`crate::UpgradeFromEntry::instructions`]
2246    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
2247    /// — inherit this accessor's discipline as future compounding runs
2248    /// migrate their consumers onto the shared slice-return shape.
2249    /// Fourth (and final) accessor on the M2 supervisor-slot
2250    /// `SupervisorSpec` type, sibling to the three `Copy`-return
2251    /// [`SupervisorSpec::estrategia`] (eafb619) /
2252    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
2253    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
2254    /// the last unlifted per-`:supervisor` field axis (the
2255    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
2256    /// per-`:supervisor` reader now routes through a typed dispatch on
2257    /// the substrate primitive. Named `children()` to match the storage
2258    /// field's name verbatim and the tatara-lisp author-surface term
2259    /// (`:children`) the field's own docstring already carries; the
2260    /// accessor's identity maps onto the canonical OTP-shape
2261    /// supervision vocabulary the [`SupervisorSpec::children`] field's
2262    /// docstring already reaches for ("Static children ..."). Returns
2263    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
2264    /// consumer of the child list treats it as a read-only sequence —
2265    /// the slice-view is the narrowest borrow that supports every
2266    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
2267    /// index, `.len()`) without leaking the backing `Vec`'s
2268    /// grow/push/reserve surface that no consumer of the typed view
2269    /// reaches for (the storage-side `Vec` remains reachable through
2270    /// the `pub children` field for the mutation-carrying
2271    /// `Caixa::supervisor_view` fold-in path in
2272    /// `manifest.rs:supervisor_view`).
2273    #[must_use]
2274    pub const fn children(&self) -> &[ChildSpec] {
2275        self.children.as_slice()
2276    }
2277
2278    /// Validate the supervisor's typed shape — strategy ↔ children
2279    /// invariants, max_restarts > 0, restart_window > 0 when set,
2280    /// per-child non-empty + duplicate-free names.
2281    ///
2282    /// Mirrors the value-shape discipline applied to every other
2283    /// typed slot:
2284    ///
2285    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
2286    ///     same "0 means the opposite of what you think" footgun
2287    ///     closed for `:politicas :timeout` (Envoy interprets a zero
2288    ///     timeout as `infinite`), `:politicas :circuit-breaker
2289    ///     :window`, and `:limits :wall-clock`. The
2290    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
2291    ///     `supervisor` requires `Period > 0`; a zero period either
2292    ///     trips on the first failure or never trips depending on
2293    ///     operator interpretation, neither of which is the
2294    ///     author's intent. Omit `:restart-window` to express "no
2295    ///     reset"; carry a positive duration to express the window.
2296    ///   - duplicate `:children` `:caixa` names are the same
2297    ///     graph-node-set / multiset distinction closed for
2298    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
2299    ///     and `:entrada :paths` (eb3456d). Two children with the
2300    ///     same `:caixa` materialize as two ComputeUnits with the
2301    ///     same name in the cluster's HelmRelease values, one
2302    ///     silently overwriting the other. Erlang/OTP's
2303    ///     `child_spec.id` is required-unique per supervisor;
2304    ///     pleme-io enforces the same set-not-multiset shape on
2305    ///     `:caixa` (the load-bearing identity in our renderer).
2306    pub fn validate(&self) -> Result<(), SupervisorError> {
2307        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
2308        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2309        // error carrier's `estrategia:` field through the lifted
2310        // [`SupervisorSpec::estrategia`] accessor rather than the raw
2311        // `self.estrategia` field access — the two production consumers
2312        // of the per-`:supervisor` sibling-restart-strategy scalar now
2313        // key off exactly one typed dispatch on the substrate primitive,
2314        // so any future rebrand on the axis (a per-cluster strategy
2315        // override the operator pins through a future `:supervisor
2316        // :estrategia-overrides` slot, a per-tenant strategy-alias table
2317        // the M4 CR materializer resolves per-CR) migrates as a single
2318        // caixa-core edit rather than a coordinated rewrite of the two
2319        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
2320        // (921fe1b) four-consumer migration on the per-`:placement`
2321        // distribution-strategy axis.
2322        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
2323        // dispatch's paired `.is_empty()` cross-slot refusal probes
2324        // (the `SimpleOneForOne`-arm
2325        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
2326        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2327        // refusal) through the lifted [`SupervisorSpec::children`]
2328        // slice-return accessor rather than the raw `self.children`
2329        // field access — the two paired production consumers of the
2330        // per-`:supervisor` static-child-list scalar-shape now key off
2331        // exactly one typed dispatch on the substrate primitive, so any
2332        // future rebrand on the axis (a per-cluster child-set overlay
2333        // the operator pins through a future `:supervisor
2334        // :children-overrides` slot, a per-tenant child-set-alias table
2335        // the M4 CR materializer resolves per-CR) migrates as a single
2336        // caixa-core edit rather than a coordinated rewrite of the
2337        // paired arms — first slice-return migration on any typed slot,
2338        // seed for the peer per-`:placement :clusters`,
2339        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
2340        // :instructions` `Vec`-carry axes.
2341        match self.estrategia() {
2342            RestartStrategy::SimpleOneForOne => {
2343                // SimpleOneForOne: children added at runtime. Static
2344                // list must be empty (one shape declared elsewhere).
2345                if !self.children().is_empty() {
2346                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
2347                }
2348            }
2349            _ => {
2350                if self.children().is_empty() {
2351                    return Err(SupervisorError::no_children(self.estrategia()));
2352                }
2353            }
2354        }
2355        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
2356        // axis. See [`crate::render::require_positive_bounded_u32`] for
2357        // the ordering discipline (zero-floor arm strictly precedes cap
2358        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
2359        // diagnostic with its counter-axis remediation directly named,
2360        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
2361        // cap-arm miss). Until this bracket landed the top edge ran all
2362        // the way to `u32::MAX` and a struct-literal
2363        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
2364        // equivalent author-surface `:max-restarts 100000` /
2365        // `:max-restarts 4294967295` typo landing in the slot) silently
2366        // passed validate. The runtime substrate consuming the value
2367        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
2368        // wasm-operator's per-supervisor restart-intensity counter, the
2369        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2370        // admission webhook) then turned a typed `:max-restarts`
2371        // policy into a no-op supervisor: the escalation threshold is
2372        // structurally so high that no realistic
2373        // restarts-per-`:restart-window` traffic shape can reach it,
2374        // the supervisor never escalates to its parent, and a bad
2375        // child can loop inside the window indefinitely with the
2376        // parent supervisor structurally never receiving the "this
2377        // subtree has exceeded its restart budget" signal the typed
2378        // slot is meant to express. The bracket set is
2379        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
2380        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
2381        // the sibling `:politicas :circuit-breaker :max-failures` axis:
2382        // both are "trip the next-higher protection layer after N
2383        // events in a rolling window" counters with identical
2384        // degenerate-at-the-high-end shape and now share one canonical
2385        // bracket helper. The bracket precedes the sibling
2386        // `:restart-window` zero-floor / canonical-millisecond arms so
2387        // an over-cap `max_restarts` paired with a structurally invalid
2388        // window surfaces the bracket diagnostic first, mirroring the
2389        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
2390        // ordering on the peer `:politicas :circuit-breaker` slot.
2391        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
2392        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
2393        // accessor rather than the raw `self.max_restarts` field access —
2394        // the one production consumer of the per-`:supervisor`
2395        // restart-budget-count scalar now keys off exactly one typed
2396        // dispatch on the substrate primitive, so any future rebrand on
2397        // the axis (a per-cluster restart-budget override the operator
2398        // pins through a future `:supervisor :max-restarts-overrides`
2399        // slot, a per-tenant restart-budget-alias table the M4 CR
2400        // materializer resolves per-CR) migrates as a single caixa-core
2401        // edit rather than a coordinated rewrite — sibling of the peer M3
2402        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
2403        // the per-`:politicas :circuit-breaker :max-failures` axis.
2404        crate::render::require_positive_bounded_u32(
2405            self.max_restarts(),
2406            SUPERVISOR_MAX_RESTARTS_MAX,
2407            || SupervisorError::ZeroMaxRestarts,
2408            SupervisorError::max_restarts_exceeds_cap,
2409        )?;
2410        // Route the [`SupervisorSpec::validate`] `:restart-window`
2411        // zero-floor + integer-millisecond canonical-form + upper-cap
2412        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
2413        // accessor rather than the raw `self.restart_window` field access —
2414        // the one production consumer of the per-`:supervisor`
2415        // restart-intensity-denominator scalar now keys off exactly one
2416        // typed dispatch on the substrate primitive, so any future rebrand
2417        // on the axis (a per-cluster restart-window override the operator
2418        // pins through a future `:supervisor :restart-window-overrides`
2419        // slot, a per-tenant restart-window-alias table the M4 CR
2420        // materializer resolves per-CR) migrates as a single caixa-core
2421        // edit rather than a coordinated rewrite — sibling of the peer M2
2422        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
2423        // on the per-`:limits :wall-clock` axis and the peer M3
2424        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
2425        // per-`:politicas :timeout` axis.
2426        if let Some(w) = self.restart_window() {
2427            // Zero-floor + integer-millisecond canonical-form +
2428            // upper-cap bracket on the typed `:restart-window` axis.
2429            // See
2430            // [`crate::render::require_positive_canonical_bounded_duration`]
2431            // for the full three-arm ordering discipline (zero-floor
2432            // strictly precedes canonical-form so `Duration::ZERO`
2433            // surfaces the self-locating `RestartWindowZero`
2434            // diagnostic; canonical-form strictly precedes the cap arm
2435            // so a sub-millisecond above-cap value surfaces the more
2436            // fundamental round-trip-shape diagnostic first) and the
2437            // three peer typed-`Duration` sites that share this
2438            // canonical bracket ([`crate::MeshPolicy::timeout`],
2439            // [`crate::CircuitBreaker::window`],
2440            // [`crate::LimitsSpec::wall_clock`]). Every validated
2441            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2442            // (1ms..=1h), integer-millisecond granularity.
2443            crate::render::require_positive_canonical_bounded_duration(
2444                w,
2445                SUPERVISOR_RESTART_WINDOW_MAX,
2446                || SupervisorError::RestartWindowZero,
2447                SupervisorError::restart_window_not_canonical,
2448                SupervisorError::restart_window_exceeds_cap,
2449            )?;
2450        }
2451        // Route the per-child DNS-1123 / semver-requirement / duplicate-
2452        // detection fan-out loop through the lifted named per-slot gate
2453        // [`SupervisorSpec::validate_children`] rather than an inline
2454        // three-per-child cascade — every future consumer that wants to
2455        // re-check only the `:children` slot's per-entry axes (the M4
2456        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2457        // admission webhook re-validating one added/renamed child, the
2458        // future wasm-operator's per-child dynamic-add re-validator on
2459        // the `SimpleOneForOne` runtime-add path once dynamic-children
2460        // graduate to a typed slot, a future partial re-validator on a
2461        // per-`:children`-entry patch) reaches every per-entry axis
2462        // through one dispatch rather than re-inlining the three-arm
2463        // cascade in lockstep with `validate` or paying the peer
2464        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
2465        // reach one entry check. Sibling of the peer M3 mesh-slot
2466        // per-slot gate family (`validate_membros` — the exact peer on
2467        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
2468        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
2469        // `validate_placement`; `validate_politicas` routing through
2470        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
2471        // per-slot gate discipline now spans both the M3 mesh-slot
2472        // family and the M2 `:children` per-child-cascade axis on one
2473        // shape: one named per-slot gate per typed per-entry loop.
2474        self.validate_children()?;
2475        Ok(())
2476    }
2477
2478    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
2479    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
2480    /// gate, and duplicate-`:caixa` dedup arm into one call every
2481    /// consumer that wants to re-validate one `:children` entry (or the
2482    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
2483    /// admits reaches through.
2484    ///
2485    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
2486    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
2487    /// three-per-entry shape (DNS-1123 name + semver-requirement +
2488    /// duplicate-`:caixa` dedup), lifted to one named substrate
2489    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2490    /// materializer's admission webhook re-checking one added or renamed
2491    /// child, the future wasm-operator's per-child dynamic-add
2492    /// re-validator on the `SimpleOneForOne` runtime-add path once
2493    /// dynamic-children graduate to a typed slot, a future partial
2494    /// re-validator on a per-`:children`-entry patch — each reaches the
2495    /// three per-entry axes through this one dispatch rather than
2496    /// re-inlining the three-arm cascade in lockstep with `validate`
2497    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
2498    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
2499    /// reach one entry check.
2500    ///
2501    /// Self-contained on `&self` — resolves its own dedup `HashSet`
2502    /// through [`SupervisorSpec::children`] rather than borrowing one
2503    /// threaded down from `validate`, the same posture the peer M3
2504    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
2505    /// [`crate::AplicacaoSpec::validate_contratos`],
2506    /// [`crate::AplicacaoSpec::validate_entrada`],
2507    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
2508    /// consumer that reaches this gate directly (without first calling
2509    /// `validate`) still runs the full per-child cascade — pinned by
2510    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2511    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2512    /// + `validate_children_is_self_contained_on_children_slot`.
2513    ///
2514    /// The three per-entry arms run in the same canonical order the
2515    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
2516    /// the diagnostic every author-declared per-`:children` entry surfaces
2517    /// through `validate` is byte-equal to the diagnostic this gate
2518    /// surfaces when called directly — the equivalence-pin pair
2519    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2520    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2521    /// asserts the two altitudes discriminate the same set on every
2522    /// per-entry-covered input.
2523    pub fn validate_children(&self) -> Result<(), SupervisorError> {
2524        let mut seen = std::collections::HashSet::new();
2525        for child in self.children() {
2526            // Every emitted cluster artifact's `metadata.name` for a
2527            // supervised child derives from this `:children :caixa` value
2528            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
2529            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
2530            // label value on every child's pod identity, and the per-
2531            // child K8s [`Service`][svc] `metadata.name` the future
2532            // wasm-operator (M3) provisions for inter-child supervision
2533            // tree wiring. Each apiserver-side schema on each landing
2534            // site enforces the DNS-1123 label rule on admission; a
2535            // structurally invalid child name (`"Worker"`, `"my_worker"`,
2536            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
2537            // UUID-shaped mistaken-identity slug) silently passes the
2538            // prior empty-/duplicate-only gate and the failure surfaces
2539            // at `kubectl apply` time as a `metadata.name: Invalid value`
2540            // rejection, far from the source caixa.lisp, with no field
2541            // naming the offending `:children` entry. Lifting the gate
2542            // to caixa-build time mirrors the `:membros :caixa` value-
2543            // shape trajectory (3f9d7a0) and the `:placement :clusters`
2544            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
2545            // identifier axis — the supervisor tree's child names —
2546            // through the lifted
2547            // [`crate::render::require_valid_dns_1123_label`] gate the
2548            // seven peer name axes (`:membros :caixa`, `:placement
2549            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
2550            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
2551            // route through, so drift between the eight axes' accepted
2552            // DNS-1123-label sets is structurally impossible.
2553            //
2554            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
2555            crate::render::require_valid_dns_1123_label(
2556                child.nome(),
2557                || SupervisorError::EmptyChildName,
2558                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
2559            )?;
2560            // The author surface for `:children :versao` is the same
2561            // Cargo-shaped semver requirement string `:deps :versao` and
2562            // `:membros :versao` carry — and the lacre pipeline resolves
2563            // all three axes through the same
2564            // [`crate::version::parse_requirement`] entry-point. The
2565            // shared [`crate::render::require_valid_versao_requirement`]
2566            // helper brackets the empty-first + parse cascade both peer
2567            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
2568            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
2569            // :versao`) route through, so drift between the three axes'
2570            // accepted requirement sets is structurally impossible and
2571            // the parse-side no-op the empty-first arm closes (semver's
2572            // empty parse yields an implicit `*`) lives in exactly one
2573            // predicate. Every `ChildSpec::versao` past validate is
2574            // round-trippable through [`crate::parse_requirement`]
2575            // without re-checking at the resolver layer, and the three
2576            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
2577            // are now structurally equivalent by construction.
2578            crate::render::require_valid_versao_requirement(
2579                child.versao_requirement(),
2580                || SupervisorError::empty_child_version(child.nome()),
2581                |reason| {
2582                    SupervisorError::child_versao_invalid(
2583                        child.nome(),
2584                        child.versao_requirement(),
2585                        reason,
2586                    )
2587                },
2588            )?;
2589            crate::render::insert_first_seen(&mut seen, child.nome(), || {
2590                SupervisorError::duplicate_child_caixa(child.nome())
2591            })?;
2592        }
2593        Ok(())
2594    }
2595}
2596
2597/// Cross-slot coherence gate on the supervision tree: no
2598/// `:children :caixa` entry may name the supervisor's own `:nome`.
2599///
2600/// A supervisor that lists itself as a child is a degenerate self-parent
2601/// — the supervision tree is a DAG rooted at the supervisor (OTP child
2602/// specs reference *distinct* child processes; a supervisor is never its
2603/// own child), and the wasm-operator's hierarchical reconciliation would
2604/// otherwise be handed a node that is its own parent: a one-node cycle it
2605/// either rejects far from the source `caixa.lisp` or recurses on. Because
2606/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
2607/// lacre closure root), a child whose `:caixa` equals the supervisor's
2608/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
2609///
2610/// Lives outside [`SupervisorSpec::validate`] because the typed view
2611/// carries the children but not the parent `:nome`; mirrors the
2612/// cross-slot precedence gate `validate_upgrade_from_against_versao`
2613/// (which likewise reads one slot against another at the
2614/// [`crate::layout`] wire-up site) and the mesh self-edge gate
2615/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
2616/// node to itself is structurally not a tree/mesh edge" discipline, here
2617/// on the supervision-tree axis.
2618pub fn validate_no_self_supervision(
2619    children: &[ChildSpec],
2620    parent_nome: &str,
2621) -> Result<(), SupervisorError> {
2622    for child in children {
2623        if child.nome() == parent_nome {
2624            return Err(SupervisorError::child_supervises_self(parent_nome));
2625        }
2626    }
2627    Ok(())
2628}
2629
2630#[derive(Debug, Error, PartialEq, Eq)]
2631pub enum SupervisorError {
2632    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
2633    NoChildren { estrategia: RestartStrategy },
2634    #[error(
2635        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
2636    )]
2637    SimpleOneForOneWithStaticChildren,
2638    #[error(":max-restarts must be > 0")]
2639    ZeroMaxRestarts,
2640    #[error(
2641        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
2642         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
2643         restart-intensity policy into a no-op supervisor: the escalation threshold is \
2644         structurally so high that no realistic restarts-per-:restart-window traffic shape \
2645         can reach it, so the supervisor never escalates to its parent and a bad child can \
2646         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
2647         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
2648         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2649         materializer's admission webhook) emits a `:max-restarts` declaration that is \
2650         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
2651         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
2652         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
2653         band) or restructure the supervision tree (split the flaky child into its own \
2654         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
2655    )]
2656    MaxRestartsExceedsCap { max_restarts: u32 },
2657    #[error(
2658        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
2659         requires Period > 0; a zero window either trips on the first failure or \
2660         never trips depending on operator interpretation. Omit :restart-window to \
2661         express `never reset`; carry a positive duration to express the window."
2662    )]
2663    RestartWindowZero,
2664    #[error(
2665        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
2666         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
2667         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
2668         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
2669         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
2670    )]
2671    RestartWindowNotCanonical { window: Duration },
2672    #[error(
2673        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
2674         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
2675         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
2676         failure-counting window is structurally so long that transient restarts are never \
2677         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
2678         when the child has exceeded its restart budget within the recent window` to `trip the \
2679         parent when the child has exceeded its restart budget over its lifetime`, and the \
2680         supervisor's reset semantic never reaches the child — every typed-slot consumer \
2681         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
2682         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2683         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
2684         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
2685         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
2686         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
2687         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
2688         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
2689         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
2690         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
2691         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
2692         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
2693         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
2694         hiding it behind a rolling-window declaration the cap arm rejects)"
2695    )]
2696    RestartWindowExceedsCap { window: Duration },
2697    #[error("child entry has empty :caixa name")]
2698    EmptyChildName,
2699    #[error(
2700        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
2701         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
2702         name / label value the child name lands in — the per-child \
2703         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
2704         label value, and the future wasm-operator per-child Service `metadata.name` \
2705         — each apiserver-side schema rejects names that don't match; use a \
2706         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
2707    )]
2708    ChildCaixaInvalid { caixa: String, reason: String },
2709    #[error("child {caixa:?} has empty :versao constraint")]
2710    EmptyChildVersion { caixa: String },
2711    #[error(
2712        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
2713         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
2714         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
2715         `:membros :versao` carry; the lacre pipeline resolves all three \
2716         through the same parser)"
2717    )]
2718    ChildVersaoInvalid {
2719        caixa: String,
2720        versao: String,
2721        reason: String,
2722    },
2723    #[error(
2724        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
2725         child_spec.id per supervisor; duplicate children materialize as duplicate \
2726         ComputeUnits in the rendered chart, one silently overwriting the other)"
2727    )]
2728    DuplicateChildCaixa { caixa: String },
2729    #[error(
2730        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
2731         never its own child (the supervision tree is a DAG rooted at the supervisor; \
2732         OTP child specs reference distinct child processes). Since every :nome is a \
2733         globally-unique substrate identity, a child naming the supervisor's own :nome \
2734         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
2735         self-referential :children entry or rename it to the actual child caixa."
2736    )]
2737    ChildSupervisesSelf { caixa: String },
2738}
2739
2740// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
2741// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
2742// and [`validate_no_self_supervision`] onto one substrate primitive per
2743// typed variant — the sibling on `SupervisorError` of the four uniform-shape
2744// `LayoutError`-envelope constructor families the peer
2745// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
2746// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
2747// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
2748// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
2749// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
2750// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
2751// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
2752// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
2753// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
2754// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
2755// variants on `{ de, para }`) already at that discipline on the peer
2756// `AplicacaoError` envelopes.
2757//
2758// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
2759// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
2760// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
2761// self-supervision arm) opened the identical
2762// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
2763// the exact "same block re-inlined at every consumer" shape the PRIME
2764// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
2765// `AplicacaoError` families each closed on their sibling envelopes. The
2766// three variants share one `{ caixa: String }` shape, so the fold routes
2767// each wire-up site through one dispatch per typed variant.
2768//
2769// The macro below generates one static constructor per variant of shape
2770// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
2771// collapses onto one dispatch:
2772// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
2773// struct-literal on the same `&str` fixture. The uniform one-field
2774// construction (`caixa: caixa.to_string()`) is spelled once — inside the
2775// macro — rather than at every wire-up site. Every constructor is
2776// `#[must_use]` so a caller who mistakenly discards the constructed error
2777// trips a compile warning at the wire-up site.
2778//
2779// Every future consumer that wants to construct one of these three
2780// variants outside `SupervisorSpec::validate_children` /
2781// `validate_no_self_supervision` — a deferred
2782// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2783// webhook re-checking one added/renamed child, a future
2784// `feira validate --supervisor` per-caixa admission verb, a per-child
2785// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
2786// once dynamic-children graduate to a typed slot, a per-Supervisor
2787// overlay resolver rejecting a duplicate/self-supervising child against
2788// a cluster-local snapshot — now reaches each variant through one call
2789// rather than re-inlining the three-line struct-literal in lockstep
2790// with the three in-crate wire-up sites.
2791macro_rules! supervisor_caixa_only_ctors {
2792    ($($ctor:ident => $variant:ident),* $(,)?) => {
2793        impl SupervisorError {
2794            $(
2795                #[doc = concat!(
2796                    "Construct a [`SupervisorError::",
2797                    stringify!($variant),
2798                    "`] naming the offending `:children :caixa` (or ",
2799                    "supervisor `:nome`, on the self-supervision arm). ",
2800                    "Folds the uniform `Self::",
2801                    stringify!($variant),
2802                    " { caixa: caixa.to_string() }` one-field ",
2803                    "struct-literal onto one substrate primitive so ",
2804                    "every [`SupervisorSpec::validate_children`] / ",
2805                    "[`validate_no_self_supervision`] wire-up on this ",
2806                    "variant reads through one dispatch rather than the ",
2807                    "pre-lift open-coded struct-literal block."
2808                )]
2809                #[must_use]
2810                pub fn $ctor(caixa: &str) -> Self {
2811                    Self::$variant { caixa: caixa.to_string() }
2812                }
2813            )*
2814        }
2815    };
2816}
2817
2818supervisor_caixa_only_ctors! {
2819    empty_child_version => EmptyChildVersion,
2820    duplicate_child_caixa => DuplicateChildCaixa,
2821    child_supervises_self => ChildSupervisesSelf,
2822}
2823
2824// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
2825// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
2826// one substrate primitive per typed variant — the M2 supervisor-side siblings
2827// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
2828// already lifted through the sibling
2829// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
2830// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
2831// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
2832// String }` two-slot shape the peer seven-variant
2833// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
2834// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
2835// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
2836// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
2837// variant carries the `{ caixa: String, versao: String, reason: String }`
2838// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
2839// carries on the same `:versao` value-shape.
2840//
2841// Each of the two wire-up sites opened the same closure-shaped
2842// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
2843// [versao: child.versao_requirement().to_string(),] reason }` block inside
2844// the paired [`crate::render::require_valid_dns_1123_label`] and
2845// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
2846// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
2847// as a bug, on the same altitude the peer `AplicacaoError` /
2848// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
2849// families already closed on their sibling envelopes.
2850//
2851// The two `#[must_use]` inherent constructors below fold each wire-up onto
2852// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
2853// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
2854// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
2855// The uniform per-field `.to_string()` / `.into()` construction is spelled
2856// once — inside each ctor body — rather than at every wire-up site. The
2857// `reason: impl Into<String>` bound accepts both `&str` literals and
2858// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
2859// diagnostic shape at the lift, matching the peer
2860// [`aplicacao_field_reason_ctors!`] and
2861// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
2862// sibling envelopes.
2863//
2864// Every future consumer that wants to construct one of these two variants
2865// outside `SupervisorSpec::validate_children` — a deferred
2866// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
2867// re-checking one added/renamed child's `:caixa` or `:versao`, a future
2868// `feira validate --supervisor` per-caixa admission verb, a per-child
2869// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
2870// dynamic-children graduate to a typed slot, a per-Supervisor overlay
2871// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
2872// cluster-local snapshot — now reaches each variant through one call rather
2873// than re-inlining the per-shape struct-literal block in lockstep with the
2874// two in-crate wire-up sites.
2875impl SupervisorError {
2876    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
2877    /// offending `:children :caixa` value under the given `reason`. Folds
2878    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
2879    /// reason: reason.into() }` two-slot struct-literal onto one substrate
2880    /// primitive so every wire-up on this variant reads through one
2881    /// dispatch, matching the peer
2882    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
2883    /// sibling `AplicacaoError { caixa: String, reason: String }`
2884    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
2885    /// outputs through the `impl Into<String>` bound.
2886    #[must_use]
2887    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
2888        Self::ChildCaixaInvalid {
2889            caixa: caixa.to_string(),
2890            reason: reason.into(),
2891        }
2892    }
2893
2894    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
2895    /// offending `:children :caixa` and its `:versao` requirement under
2896    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
2897    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
2898    /// reason.into() }` three-slot struct-literal onto one substrate
2899    /// primitive so every wire-up on this variant reads through one
2900    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
2901    /// { caixa, versao, reason }` three-slot axis on the peer
2902    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
2903    /// and `format!(…)` outputs through the `impl Into<String>` bound.
2904    #[must_use]
2905    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
2906        Self::ChildVersaoInvalid {
2907            caixa: caixa.to_string(),
2908            versao: versao.to_string(),
2909            reason: reason.into(),
2910        }
2911    }
2912}
2913
2914// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
2915// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
2916// three bracket-arms — one struct-literal at the `:children`-empty
2917// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
2918// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
2919// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
2920// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
2921// [`crate::render::require_positive_canonical_bounded_duration`]
2922// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
2923// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
2924// primitive per typed variant, matching the sibling
2925// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
2926// variants on the same `{ <field>: Duration | u32 }` shape) at that
2927// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
2928// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
2929// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
2930// wire-up site through one dispatch per typed variant without a runtime-
2931// work delta.
2932//
2933// Each of the four wire-up sites opened the identical
2934// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
2935// exact "same block re-inlined at every consumer" shape the PRIME
2936// DIRECTIVE names as a bug, on the same altitude the peer
2937// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
2938// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
2939// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
2940// the fold routes each wire-up site through one dispatch per typed
2941// variant.
2942//
2943// The macro below generates one static constructor per variant of shape
2944// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
2945// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
2946// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
2947// fixture — as a direct call at the [`SupervisorSpec::validate`]
2948// `:children`-empty refusal, or as a bare function pointer in the
2949// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
2950// [`crate::render::require_positive_bounded_u32`] /
2951// [`crate::render::require_positive_canonical_bounded_duration`] gate
2952// carries — rather than the pre-lift open-coded one-line closure over
2953// the same one-field struct-literal. `const fn` preserves the `Copy`-
2954// pass-through's zero-runtime-work property verbatim. Every constructor
2955// is `#[must_use]` so a caller who mistakenly discards the constructed
2956// error trips a compile warning at the wire-up site.
2957//
2958// Every future consumer that wants to construct one of these four
2959// variants outside `SupervisorSpec::validate` — a deferred
2960// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2961// webhook re-checking one edited `:estrategia` / `:max-restarts` /
2962// `:restart-window` slot against the cap + canonical-form cascade, a
2963// future `feira validate --supervisor` per-caixa admission verb re-
2964// running the shape gates on demand, a per-Supervisor overlay resolver
2965// rejecting an author-supplied slot against a cluster-local snapshot —
2966// now reaches each variant through one call rather than re-inlining the
2967// per-shape struct-literal block in lockstep with the four in-crate
2968// wire-up sites.
2969macro_rules! supervisor_scalar_ctors {
2970    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
2971        impl SupervisorError {
2972            $(
2973                #[doc = concat!(
2974                    "Construct a [`SupervisorError::",
2975                    stringify!($variant),
2976                    "`] naming the offending per-`:supervisor` `",
2977                    stringify!($field),
2978                    "` scalar. Folds the uniform `Self::",
2979                    stringify!($variant),
2980                    " { ",
2981                    stringify!($field),
2982                    " }` one-field `Copy`-pass-through struct-literal onto ",
2983                    "one substrate primitive so every per-axis wire-up on ",
2984                    "this variant reads through one dispatch — as a direct ",
2985                    "call (`SupervisorError::",
2986                    stringify!($ctor),
2987                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
2988                    "the same `Copy`-`",
2989                    stringify!($ty),
2990                    "` fixture) or as a bare function pointer in the ",
2991                    "`impl FnOnce(",
2992                    stringify!($ty),
2993                    ") -> SupervisorError` bracket-closure slot every ",
2994                    "`crate::render::require_positive_bounded_*` / ",
2995                    "`crate::render::require_positive_canonical_bounded_*` ",
2996                    "gate carries — rather than the pre-lift open-coded ",
2997                    "one-line closure over the same one-field struct-",
2998                    "literal. `const fn` preserves the `Copy`-pass-through's ",
2999                    "zero-runtime-work property verbatim."
3000                )]
3001                #[must_use]
3002                pub const fn $ctor($field: $ty) -> Self {
3003                    Self::$variant { $field }
3004                }
3005            )*
3006        }
3007    };
3008}
3009
3010supervisor_scalar_ctors! {
3011    no_children => NoChildren { estrategia: RestartStrategy },
3012    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
3013    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
3014    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
3015}
3016
3017/// Shared duration string codec for the typed slots that take a
3018/// duration (`restart_window`, `MeshPolicy::timeout`,
3019/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
3020/// reuse it without duplicating the parser.
3021pub mod duration_codec {
3022    use super::Duration;
3023    use serde::{Deserializer, Serializer};
3024
3025    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
3026        // Route through the canonical [`crate::render::serialize_option_via_str`]
3027        // — the substrate-side single-owner primitive for the forward
3028        // arm of the typed-magnitude codec family. See its docstring
3029        // for the full sibling roster.
3030        crate::render::serialize_option_via_str(v, s, render)
3031    }
3032
3033    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
3034        // Route through the canonical [`crate::render::deserialize_option_via_str`]
3035        // — the substrate-side single-owner primitive for the reverse
3036        // arm of the typed-magnitude codec family. See its docstring
3037        // for the full sibling roster.
3038        crate::render::deserialize_option_via_str(d, parse)
3039    }
3040
3041    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
3042        // Paired whitespace-rejection arm — same canonical-form
3043        // render-determinism discipline as the peer
3044        // `limits::parse_byte_size` / `limits::parse_duration` /
3045        // `limits::parse_millicores` /
3046        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
3047        // byte-scan closes the WhatWG-conformant whitespace bytes
3048        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
3049        // `char::is_whitespace` scan closes the strictly-complementary
3050        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
3051        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
3052        // codepoints) that `str::trim` at parse entry silently strips.
3053        // Either drift class would round-trip through `render` to a
3054        // *different* canonical form on next emit — breaking the
3055        // THEORY.md Part V render-determinism contract on three typed-
3056        // duration slots at once (`:supervisor :restart-window`,
3057        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
3058        // via the shared codec.
3059        //
3060        // Routed through the lifted [`crate::render::reject_whitespace`]
3061        // primitive — the substrate-side single-owner paired-arm gate
3062        // every typed-magnitude codec in caixa-core shares.
3063        crate::render::reject_whitespace::<String, _, _>(
3064            s,
3065            |b| {
3066                format!(
3067                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
3068                 authoring form for the typed duration slots routed through this shared codec \
3069                 (`:supervisor :restart-window`, `:politicas :timeout`, \
3070                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3071                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
3072                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
3073                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
3074                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
3075                 Part V render-determinism contract every typed slot carries. Strip every \
3076                 whitespace byte (write `\"30s\"` verbatim)"
3077                )
3078            },
3079            |ch| {
3080                format!(
3081                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
3082                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
3083                 duration slots routed through this shared codec (`:supervisor \
3084                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
3085                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
3086                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
3087                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
3088                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
3089                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
3090                 `White_Space` property, strictly wider than the ASCII byte set) silently \
3091                 strips it at parse entry, and the value round-trips through `render` to \
3092                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
3093                 the THEORY.md Part V render-determinism contract every typed slot \
3094                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
3095                 verbatim with only ASCII bytes)",
3096                    cp = ch as u32
3097                )
3098            },
3099        )?;
3100        let s = s.trim();
3101        // Routed through the lifted
3102        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
3103        // the single-owner split every ASCII-alphabetic-unit typed-
3104        // magnitude codec in caixa-core (`limits::parse_byte_size` /
3105        // `limits::parse_duration` / this shared duration codec) shares.
3106        // See its docstring for the full sibling roster on the same
3107        // primitive altitude.
3108        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
3109        let num_trim = num_part.trim();
3110        // The canonical authoring form for every typed slot routed
3111        // through this shared codec — `:supervisor :restart-window`,
3112        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
3113        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
3114        // non-negative integer with no decimal point and no leading
3115        // sign, so the parser's accepted set must match for
3116        // serialize/deserialize to round-trip without canonical-form
3117        // drift. Until this gate landed the parser accepted any
3118        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
3119        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
3120        // tripped the value to a *different* canonical string on the
3121        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
3122        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
3123        // — breaking the THEORY.md Part V render-determinism contract
3124        // on three typed slots at once. Same canonical-form discipline
3125        // `crate::limits::parse_duration` (818dd38, the immediate
3126        // predecessor on the peer `:limits :wall-clock` codec) applies;
3127        // this gate lifts the discipline onto the shared codec that
3128        // backs the remaining three typed-duration slots in caixa-core.
3129        //
3130        // Strict canonical form: every byte of the magnitude is an
3131        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
3132        // inputs the gate distinguishes "non-canonical-but-numeric"
3133        // (parses as f64 or i64 — surfaced with a self-locating
3134        // diagnostic naming the canonical authoring form, the
3135        // round-trip drift each rejected shape would produce on first
3136        // serialize, and the canonical-form remediation) from
3137        // "garbage" (parses as neither — surfaced with the existing
3138        // narrower "bad duration magnitude" wording so its diagnostic
3139        // shape remains stable for the parser-shape footgun case).
3140        // The pre-existing `num < 0.0` arm is now unreachable — the
3141        // digit-only gate strictly precedes magnitude parsing, and a
3142        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
3143        // non-canonical-but-numeric branch with the `-30` named
3144        // verbatim in the diagnostic rather than the prior
3145        // value-laundered "negative duration in \"-30s\"" wording.
3146        //
3147        // Routed through the lifted
3148        // [`crate::render::is_digit_only_magnitude`] predicate — the
3149        // same source of truth the four peer typed-magnitude codec
3150        // sites share.
3151        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
3152        if !digit_only {
3153            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
3154            if numeric {
3155                return Err(format!(
3156                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
3157                     canonical authoring form for the typed duration slots routed through \
3158                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3159                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3160                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
3161                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
3162                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
3163                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
3164                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
3165                     THEORY.md Part V render-determinism contract every typed slot carries. \
3166                     Pick an integer magnitude in the unit that divides cleanly (write \
3167                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
3168                ));
3169            }
3170            return Err(format!("bad duration magnitude in {s:?}"));
3171        }
3172        // Leading-zero arm — peer with the `rate_limit_codec` leading-
3173        // zero arm (4f46830) on the same canonical-form render-
3174        // determinism axis. The digit-only gate accepts `"030s"`,
3175        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
3176        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
3177        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
3178        // *different* canonical string on the next emit, breaking the
3179        // THEORY.md Part V render-determinism contract the same way
3180        // `"+30s"` did before the leading-`+` arm landed. The single-
3181        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
3182        // losslessly through `render` (`render(Duration::ZERO)` emits
3183        // `"0s"`) — the downstream semantic-zero gates (e.g.
3184        // `SupervisorError::ZeroRestartWindow` on
3185        // `:supervisor :restart-window`,
3186        // `AplicacaoError::PolicyTimeoutZero` /
3187        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
3188        // duration slots) refuse zero-magnitude authoring at the typed-
3189        // validate layer above, so the single-byte `"0"` stays in the
3190        // accepted set at this codec layer and the diagnostic
3191        // partitioning between canonical-form drift (this arm) and
3192        // semantic-zero (the downstream gates) remains stable.
3193        // Peer with the future leading-zero arms on the two remaining
3194        // typed-magnitude codecs the trajectory acknowledges:
3195        // `limits::parse_duration` backing `:limits :wall-clock`,
3196        // `limits::parse_byte_size` backing `:limits :memory` — each
3197        // carries the same canonical-form-drift class today; this
3198        // gate lands the discipline on the shared duration codec
3199        // first because the `rate_limit_codec` predecessor on the
3200        // same canonical-form-drift axis is the closest peer on the
3201        // trajectory.
3202        //
3203        // Routed through the lifted
3204        // [`crate::render::is_leading_zero_padded_magnitude`]
3205        // predicate — the same source of truth the four peer
3206        // typed-magnitude codec sites share.
3207        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
3208            return Err(format!(
3209                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
3210                 canonical authoring form for the typed duration slots routed through \
3211                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3212                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3213                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
3214                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
3215                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
3216                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
3217                 serialize — breaking the THEORY.md Part V render-determinism contract \
3218                 every typed slot carries. Strip the leading zeros (write \
3219                 `\"30s\"` instead of `\"030s\"`)"
3220            ));
3221        }
3222        // The digit-only gate guarantees every byte is `[0-9]`, and
3223        // the leading-zero arm above guarantees the magnitude is
3224        // either the single byte `"0"` or starts with `[1-9]`, so
3225        // the only way `u64::from_str` can fail here is overflow (the
3226        // magnitude exceeds `u64::MAX`). Surface that with an
3227        // overflow-shaped wording so the diagnostic names the offending
3228        // magnitude verbatim rather than collapsing onto the
3229        // non-canonical arm. The codec now operates on `u64` end-to-end
3230        // — every accepted magnitude is integer-exact; no f64 mantissa
3231        // drift between author-supplied magnitude and the consumer's
3232        // `Duration` value. Same shape `crate::limits::parse_duration`
3233        // (818dd38) carries on the peer `:limits :wall-clock` axis.
3234        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
3235            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
3236        })?;
3237        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
3238        // unit-arm dispatch through the canonical
3239        // [`crate::render::duration_from_integer_magnitude_and_unit`]
3240        // primitive — the substrate-side single-owner unit-dispatch
3241        // table every typed-duration codec in caixa-core routes
3242        // through (peer: `crate::limits::parse_duration` backing
3243        // `:limits :wall-clock`). Every unit conversion is integer-
3244        // exact for an integer magnitude; overflow surfaces via the
3245        // typed `DurationUnitError::Overflow { multiplier }`
3246        // discriminant so this arm reconstructs the pre-lift
3247        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
3248        // wording verbatim from `num` / `unit_trim` / the returned
3249        // `multiplier`, and the unknown-unit arm reconstructs the
3250        // pre-lift `"unknown duration unit \"<other>\""` wording from
3251        // the caller-scoped `unit_trim`. Load-bearing pinned by
3252        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
3253        let unit_trim = unit.trim();
3254        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
3255            |e| match e {
3256                crate::render::DurationUnitError::Overflow { multiplier } => format!(
3257                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
3258                ),
3259                crate::render::DurationUnitError::UnknownUnit => {
3260                    format!("unknown duration unit {unit_trim:?}")
3261                }
3262            },
3263        )?;
3264        Ok(dur)
3265    }
3266
3267    /// Render a [`Duration`] in the canonical pleme-io duration string
3268    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
3269    /// caixa typed-duration slot serializes to and the same form K8s
3270    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
3271    /// EnvoyConfig per-route timeouts both expect (an integer
3272    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
3273    /// `+`). Lifted to `pub` so caixa-side renderers
3274    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
3275    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
3276    /// emitter, the future caixa-otel collector pipeline emitter) can
3277    /// consume the same canonical formatter without re-inlining the
3278    /// magnitude/unit decision tree (and inheriting the same drift
3279    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
3280    /// downstream apply-time parsing in non-obvious ways).
3281    pub fn render(d: Duration) -> String {
3282        let total_ms = d.as_millis();
3283        if total_ms == 0 {
3284            return "0s".into();
3285        }
3286        if total_ms.is_multiple_of(3600 * 1000) {
3287            return format!("{}h", total_ms / (3600 * 1000));
3288        }
3289        if total_ms.is_multiple_of(60 * 1000) {
3290            return format!("{}m", total_ms / (60 * 1000));
3291        }
3292        if total_ms.is_multiple_of(1000) {
3293            return format!("{}s", total_ms / 1000);
3294        }
3295        format!("{total_ms}ms")
3296    }
3297
3298    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
3299    ///
3300    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
3301    /// largest divisor unit, so any sub-millisecond residue
3302    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
3303    /// §V.2.7 render-determinism contract:
3304    ///
3305    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
3306    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
3307    ///     `1_000_000` ns ≠ original `1_500_000` ns;
3308    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
3309    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
3310    ///     on every typed-`Duration` slot then rejects on re-validate.
3311    ///
3312    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
3313    /// the codec's round-trippable accepted set lives in exactly one place —
3314    /// every typed-`Duration` slot that routes through this shared codec
3315    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
3316    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
3317    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
3318    /// every typed-`Duration` slot whose own codec shares the same
3319    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
3320    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
3321    /// pair) calls this predicate from its `validate()` to bracket the
3322    /// accepted set against the codec's accepted set, structurally. Drift
3323    /// between the codec's granularity and any typed slot's accepted set is
3324    /// then a single-source-of-truth edit at this predicate rather than a
3325    /// silent round-trip break the next consumer discovers at apply time.
3326    ///
3327    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
3328    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
3329    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
3330    /// family — same "typed-slot's valid set matches its codec's accepted
3331    /// set, structurally" discipline carried at the codec layer.
3332    #[must_use]
3333    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
3334        d.subsec_nanos().is_multiple_of(1_000_000)
3335    }
3336}
3337
3338/// Required-Duration variant for fields that aren't Option<Duration>.
3339pub mod duration_codec_required {
3340    use super::Duration;
3341    use serde::{Deserialize, Deserializer, Serializer};
3342
3343    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
3344        s.serialize_str(&super::duration_codec::render(*v))
3345    }
3346
3347    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
3348        let s = String::deserialize(d)?;
3349        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
3350    }
3351}
3352
3353#[cfg(test)]
3354mod tests {
3355    use super::*;
3356
3357    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
3358        ChildSpec {
3359            caixa: name.into(),
3360            versao: ver.into(),
3361            restart,
3362        }
3363    }
3364
3365    #[test]
3366    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
3367        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
3368        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
3369        // posture. Each accessor projects the per-`:children :caixa`
3370        // / per-`:children :versao` [`String`] storage through the
3371        // `pub const fn` [`String::as_str`] (const-stable since Rust
3372        // 1.87, well within the workspace MSRV) — any future
3373        // accidental downgrade to non-`const` fails the corresponding
3374        // `<name>_via_const_fn` wrapper at caixa-core build time with
3375        // E0015 (`cannot call non-const method`), strictly stronger
3376        // than a runtime `assert!`. Sibling of the peer
3377        // per-M2/M3/universal-axis `String → &str` scalar-accessor
3378        // family pins on the sibling `const`-eval-surface passes
3379        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
3380        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
3381        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
3382        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
3383        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
3384        // [`crate::aplicacao::Entrada::destination`] at the M3
3385        // ingress axis,
3386        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
3387        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
3388        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
3389        // axis, and the per-`:contratos`
3390        // [`crate::aplicacao::WitContract::source`] /
3391        // [`crate::aplicacao::WitContract::destination`] /
3392        // [`crate::aplicacao::WitContract::world_ref`] trio the
3393        // sibling pin at 279823b already anchors).
3394        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
3395            c.nome()
3396        }
3397        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
3398            c.versao_requirement()
3399        }
3400        for (caixa, versao) in [
3401            ("worker-a", "^0.1"),
3402            ("worker-b", "~0.2.3"),
3403            ("collector", "*"),
3404        ] {
3405            let c = child(caixa, versao, RestartPolicy::Permanent);
3406            assert_eq!(nome_via_const_fn(&c), c.nome());
3407            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
3408            assert_eq!(c.nome(), caixa);
3409            assert_eq!(c.versao_requirement(), versao);
3410        }
3411    }
3412
3413    #[test]
3414    fn supervisor_children_slice_return_accessor_is_const_fn() {
3415        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
3416        // `const`-eval-surface posture. The accessor destructures the
3417        // per-`:children` `Vec<ChildSpec>` storage through the
3418        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
3419        // 1.66, well within the workspace MSRV) — any future
3420        // accidental downgrade to non-`const` fails
3421        // `children_via_const_fn` at caixa-core build time with E0015
3422        // (`cannot call non-const method`), strictly stronger than a
3423        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
3424        // `Vec → &[T]` slice-return accessor family pin
3425        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
3426        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
3427        // per-`:membros` / per-`:contratos` slice-return axes, and of
3428        // the peer M2 upgrade-appup axis pin
3429        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
3430        // on the per-`:upgrade-from :instructions` slice-return axis.
3431        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
3432            s.children()
3433        }
3434        // Sweep both the empty-children (leaf-supervisor with no
3435        // static children — the `SimpleOneForOne` dynamic-child
3436        // arm's canonical shape) and the populated-children
3437        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
3438        // arm's canonical shape) axes so the accessor carries a
3439        // const-dispatch pin on both arms.
3440        let s_empty = SupervisorSpec {
3441            estrategia: RestartStrategy::SimpleOneForOne,
3442            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3443            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3444            children: vec![],
3445        };
3446        assert!(children_via_const_fn(&s_empty).is_empty());
3447        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
3448        let s_full = SupervisorSpec {
3449            estrategia: RestartStrategy::OneForOne,
3450            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3451            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3452            children: vec![
3453                child("worker-a", "^0.1", RestartPolicy::Permanent),
3454                child("worker-b", "~0.2.3", RestartPolicy::Transient),
3455                child("collector", "*", RestartPolicy::Temporary),
3456            ],
3457        };
3458        assert_eq!(children_via_const_fn(&s_full).len(), 3);
3459        assert_eq!(children_via_const_fn(&s_full), s_full.children());
3460    }
3461
3462    #[test]
3463    fn default_has_one_for_one_and_5_restarts_in_60s() {
3464        let s = SupervisorSpec::default();
3465        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
3466        assert_eq!(s.max_restarts, 5);
3467        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
3468        assert!(s.children.is_empty());
3469    }
3470
3471    #[test]
3472    fn validate_one_for_one_requires_children() {
3473        let mut s = SupervisorSpec::default();
3474        s.children = vec![];
3475        assert!(matches!(
3476            s.validate().unwrap_err(),
3477            SupervisorError::NoChildren { .. }
3478        ));
3479        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
3480        s.validate().unwrap();
3481    }
3482
3483    #[test]
3484    fn validate_simple_one_for_one_forbids_static_children() {
3485        let mut s = SupervisorSpec {
3486            estrategia: RestartStrategy::SimpleOneForOne,
3487            ..SupervisorSpec::default()
3488        };
3489        s.children
3490            .push(child("w", "^0.1", RestartPolicy::Permanent));
3491        assert_eq!(
3492            s.validate().unwrap_err(),
3493            SupervisorError::SimpleOneForOneWithStaticChildren
3494        );
3495        s.children.clear();
3496        s.validate().unwrap();
3497    }
3498
3499    #[test]
3500    fn validate_rejects_zero_max_restarts() {
3501        let s = SupervisorSpec {
3502            max_restarts: 0,
3503            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3504            ..SupervisorSpec::default()
3505        };
3506        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
3507    }
3508
3509    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
3510    //
3511    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
3512    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
3513    // `:supervisor :max-restarts` axis — both fields are "trip the
3514    // next-higher protection layer after N events in a rolling window"
3515    // counters with identical degenerate-at-the-high-end shape, so the
3516    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
3517    // exactly as it lies in `1..=1000` on the breaker side.
3518
3519    #[test]
3520    fn validate_rejects_max_restarts_above_cap() {
3521        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
3522        // 1` is structurally one past the cap and silently passed
3523        // validate on every pre-gate codebase because the typed slot's
3524        // only check was the zero-floor arm. The no-op-supervisor vector
3525        // only surfaced at the runtime substrate (Erlang/OTP
3526        // MaxIntensity/Period ratio, the future wasm-operator's
3527        // per-supervisor restart-intensity counter) far from the source
3528        // caixa.lisp with no field naming the offending supervisor.
3529        let s = SupervisorSpec {
3530            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3531            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3532            ..SupervisorSpec::default()
3533        };
3534        assert_eq!(
3535            s.validate().unwrap_err(),
3536            SupervisorError::MaxRestartsExceedsCap {
3537                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3538            }
3539        );
3540    }
3541
3542    #[test]
3543    fn validate_rejects_max_restarts_far_above_cap() {
3544        // The `u32::MAX` worst case — the four-billion-restart
3545        // threshold a typo (`:max-restarts 4294967295`) or a
3546        // struct-literal copy-paste lands in the slot. Pin the cap
3547        // arm's coverage explicitly across the full `u32` overflow so
3548        // a future relaxation that drops the upper bound surfaces
3549        // here. Same shape every other typed-cap arm on this surface
3550        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
3551        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
3552        let s = SupervisorSpec {
3553            max_restarts: u32::MAX,
3554            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3555            ..SupervisorSpec::default()
3556        };
3557        assert_eq!(
3558            s.validate().unwrap_err(),
3559            SupervisorError::MaxRestartsExceedsCap {
3560                max_restarts: u32::MAX,
3561            }
3562        );
3563    }
3564
3565    #[test]
3566    fn validate_accepts_max_restarts_at_cap() {
3567        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
3568        // must validate. The cap is inclusive on the top edge,
3569        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
3570        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
3571        // discipline on the sibling capped axes. Pin the boundary
3572        // explicitly so a future off-by-one tightening
3573        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
3574        // here as a test failure rather than a silent contract
3575        // narrowing.
3576        let s = SupervisorSpec {
3577            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
3578            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3579            ..SupervisorSpec::default()
3580        };
3581        s.validate()
3582            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
3583    }
3584
3585    #[test]
3586    fn validate_accepts_max_restarts_typical_values() {
3587        // The documented production-playbook band positive-control
3588        // sweep — every value Erlang/OTP / Elixir / Riak Core /
3589        // RabbitMQ recommend (1..=100) must pass, plus a sweep
3590        // through the hyperscale band (200, 500, 1000) the cap
3591        // accepts. Pin the inclusive validated set explicitly so a
3592        // future tightening of the ceiling surfaces here.
3593        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
3594            let s = SupervisorSpec {
3595                max_restarts: n,
3596                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3597                ..SupervisorSpec::default()
3598            };
3599            s.validate()
3600                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
3601        }
3602    }
3603
3604    #[test]
3605    fn zero_max_restarts_takes_precedence_over_cap() {
3606        // The cross-arm ordering pin: `0` is structurally outside
3607        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
3608        // (cap), but the zero-floor diagnostic is the more
3609        // self-locating one (it directly names the counter-axis
3610        // remediation), so the validate gate must fire on zero first.
3611        // Same shape every other zero-then-shape ordering on this
3612        // surface uses (PolicyRetriesZero then
3613        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
3614        // PolicyBreakerMaxFailuresExceedsCap).
3615        let s = SupervisorSpec {
3616            max_restarts: 0,
3617            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3618            ..SupervisorSpec::default()
3619        };
3620        assert_eq!(
3621            s.validate().unwrap_err(),
3622            SupervisorError::ZeroMaxRestarts,
3623            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
3624        );
3625    }
3626
3627    #[test]
3628    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
3629        // The cross-arm ordering pin between the cap and the sibling
3630        // `:restart-window` gates (zero-window, canonical-window). A
3631        // supervisor carrying both an over-cap `max_restarts` AND a
3632        // structurally invalid window (zero, sub-ms) must surface the
3633        // cap diagnostic first — the cap arm is wired immediately
3634        // after the zero-restart arm and strictly before the window
3635        // arms, so the offending value the diagnostic names matches
3636        // the order the author would discover the gates by reading
3637        // top-to-bottom through `SupervisorSpec::validate`. Pin the
3638        // order so a future refactor that reorders the arms surfaces
3639        // here as a test failure rather than a silent diagnostic
3640        // regression. Peer of
3641        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
3642        // on the sibling `:politicas :circuit-breaker` slot.
3643        let s = SupervisorSpec {
3644            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3645            restart_window: Some(Duration::ZERO),
3646            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3647            ..SupervisorSpec::default()
3648        };
3649        assert_eq!(
3650            s.validate().unwrap_err(),
3651            SupervisorError::MaxRestartsExceedsCap {
3652                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3653            },
3654            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
3655        );
3656    }
3657
3658    #[test]
3659    fn max_restarts_cap_diagnostic_carries_offending_value() {
3660        // The diagnostic-shape pin: the offending `u32` is carried
3661        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
3662        // variant so the surfaced error message names the value the
3663        // author wrote (`":supervisor :max-restarts (50000) exceeds the
3664        // supervisor-policy ceiling …"`), not just the cap. Same
3665        // self-locating diagnostic shape every other typed-cap arm on
3666        // this surface carries
3667        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
3668        // the offending failure count verbatim,
3669        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
3670        // retries count verbatim).
3671        let s = SupervisorSpec {
3672            max_restarts: 50_000,
3673            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3674            ..SupervisorSpec::default()
3675        };
3676        let err = s.validate().unwrap_err();
3677        assert!(
3678            matches!(
3679                err,
3680                SupervisorError::MaxRestartsExceedsCap {
3681                    max_restarts: 50_000
3682                }
3683            ),
3684            "got {err:?}"
3685        );
3686        let msg = err.to_string();
3687        assert!(
3688            msg.contains("50000"),
3689            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
3690        );
3691    }
3692
3693    #[test]
3694    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
3695        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
3696        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
3697        // half of Learn You Some Erlang's worker-supervisor default,
3698        // sibling of the `60s` `Period` half that the paired
3699        // [`Default for SupervisorSpec`] impl already pins on the
3700        // sibling `restart_window` axis. Pinning the literal here
3701        // surfaces a future rebrand (a tightening to Elixir's `3`,
3702        // a widening to a per-cluster overlay the operator pins
3703        // through a future `:max-restarts-overrides` slot) as a
3704        // deliberate test edit, not a silent contract migration.
3705        // Peer of the sibling
3706        // [`supervisor_max_restarts_cap_pins_canonical_value`]
3707        // upper-bracket pin on the same axis.
3708        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
3709    }
3710
3711    #[test]
3712    fn default_max_restarts_helper_routes_through_lifted_default() {
3713        // Composition pin: the private `default_max_restarts()`
3714        // serde-`#[serde(default = "…")]` helper on
3715        // [`SupervisorSpec::max_restarts`] must route through the
3716        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3717        // typed `pub const` rather than a raw `5` literal. Prior to
3718        // the lift the helper carried an inline `5` with no compile-
3719        // time link back to the shared default, so the wire-format
3720        // author-omitted arm and the caixa-core
3721        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
3722        // arm could silently split on any future default rebrand.
3723        // Byte-parity against the lifted constant closes the split.
3724        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
3725    }
3726
3727    #[test]
3728    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
3729        // Composition pin: the [`Default for SupervisorSpec`] impl's
3730        // struct-literal `max_restarts` field must route through the
3731        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3732        // typed `pub const` (via the private helper this test's
3733        // sibling `default_max_restarts_helper_routes_through_lifted_default`
3734        // already pins onto the constant). Structurally: every
3735        // `SupervisorSpec::default()` call must yield a
3736        // `max_restarts` field byte-equal to the lifted constant
3737        // (the two paired defaults — the serde-side wire-format arm
3738        // and the struct-literal default arm — cannot silently split
3739        // on any future default rebrand). Peer of the sibling
3740        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
3741        // — this pin closes the byte-parity arm on the two paired
3742        // altitude entry points onto the shared substrate constant.
3743        assert_eq!(
3744            SupervisorSpec::default().max_restarts(),
3745            SUPERVISOR_MAX_RESTARTS_DEFAULT,
3746        );
3747    }
3748
3749    #[test]
3750    fn supervisor_restart_window_default_pins_otp_canonical_value() {
3751        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
3752        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
3753        // Learn You Some Erlang's worker-supervisor default, paired
3754        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
3755        // `MaxIntensity` half this constant is the sliding-window
3756        // denominator of on the same `MaxIntensity / Period`
3757        // restart-intensity ratio. Pinning the literal here surfaces a
3758        // future coherent rebrand of the paired default (Elixir's
3759        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
3760        // the operator pins through a future
3761        // `:restart-window-overrides` slot) as a deliberate test edit,
3762        // not a silent contract migration. Peer of the sibling
3763        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
3764        // paired-half pin on the same OTP-canonical default and the
3765        // [`supervisor_restart_window_cap_pins_canonical_value`]
3766        // upper-bracket pin on the same axis.
3767        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
3768    }
3769
3770    #[test]
3771    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
3772        // Composition pin: the [`Default for SupervisorSpec`] impl's
3773        // struct-literal `restart_window` field must route through the
3774        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3775        // typed `pub const` rather than a raw
3776        // `Duration::from_secs(60)` literal. Prior to this lift the
3777        // paired `{intensity, 5, 60}` OTP-canonical default was split
3778        // across two altitudes with no compile-time link between the
3779        // halves — the `MaxIntensity` half rode through the lifted
3780        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
3781        // `Period` half rode as an open-coded literal at the
3782        // composition site, so a future coherent rebrand of the paired
3783        // canonical would have had to migrate one half through the
3784        // constant and the other through a raw literal in lockstep.
3785        // Byte-parity against the lifted constant on the `Period` half
3786        // closes the split — the paired OTP-canonical default now
3787        // migrates as one unit on any future axis change. Peer of the
3788        // sibling
3789        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3790        // byte-parity pin on the paired `MaxIntensity` half.
3791        assert_eq!(
3792            SupervisorSpec::default().restart_window(),
3793            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3794        );
3795    }
3796
3797    #[test]
3798    fn supervisor_estrategia_default_pins_otp_canonical_value() {
3799        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
3800        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
3801        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
3802        // canonical default, paired with the sibling
3803        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
3804        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
3805        // this constant is the strategy discriminator of on the same
3806        // OTP-canonical worker-supervisor default. Pinning the arm here
3807        // surfaces a future coherent rebrand of the paired triple (Elixir's
3808        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
3809        // intensity/period axes leaving this strategy arm untouched, an OTP
3810        // `rest_for_one` widening once the substrate discovers startup-
3811        // order-coupled child cohorts as the more common worker-supervisor
3812        // shape, a per-cluster overlay the operator pins through a future
3813        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
3814        // supervision-canary roadmap acknowledges) as a deliberate test
3815        // edit, not a silent contract migration. Peer of the sibling
3816        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
3817        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3818        // paired-half pins on the same OTP-canonical default.
3819        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
3820    }
3821
3822    #[test]
3823    fn restart_strategy_default_routes_through_lifted_default() {
3824        // Composition pin: the [`Default for RestartStrategy`] impl's
3825        // return arm must route through the substrate-canonical
3826        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
3827        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
3828        // an inline `Self::OneForOne` with no compile-time link back to
3829        // the shared OTP-canonical `one_for_one` strategy the paired
3830        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
3831        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
3832        // `.unwrap_or_default()` (now
3833        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
3834        // so a future rebrand of the OTP-canonical strategy default (an
3835        // OTP `rest_for_one` widening once the substrate discovers
3836        // startup-order-coupled child cohorts as the more common worker-
3837        // supervisor shape, a per-cluster overlay the operator pins
3838        // through a future `:estrategia-overrides` slot) would have had to
3839        // be threaded through the `Default` impl and the two peer routes
3840        // in lockstep or the three consumers would silently split. Byte-
3841        // parity against the lifted constant closes the split. Peer of
3842        // the sibling
3843        // [`default_max_restarts_helper_routes_through_lifted_default`] +
3844        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3845        // composition pins on the paired `MaxIntensity` + `Period` halves.
3846        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
3847    }
3848
3849    #[test]
3850    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
3851        // Composition pin: the [`Default for SupervisorSpec`] impl's
3852        // struct-literal `estrategia` field must route through the
3853        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
3854        // `pub const` (either directly, or via the
3855        // [`RestartStrategy::default`] impl that the sibling
3856        // `restart_strategy_default_routes_through_lifted_default` pin
3857        // already routes onto the constant). Structurally: every
3858        // `SupervisorSpec::default()` call must yield an `estrategia`
3859        // field byte-equal to the lifted constant (the three paired
3860        // defaults — the [`Default for RestartStrategy`] impl arm, the
3861        // struct-literal default arm here, and the
3862        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
3863        // silently split on any future default rebrand). Peer of the
3864        // sibling
3865        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3866        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3867        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
3868        // of the same `SupervisorSpec::default()` composed altitude.
3869        assert_eq!(
3870            SupervisorSpec::default().estrategia(),
3871            SUPERVISOR_ESTRATEGIA_DEFAULT,
3872        );
3873    }
3874
3875    #[test]
3876    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
3877        // Composition pin: the [`Default for SupervisorSpec`] impl must
3878        // route through the substrate-canonical
3879        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
3880        // rather than a re-hand-authored struct-literal cascade. Sharpens
3881        // the sibling per-arm
3882        // `supervisor_spec_default_*_routes_through_lifted_default` pins
3883        // from a per-field lift into a whole-struct one-source-of-truth
3884        // pin — the derived-until-now [`Default::default`] and the
3885        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
3886        // construction, not by coincidence.
3887        //
3888        // A future extension of the OTP-canonical baseline (a fifth
3889        // `restart_intensity` field the Erlang/OTP `#supervisor` record
3890        // grows, a per-child-cohort split of the `restart_window` /
3891        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
3892        // CR materializer's admission-time overlay pass) reaches both
3893        // paths through exactly one edit on
3894        // [`SupervisorSpec::otp_canonical`] — the derived path could
3895        // silently disagree with the constructor's shape on any new
3896        // field whose [`Default::default`] resolves to a different arm
3897        // than the OTP-canonical baseline the constructor names, while
3898        // this delegated impl reaches the constructor directly and
3899        // picks up every future extension by construction.
3900        //
3901        // Fourth peer on the M2 / M3 typed-slot-spec
3902        // [`Default`]-through-const-ctor fold family — sibling of the
3903        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
3904        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
3905        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
3906        // (91641a4), and [`crate::BehaviorSpec`]
3907        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
3908        // per-`Option`-only-typed-slot folds — extended here onto the
3909        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
3910        // is not "everything `None`" but the Erlang/OTP-canonical
3911        // `{one_for_one, 5, 60}` worker-supervisor triple.
3912        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
3913    }
3914
3915    #[test]
3916    fn supervisor_spec_otp_canonical_byte_equals_default() {
3917        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
3918        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
3919        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
3920        // pin already asserts against the [`Default::default`] path.
3921        // Sharpens the pair-invariant into a per-constructor pin so a
3922        // future extension of [`SupervisorSpec`] with a fifth field
3923        // whose OTP-canonical shape is non-`Default::default`-equivalent
3924        // trips at caixa-core test time rather than at a downstream
3925        // consumer that composed [`SupervisorSpec::otp_canonical`] with
3926        // [`SupervisorSpec::validate`] as its "canonical baseline
3927        // seed".
3928        let canonical = SupervisorSpec::otp_canonical();
3929        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
3930        assert_eq!(canonical.max_restarts, 5);
3931        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
3932        assert!(canonical.children.is_empty());
3933    }
3934
3935    #[test]
3936    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
3937        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
3938        // remain callable from a `const`-bound position so downstream
3939        // `const`-context callers wanting a canonical OTP-baseline seed
3940        // can construct one at compile time without runtime dispatch on
3941        // the derived [`Default::default`]. Peer of the sibling
3942        // `pub const fn` [`crate::LimitsSpec::empty`] /
3943        // [`crate::aplicacao::MeshPolicy::empty`] /
3944        // [`crate::BehaviorSpec::empty`] constructors on the sibling
3945        // typed-slot-spec `pub const fn` axis. If a future edit breaks
3946        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
3947        // (a non-`const` field-default helper, a non-`const`-stable
3948        // container type promotion), this evaluation fails at
3949        // build time on this file rather than at a downstream
3950        // `const`-context call site.
3951        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
3952        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
3953        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
3954        assert_eq!(
3955            CANONICAL.restart_window,
3956            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3957        );
3958        assert!(CANONICAL.children.is_empty());
3959    }
3960
3961    #[test]
3962    fn supervisor_child_restart_default_pins_otp_canonical_value() {
3963        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
3964        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
3965        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
3966        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
3967        // half of the same OTP-shape supervisor-tree default set whose
3968        // per-`:supervisor` halves the sibling
3969        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3970        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
3971        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
3972        // arm here surfaces a future rebrand of the per-child default (an
3973        // OTP-`transient` widening once the substrate discovers clean-
3974        // completion-aware children as the more common child shape, a
3975        // per-cluster overlay the operator pins through a future
3976        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
3977        // supervision-canary roadmap acknowledges) as a deliberate test
3978        // edit, not a silent contract migration. Peer of the sibling
3979        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
3980        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
3981        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3982        // value pins on the per-`:supervisor` halves.
3983        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
3984    }
3985
3986    #[test]
3987    fn restart_policy_default_routes_through_lifted_default() {
3988        // Composition pin: the [`Default for RestartPolicy`] impl's return
3989        // arm must route through the substrate-canonical
3990        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
3991        // than a raw `Self::Permanent` arm. Prior to the lift the impl
3992        // carried an inline `Self::Permanent` with no compile-time link
3993        // back to the OTP-shape supervisor-tree default set whose three
3994        // per-`:supervisor` halves already rode through lifted constants
3995        // — so a future coherent rebrand of the set would have had to
3996        // migrate three halves through typed constants and this fourth
3997        // through a raw enum arm in lockstep or the supervisor-level and
3998        // child-level defaults would silently drift apart. Byte-parity
3999        // against the lifted constant closes the split. Peer of the
4000        // sibling
4001        // [`restart_strategy_default_routes_through_lifted_default`]
4002        // composition pin on the per-`:supervisor` `:estrategia` axis.
4003        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
4004    }
4005
4006    #[test]
4007    fn child_spec_serde_default_restart_routes_through_lifted_default() {
4008        // Composition pin: the serde-side `#[serde(default)]` on
4009        // [`ChildSpec::restart`] — the wire-format author-omitted
4010        // `:children :restart` arm — must resolve onto the substrate-
4011        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
4012        // (via the [`Default for RestartPolicy`] impl the sibling
4013        // `restart_policy_default_routes_through_lifted_default` pin
4014        // already routes onto the constant). Structurally: a `ChildSpec`
4015        // deserialized from a payload that omits the `restart` key must
4016        // yield a `restart` field byte-equal to the lifted constant, so
4017        // the wire-format author-omitted arm and the
4018        // [`RestartPolicy::default`] impl arm cannot silently split on any
4019        // future default rebrand. Peer of the sibling
4020        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
4021        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4022        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4023        // byte-parity pins on the per-`:supervisor` halves of the same
4024        // author-omitted-slot resolution surface.
4025        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
4026            .expect("ChildSpec must deserialize with the restart key omitted");
4027        assert_eq!(
4028            omitted.restart(),
4029            SUPERVISOR_CHILD_RESTART_DEFAULT,
4030            "an author-omitted :children :restart slot must degrade onto \
4031             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
4032             {:?}, expected {:?})",
4033            omitted.restart(),
4034            SUPERVISOR_CHILD_RESTART_DEFAULT,
4035        );
4036    }
4037
4038    #[test]
4039    fn supervisor_max_restarts_cap_pins_canonical_value() {
4040        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
4041        // 1000 — the same ceiling the peer
4042        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
4043        // `:politicas :circuit-breaker :max-failures` axis (both are
4044        // "trip the next-higher protection layer after N events in a
4045        // rolling window" counters with identical
4046        // degenerate-at-the-high-end shape; uniform top edge so the
4047        // M4 CR materializers and the wasm-operator reconciler reach
4048        // for either field knowing the value is in `1..=1000`). Two
4049        // orders of magnitude above every documented Erlang/OTP /
4050        // Elixir / Riak Core / RabbitMQ production-playbook
4051        // recommendation band and below the clearly-pathological
4052        // "effectively no escalation" floor (10_000, 100_000,
4053        // u32::MAX). Pinning the literal value here surfaces a future
4054        // drift (a relaxation to 10_000, a tightening to 100) as a
4055        // deliberate test edit, not a silent contract narrowing.
4056        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
4057    }
4058
4059    #[test]
4060    fn validate_rejects_empty_child_name() {
4061        let s = SupervisorSpec {
4062            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4063            ..SupervisorSpec::default()
4064        };
4065        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
4066    }
4067
4068    #[test]
4069    fn validate_rejects_empty_child_version() {
4070        let s = SupervisorSpec {
4071            children: vec![child("w", "", RestartPolicy::Permanent)],
4072            ..SupervisorSpec::default()
4073        };
4074        assert!(matches!(
4075            s.validate().unwrap_err(),
4076            SupervisorError::EmptyChildVersion { .. }
4077        ));
4078    }
4079
4080    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
4081
4082    #[test]
4083    fn validate_rejects_invalid_child_versao_requirement() {
4084        // The fail-before-pass-after pin: a non-empty but malformed
4085        // semver requirement (`"^bad-version"`) silently passed
4086        // `validate()` on every pre-gate codebase because the prior
4087        // shape only refused the empty string. The parse failure
4088        // surfaced far downstream at lacre-resolve time with a
4089        // `semver::Error` that didn't name which `:children` entry
4090        // carried the typo. The new gate moves the check to caixa-build
4091        // time at the source caixa.lisp — the third `:versao` typed
4092        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
4093        // structural parity.
4094        let s = SupervisorSpec {
4095            children: vec![
4096                child("worker", "^0.1", RestartPolicy::Permanent),
4097                child("cache", "^bad-version", RestartPolicy::Transient),
4098            ],
4099            ..SupervisorSpec::default()
4100        };
4101        let err = s.validate().unwrap_err();
4102        assert!(
4103            matches!(
4104                err,
4105                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4106                    if caixa == "cache" && versao == "^bad-version"
4107            ),
4108            "got {err:?}"
4109        );
4110    }
4111
4112    #[test]
4113    fn validate_rejects_child_versao_with_double_caret_typo() {
4114        // `"^^0.1"` is the canonical doubled-caret typo — looks
4115        // Cargo-shaped on first glance but fails the parser because
4116        // semver doesn't accept stacked operators. Pin this
4117        // adjacent-shape footgun explicitly so a future relaxation that
4118        // accepts "looks-canonical-but-isn't" forms surfaces here.
4119        let s = SupervisorSpec {
4120            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
4121            ..SupervisorSpec::default()
4122        };
4123        let err = s.validate().unwrap_err();
4124        assert!(
4125            matches!(
4126                err,
4127                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4128                    if caixa == "worker" && versao == "^^0.1"
4129            ),
4130            "got {err:?}"
4131        );
4132    }
4133
4134    #[test]
4135    fn validate_rejects_child_versao_with_v_prefixed_tag() {
4136        // `"v0.1"` is the canonical "git-tag-shape leaking into the
4137        // semver requirement slot" typo — an author copies the
4138        // publish-side git-tag string verbatim into `:versao`, but
4139        // Cargo's semver parser rejects the leading `v`. Same
4140        // adjacent-shape footgun pinned for `:membros :versao`
4141        // (9888b13).
4142        let s = SupervisorSpec {
4143            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
4144            ..SupervisorSpec::default()
4145        };
4146        let err = s.validate().unwrap_err();
4147        assert!(
4148            matches!(
4149                err,
4150                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4151                    if caixa == "worker" && versao == "v0.1"
4152            ),
4153            "got {err:?}"
4154        );
4155    }
4156
4157    #[test]
4158    fn validate_accepts_canonical_child_versao_forms() {
4159        // The Cargo-shaped requirement forms `:deps :versao` and
4160        // `:membros :versao` already accept via
4161        // `crate::parse_requirement` must pass the children gate
4162        // without re-validating at the resolver layer. Pin every leg so
4163        // a future tightening of the canonical set surfaces here as a
4164        // test failure.
4165        for form in [
4166            "^0.1",      // caret — minor-range pin (the most common shape)
4167            "~0.1.2",    // tilde — patch-range pin
4168            "0.1.0",     // exact — single-version pin
4169            "*",         // wildcard — any version (semver::VersionReq::STAR)
4170            ">=0.1, <2", // multi-range — comma-separated comparators
4171        ] {
4172            let s = SupervisorSpec {
4173                children: vec![child("worker", form, RestartPolicy::Permanent)],
4174                ..SupervisorSpec::default()
4175            };
4176            s.validate()
4177                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4178        }
4179    }
4180
4181    #[test]
4182    fn child_versao_empty_takes_precedence_over_invalid() {
4183        // Order pin: the existing `EmptyChildVersion` diagnostic (which
4184        // doesn't try to parse) fires before the new
4185        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
4186        // `:versao` keeps its narrower error message —
4187        // `parse_requirement` would also reject `""`, but the
4188        // empty-string arm is the more self-locating diagnostic for the
4189        // author. Same ordering discipline as
4190        // `membro_versao_empty_takes_precedence_over_invalid` in
4191        // aplicacao.rs.
4192        let s = SupervisorSpec {
4193            children: vec![child("worker", "", RestartPolicy::Permanent)],
4194            ..SupervisorSpec::default()
4195        };
4196        let err = s.validate().unwrap_err();
4197        assert!(
4198            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
4199            "got {err:?}"
4200        );
4201    }
4202
4203    #[test]
4204    fn child_versao_invalid_fires_before_duplicate_check() {
4205        // Order pin: a malformed requirement on a non-duplicate entry
4206        // surfaces *its own* diagnostic (which names the offending
4207        // `:versao` string), even when a later entry would otherwise
4208        // collapse onto an earlier name. The per-entry shape gate runs
4209        // inline before the duplicate-key insert — parallel to
4210        // `membro_versao_invalid_fires_before_duplicate_check` in
4211        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
4212        let s = SupervisorSpec {
4213            children: vec![
4214                child("worker", "^bad", RestartPolicy::Permanent),
4215                child("cache", "^0.1", RestartPolicy::Transient),
4216                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4217            ],
4218            ..SupervisorSpec::default()
4219        };
4220        let err = s.validate().unwrap_err();
4221        assert!(
4222            matches!(
4223                err,
4224                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
4225            ),
4226            "got {err:?}"
4227        );
4228    }
4229
4230    #[test]
4231    fn child_versao_invalid_diagnostic_carries_offending_versao() {
4232        // The diagnostic-shape pin: the error names the offending
4233        // `:versao` value verbatim so the author can grep their
4234        // caixa.lisp without re-running the build, and carries a
4235        // non-empty `reason` from `semver::VersionReq::parse` so the
4236        // parser's own wording flows through to the diagnostic.
4237        let s = SupervisorSpec {
4238            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
4239            ..SupervisorSpec::default()
4240        };
4241        let err = s.validate().unwrap_err();
4242        let SupervisorError::ChildVersaoInvalid {
4243            caixa,
4244            versao,
4245            reason,
4246        } = err
4247        else {
4248            panic!("expected ChildVersaoInvalid, got other variant");
4249        };
4250        assert_eq!(caixa, "worker");
4251        assert_eq!(versao, "not-a-req");
4252        assert!(
4253            !reason.is_empty(),
4254            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
4255        );
4256    }
4257
4258    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
4259
4260    #[test]
4261    fn validate_rejects_child_caixa_with_uppercase() {
4262        // The canonical "I copied the Servico's display name verbatim"
4263        // typo — child caixa names are lowercase per K8s DNS-1123 label
4264        // rule. The diagnostic names the offending name and suggests the
4265        // lower-cased fix in one edit, mirroring the
4266        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
4267        let s = SupervisorSpec {
4268            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
4269            ..SupervisorSpec::default()
4270        };
4271        let err = s.validate().unwrap_err();
4272        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4273            panic!("expected ChildCaixaInvalid, got other variant");
4274        };
4275        assert_eq!(caixa, "Worker");
4276        assert!(
4277            reason.contains("uppercase"),
4278            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
4279        );
4280        assert!(
4281            reason.contains("\"worker\""),
4282            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
4283        );
4284    }
4285
4286    #[test]
4287    fn validate_rejects_child_caixa_with_underscore() {
4288        // The canonical "I'm thinking of a Python module / Postgres
4289        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
4290        // label schema. K8s rejects `metadata.name: my_worker` at
4291        // admission time with an opaque `field is invalid` (no source-
4292        // citing diagnostic). The gate moves it to caixa-build time.
4293        let s = SupervisorSpec {
4294            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
4295            ..SupervisorSpec::default()
4296        };
4297        let err = s.validate().unwrap_err();
4298        assert!(
4299            matches!(
4300                err,
4301                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4302                    if caixa == "my_worker" && reason.contains('_')
4303            ),
4304            "got {err:?}"
4305        );
4306    }
4307
4308    #[test]
4309    fn validate_rejects_child_caixa_with_dot() {
4310        // A `:children :caixa` entry is a single DNS-1123 label, not a
4311        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
4312        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
4313        // (3f9d7a0) on the peer name axis.
4314        let s = SupervisorSpec {
4315            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
4316            ..SupervisorSpec::default()
4317        };
4318        let err = s.validate().unwrap_err();
4319        assert!(
4320            matches!(
4321                err,
4322                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4323                    if caixa == "team.worker" && reason.contains('.')
4324            ),
4325            "got {err:?}"
4326        );
4327    }
4328
4329    #[test]
4330    fn validate_rejects_child_caixa_with_leading_hyphen() {
4331        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
4332        // with an alphanumeric. The K8s apiserver rejects `-worker`
4333        // outright; the renderer would emit a `metadata.name: "-worker"`
4334        // that fails admission far from the source caixa.lisp.
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        assert!(
4341            matches!(
4342                err,
4343                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4344                    if caixa == "-worker" && reason.contains("start and end")
4345            ),
4346            "got {err:?}"
4347        );
4348    }
4349
4350    #[test]
4351    fn validate_rejects_child_caixa_with_trailing_hyphen() {
4352        // The symmetric arm of the boundary rule. Pin separately so
4353        // both ends of the label are covered against a future relaxation
4354        // that only checks one boundary.
4355        let s = SupervisorSpec {
4356            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
4357            ..SupervisorSpec::default()
4358        };
4359        let err = s.validate().unwrap_err();
4360        assert!(
4361            matches!(
4362                err,
4363                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4364                    if caixa == "worker-"
4365            ),
4366            "got {err:?}"
4367        );
4368    }
4369
4370    #[test]
4371    fn validate_rejects_child_caixa_with_unicode() {
4372        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
4373        // (`xn--…`) by the author before it reaches K8s. The byte-by-
4374        // byte ASCII validity check rejects multi-byte UTF-8 sequences
4375        // by the first byte that fails the `[a-z0-9-]` predicate.
4376        let s = SupervisorSpec {
4377            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
4378            ..SupervisorSpec::default()
4379        };
4380        let err = s.validate().unwrap_err();
4381        assert!(
4382            matches!(
4383                err,
4384                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4385                    if caixa == "café"
4386            ),
4387            "got {err:?}"
4388        );
4389    }
4390
4391    #[test]
4392    fn validate_rejects_child_caixa_with_whitespace() {
4393        // Whitespace is the canonical "I pasted from a sketch / doc"
4394        // footgun. The apiserver rejects every `metadata.name` value
4395        // carrying whitespace; pin the gate fires at the right boundary.
4396        let s = SupervisorSpec {
4397            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
4398            ..SupervisorSpec::default()
4399        };
4400        let err = s.validate().unwrap_err();
4401        assert!(
4402            matches!(
4403                err,
4404                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4405                    if caixa == "my worker"
4406            ),
4407            "got {err:?}"
4408        );
4409    }
4410
4411    #[test]
4412    fn validate_rejects_child_caixa_too_long() {
4413        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
4414        // 63 bytes; the K8s apiserver rejects every `metadata.name`
4415        // axis over the limit at admission time. The diagnostic names
4416        // both the cap and the actual length so the author can shorten
4417        // in one edit, mirroring `rejects_membro_caixa_too_long`
4418        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
4419        let too_long = "a".repeat(64);
4420        let s = SupervisorSpec {
4421            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
4422            ..SupervisorSpec::default()
4423        };
4424        let err = s.validate().unwrap_err();
4425        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4426            panic!("expected ChildCaixaInvalid, got other variant");
4427        };
4428        assert_eq!(caixa, too_long);
4429        assert!(
4430            reason.contains("63"),
4431            "diagnostic must name the 63-byte cap (got: {reason:?})"
4432        );
4433        assert!(
4434            reason.contains("64"),
4435            "diagnostic must name the actual length (got: {reason:?})"
4436        );
4437    }
4438
4439    #[test]
4440    fn child_caixa_max_length_validates() {
4441        // The 63-byte boundary control pin — exactly-at-the-cap is
4442        // accepted, mirroring `membro_caixa_max_length_validates`
4443        // (3f9d7a0) and `placement_cluster_max_length_validates`
4444        // (6cbb900). Pinned separately so a future off-by-one tightening
4445        // surfaces here.
4446        let max_label = "a".repeat(63);
4447        let s = SupervisorSpec {
4448            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
4449            ..SupervisorSpec::default()
4450        };
4451        s.validate().unwrap();
4452    }
4453
4454    #[test]
4455    fn validate_accepts_canonical_child_caixa_forms() {
4456        // The realistic shapes a supervised child's `:caixa` carries —
4457        // single-word `worker`, version-suffixed `cache-v2`, single-char
4458        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
4459        // `payment-retry`, all-digit `0`. Pin every leg so a future
4460        // tightening (e.g. requiring a leading lowercase letter) surfaces
4461        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
4462        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
4463        // (6cbb900).
4464        for form in [
4465            "worker",
4466            "cache-v2",
4467            "a",
4468            "db",
4469            "2-pool",
4470            "payment-retry",
4471            "0",
4472        ] {
4473            let s = SupervisorSpec {
4474                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
4475                ..SupervisorSpec::default()
4476            };
4477            s.validate()
4478                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4479        }
4480    }
4481
4482    #[test]
4483    fn child_caixa_empty_takes_precedence_over_invalid() {
4484        // Order pin: the existing `EmptyChildName` diagnostic (which
4485        // doesn't try to parse the DNS-1123 shape) fires before the new
4486        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
4487        // its narrower error message — `is_dns_1123_label` would reject
4488        // the empty string too (boundary check on the first byte), but
4489        // the empty-string arm is the more self-locating diagnostic for
4490        // the author. Same ordering discipline as
4491        // `membro_caixa_empty_takes_precedence_over_invalid` in
4492        // aplicacao.rs.
4493        let s = SupervisorSpec {
4494            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4495            ..SupervisorSpec::default()
4496        };
4497        let err = s.validate().unwrap_err();
4498        assert_eq!(err, SupervisorError::EmptyChildName);
4499    }
4500
4501    #[test]
4502    fn child_caixa_invalid_fires_before_versao_check() {
4503        // Order pin: the per-axis shape gate runs inline before the
4504        // per-entry versao check, so a malformed `:caixa` on an entry
4505        // whose `:versao` would also fail surfaces the more self-
4506        // locating name-axis diagnostic first. Parallel to
4507        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
4508        // and `placement_cluster_invalid_fires_before_duplicate_check`
4509        // (6cbb900).
4510        let s = SupervisorSpec {
4511            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
4512            ..SupervisorSpec::default()
4513        };
4514        let err = s.validate().unwrap_err();
4515        assert!(
4516            matches!(
4517                err,
4518                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
4519            ),
4520            "got {err:?}"
4521        );
4522    }
4523
4524    #[test]
4525    fn child_caixa_invalid_fires_before_duplicate_check() {
4526        // Order pin: a malformed name on a non-duplicate entry surfaces
4527        // its own diagnostic, even when a later entry would otherwise
4528        // collapse onto an earlier name. The per-entry shape gate runs
4529        // inline before the duplicate-key HashSet insert, mirroring
4530        // `placement_cluster_invalid_fires_before_duplicate_check`
4531        // (6cbb900).
4532        let s = SupervisorSpec {
4533            children: vec![
4534                child("Worker", "^0.1", RestartPolicy::Permanent),
4535                child("cache", "^0.1", RestartPolicy::Transient),
4536                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4537            ],
4538            ..SupervisorSpec::default()
4539        };
4540        let err = s.validate().unwrap_err();
4541        assert!(
4542            matches!(
4543                err,
4544                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
4545            ),
4546            "got {err:?}"
4547        );
4548    }
4549
4550    #[test]
4551    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
4552        // The diagnostic-shape pin: the error names the offending
4553        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
4554        // the author can grep their caixa.lisp without re-running the
4555        // build. Mirrors the diagnostic-shape sweep on every prior
4556        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
4557        let s = SupervisorSpec {
4558            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
4559            ..SupervisorSpec::default()
4560        };
4561        let err = s.validate().unwrap_err();
4562        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4563            panic!("expected ChildCaixaInvalid, got other variant");
4564        };
4565        assert_eq!(caixa, "My_Worker");
4566        assert!(
4567            !reason.is_empty(),
4568            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
4569        );
4570    }
4571
4572    // ── value-shape: zero restart_window + duplicate child names ──────────
4573
4574    #[test]
4575    fn validate_accepts_none_restart_window() {
4576        // Omitted `:restart-window` is the "never reset" sentinel —
4577        // valid by design. Mirrors :limits axes where None = unbounded.
4578        let s = SupervisorSpec {
4579            restart_window: None,
4580            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4581            ..SupervisorSpec::default()
4582        };
4583        s.validate().unwrap();
4584    }
4585
4586    #[test]
4587    fn validate_rejects_zero_restart_window() {
4588        // Same "0 means the opposite of what you think" footgun closed
4589        // for :politicas :timeout (Envoy treats 0s as infinite) and
4590        // :limits :wall-clock (wasmtime traps before the call starts).
4591        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
4592        let s = SupervisorSpec {
4593            restart_window: Some(Duration::ZERO),
4594            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4595            ..SupervisorSpec::default()
4596        };
4597        assert_eq!(
4598            s.validate().unwrap_err(),
4599            SupervisorError::RestartWindowZero
4600        );
4601    }
4602
4603    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
4604    //
4605    // The fourth (and last) typed-`Duration` axis in caixa-core to get
4606    // the integer-millisecond canonical-form gate — peer with
4607    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
4608    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
4609    // path is already gated at the shared codec layer (see
4610    // `restart_window_serde_rejects_fractional_seconds`); this arm
4611    // closes the programmatic-struct-literal path the codec gate can't
4612    // see.
4613
4614    #[test]
4615    fn validate_rejects_sub_millisecond_restart_window() {
4616        // The fail-before-pass-after pin: a programmatic
4617        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
4618        // `validate` on every pre-gate codebase, then truncated to
4619        // `as_millis() == 1` on first serialize — the shared codec
4620        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
4621        // 1_000_000 ns, the typed `restart_window` no longer matches
4622        // its rendered form.
4623        let s = SupervisorSpec {
4624            restart_window: Some(Duration::from_micros(1500)),
4625            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4626            ..SupervisorSpec::default()
4627        };
4628        match s.validate().unwrap_err() {
4629            SupervisorError::RestartWindowNotCanonical { window } => {
4630                assert_eq!(window, Duration::from_micros(1500));
4631            }
4632            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4633        }
4634    }
4635
4636    #[test]
4637    fn validate_rejects_one_nanosecond_restart_window() {
4638        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
4639        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
4640        // so the shared codec emits the literal `"0s"` — the next
4641        // serde round-trip would parse back to `Duration::ZERO`, which
4642        // the `RestartWindowZero` arm then rejects on re-validate. The
4643        // canonical-form gate at this layer surfaces a self-locating
4644        // diagnostic naming the offending Duration verbatim rather
4645        // than a downstream `RestartWindowZero` whose remediation
4646        // points at omitting the slot.
4647        let s = SupervisorSpec {
4648            restart_window: Some(Duration::from_nanos(1)),
4649            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4650            ..SupervisorSpec::default()
4651        };
4652        match s.validate().unwrap_err() {
4653            SupervisorError::RestartWindowNotCanonical { window } => {
4654                assert_eq!(window, Duration::from_nanos(1));
4655            }
4656            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4657        }
4658    }
4659
4660    #[test]
4661    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
4662        // The 1-ns-past-1ms boundary case: a `Duration` carrying
4663        // 1_000_001 ns is structurally past the integer-ms granularity
4664        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
4665        // trip would truncate to `1ms` and the consumer would observe
4666        // a 1-ns drift on every emit. Same boundary the peer
4667        // `validate_rejects_nanosecond_past_canonical_boundary` test
4668        // in limits.rs pins for the `:limits :wall-clock` axis.
4669        let w = Duration::from_nanos(1_000_001);
4670        let s = SupervisorSpec {
4671            restart_window: Some(w),
4672            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4673            ..SupervisorSpec::default()
4674        };
4675        assert_eq!(
4676            s.validate().unwrap_err(),
4677            SupervisorError::RestartWindowNotCanonical { window: w }
4678        );
4679    }
4680
4681    #[test]
4682    fn validate_accepts_integer_millisecond_restart_window_values() {
4683        // The positive-control sweep: every `Duration` the shared
4684        // codec can round-trip losslessly — the canonical
4685        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
4686        // pair emits and accepts — passes `validate` without
4687        // surfacing the new canonical-form arm. Mirrors
4688        // `validate_accepts_integer_millisecond_wall_clock_values` on
4689        // the sibling `:limits :wall-clock` axis.
4690        for w in [
4691            Duration::from_millis(1),
4692            Duration::from_millis(500),
4693            Duration::from_millis(1500),
4694            Duration::from_secs(1),
4695            Duration::from_secs(30),
4696            Duration::from_secs(60),
4697            Duration::from_secs(120),
4698            Duration::from_secs(3600),
4699        ] {
4700            let s = SupervisorSpec {
4701                restart_window: Some(w),
4702                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4703                ..SupervisorSpec::default()
4704            };
4705            s.validate()
4706                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
4707        }
4708    }
4709
4710    #[test]
4711    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
4712        // Cross-arm ordering pin: `Duration::ZERO` has
4713        // `subsec_nanos() == 0` and would otherwise pass the
4714        // canonical-form arm — the zero-floor arm must fire first so
4715        // the more self-locating `RestartWindowZero` diagnostic (with
4716        // its omit-axis remediation directly named) leads. Same
4717        // posture every peer zero-then-shape gate uses
4718        // (`WallClockZero` → `WallClockNotCanonical`,
4719        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
4720        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
4721        let s = SupervisorSpec {
4722            restart_window: Some(Duration::ZERO),
4723            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4724            ..SupervisorSpec::default()
4725        };
4726        assert_eq!(
4727            s.validate().unwrap_err(),
4728            SupervisorError::RestartWindowZero
4729        );
4730    }
4731
4732    #[test]
4733    fn restart_window_canonical_diagnostic_carries_offending_duration() {
4734        // Diagnostic-shape pin: the canonical-form arm names the
4735        // offending `Duration` verbatim so the author's grep lands on
4736        // the field's value, not a generic "duration not canonical"
4737        // message. Same shape every other typed-canonical-form arm
4738        // on this surface carries (`WallClockNotCanonical` carries
4739        // the offending `Duration` verbatim,
4740        // `PolicyTimeoutNotCanonical` carries the offending
4741        // `Duration` verbatim).
4742        let w = Duration::from_micros(500);
4743        let s = SupervisorSpec {
4744            restart_window: Some(w),
4745            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4746            ..SupervisorSpec::default()
4747        };
4748        let err = s.validate().unwrap_err();
4749        let msg = err.to_string();
4750        assert!(
4751            msg.contains("500"),
4752            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
4753        );
4754        assert!(
4755            msg.contains("sub-millisecond"),
4756            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
4757        );
4758    }
4759
4760    #[test]
4761    fn restart_window_validated_value_round_trips_through_codec() {
4762        // The structural property the canonical-ms gate enforces:
4763        // every `SupervisorSpec::restart_window` past
4764        // `SupervisorSpec::validate` round-trips losslessly through
4765        // the shared duration codec (serialize → string →
4766        // deserialize → equal value). Pin this end-to-end so a future
4767        // change to either side (the validate gate's accepted
4768        // granularity, the codec's parse/render unit set) that breaks
4769        // the alignment surfaces here. Peer of
4770        // `wall_clock_validated_value_round_trips_through_codec` on
4771        // the sibling `:limits :wall-clock` axis.
4772        for w in [
4773            Duration::from_millis(1),
4774            Duration::from_millis(1500),
4775            Duration::from_secs(30),
4776            Duration::from_secs(3600),
4777        ] {
4778            let s = SupervisorSpec {
4779                restart_window: Some(w),
4780                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4781                ..SupervisorSpec::default()
4782            };
4783            s.validate().unwrap();
4784            let json = serde_json::to_string(&s).unwrap();
4785            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4786            assert_eq!(back.restart_window, Some(w));
4787        }
4788    }
4789
4790    // ── value-shape: upper cap on :restart-window ─────────────────────────
4791    //
4792    // The fourth (and last) typed-`Duration` axis in caixa-core to get
4793    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
4794    // `:politicas :timeout` (2e8ee7e), and `:politicas
4795    // :circuit-breaker :window` (379a814). Brackets the typed
4796    // `:restart-window` axis structurally: every validated value lies
4797    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
4798    // granularity, closing the
4799    // rolling-window-degenerates-to-lifetime-counter footgun the prior
4800    // zero-floor-and-canonical-form-only checks left open.
4801
4802    #[test]
4803    fn validate_rejects_restart_window_above_cap() {
4804        // The fail-before-pass-after pin: 3601s = 1h + 1s is
4805        // structurally one canonical-tick past the
4806        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
4807        // integer-millisecond magnitude the canonical-form arm above
4808        // accepts cleanly, that the shared duration codec round-trips
4809        // losslessly as `"3601s"`, and that silently passed validate on
4810        // every pre-gate codebase because the typed slot's only checks
4811        // were the zero-floor and canonical-form arms. The runtime
4812        // substrate consuming the value (Erlang/OTP's MaxIntensity/
4813        // Period reconciler, the future wasm-operator's per-supervisor
4814        // restart-intensity counter) reaches for a `Duration` so long
4815        // no realistic restart-recovery pattern resets the counter,
4816        // far from the source caixa.lisp.
4817        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
4818        let s = SupervisorSpec {
4819            restart_window: Some(w),
4820            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4821            ..SupervisorSpec::default()
4822        };
4823        assert_eq!(
4824            s.validate().unwrap_err(),
4825            SupervisorError::RestartWindowExceedsCap { window: w }
4826        );
4827    }
4828
4829    #[test]
4830    fn validate_rejects_restart_window_one_millisecond_above_cap() {
4831        // Boundary case: exactly 1ms past the cap (the granularity the
4832        // canonical-form gate enforces). Catches a future "strictly
4833        // less than" half-measure and pins the diagnostic to name the
4834        // offending `Duration` verbatim. Peer of
4835        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
4836        // `rejects_policy_timeout_one_millisecond_above_cap` /
4837        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
4838        // on the sibling typed-`Duration` axes' top edges.
4839        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
4840        let s = SupervisorSpec {
4841            restart_window: Some(w),
4842            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4843            ..SupervisorSpec::default()
4844        };
4845        assert_eq!(
4846            s.validate().unwrap_err(),
4847            SupervisorError::RestartWindowExceedsCap { window: w }
4848        );
4849    }
4850
4851    #[test]
4852    fn validate_rejects_restart_window_far_above_cap() {
4853        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
4854        // `(:restart-window "7d")`, or any "I want a lifetime counter
4855        // but wrote a `<integer>h` magnitude anyway" typo — values the
4856        // canonical-form arm accepts as integer-millisecond magnitudes,
4857        // the codec round-trips losslessly through serde, but the
4858        // operator's `MaxIntensity / Period` reconciler cannot honor
4859        // as a meaningful rolling window. Until this gate landed
4860        // validate accepted them. Pin the common above-cap values (24h,
4861        // 7d, ~11.5d) so a future relaxation that drops the upper bound
4862        // surfaces here.
4863        for w in [
4864            Duration::from_secs(86_400),    // 24h
4865            Duration::from_secs(604_800),   // 7d
4866            Duration::from_secs(1_000_000), // ~11.5 days
4867        ] {
4868            let s = SupervisorSpec {
4869                restart_window: Some(w),
4870                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4871                ..SupervisorSpec::default()
4872            };
4873            assert_eq!(
4874                s.validate().unwrap_err(),
4875                SupervisorError::RestartWindowExceedsCap { window: w }
4876            );
4877        }
4878    }
4879
4880    #[test]
4881    fn validate_accepts_restart_window_at_cap() {
4882        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
4883        // (1h) — must validate. The cap is inclusive on the top edge,
4884        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
4885        // [`crate::POLICY_TIMEOUT_MAX`] /
4886        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
4887        // capped axes. Pin the boundary explicitly so a future
4888        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
4889        // instead of `>`) surfaces here as a test failure rather than a
4890        // silent contract narrowing.
4891        let s = SupervisorSpec {
4892            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
4893            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4894            ..SupervisorSpec::default()
4895        };
4896        s.validate()
4897            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
4898    }
4899
4900    #[test]
4901    fn validate_accepts_restart_window_typical_values() {
4902        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
4903        // per-supervisor production-playbook band positive-control
4904        // sweep — every value Learn You Some Erlang's `{intensity, 5,
4905        // 60}` worker-supervisor `Period = 60s` default, Elixir's
4906        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
4907        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
4908        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
4909        // default recommend (5s..=300s) must pass, plus a sweep
4910        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
4911        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
4912        // on the sibling `:limits :wall-clock` axis.
4913        for w in [
4914            Duration::from_millis(1),
4915            Duration::from_millis(500),
4916            Duration::from_secs(1),
4917            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
4918            Duration::from_secs(10), // Riak Core lower
4919            Duration::from_secs(30),
4920            Duration::from_secs(60),  // Learn You Some Erlang default
4921            Duration::from_secs(120), // OTP supervisor MaxT typical
4922            Duration::from_secs(300), // Riak Core upper
4923            Duration::from_secs(900), // 15m
4924            Duration::from_secs(1800),
4925            Duration::from_secs(3600), // exactly 1h, the cap
4926        ] {
4927            let s = SupervisorSpec {
4928                restart_window: Some(w),
4929                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4930                ..SupervisorSpec::default()
4931            };
4932            s.validate()
4933                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
4934        }
4935    }
4936
4937    #[test]
4938    fn restart_window_zero_takes_precedence_over_cap() {
4939        // The cross-arm ordering pin: `Duration::ZERO` is structurally
4940        // outside both `>= 1ms` (zero-floor) and `<=
4941        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
4942        // diagnostic is the more self-locating one (it directly names
4943        // the omit-axis remediation), so the validate gate must fire
4944        // on zero first. Same shape every other zero-then-cap ordering
4945        // on this surface uses (`WallClockZero` then
4946        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
4947        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
4948        // `PolicyBreakerWindowExceedsCap`).
4949        let s = SupervisorSpec {
4950            restart_window: Some(Duration::ZERO),
4951            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4952            ..SupervisorSpec::default()
4953        };
4954        assert_eq!(
4955            s.validate().unwrap_err(),
4956            SupervisorError::RestartWindowZero,
4957            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
4958        );
4959    }
4960
4961    #[test]
4962    fn restart_window_canonical_takes_precedence_over_cap() {
4963        // The cross-arm ordering pin: a `Duration` that is *both*
4964        // sub-millisecond (non-canonical-form) and structurally above
4965        // the cap surfaces the canonical-form diagnostic first,
4966        // because the round-trip-shape break is the more fundamental
4967        // issue (the value can't even round-trip through the codec,
4968        // so the cap diagnostic naming `1ms..=1h` would be misleading
4969        // — there's no integer-ms form of the offending value). Pin
4970        // the order so a future refactor that reorders the arms
4971        // surfaces here as a test failure rather than a silent
4972        // diagnostic regression. Peer of
4973        // `wall_clock_canonical_takes_precedence_over_cap` /
4974        // `policy_timeout_canonical_takes_precedence_over_cap`.
4975        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
4976        let s = SupervisorSpec {
4977            restart_window: Some(w),
4978            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4979            ..SupervisorSpec::default()
4980        };
4981        assert_eq!(
4982            s.validate().unwrap_err(),
4983            SupervisorError::RestartWindowNotCanonical { window: w },
4984            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
4985        );
4986    }
4987
4988    #[test]
4989    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
4990        // The cross-arm ordering pin between the `:max-restarts` cap
4991        // and the sibling `:restart-window` cap. A supervisor carrying
4992        // both an over-cap `max_restarts` AND an over-cap window must
4993        // surface the `MaxRestartsExceedsCap` diagnostic first — the
4994        // cap arm is wired immediately after the zero-restart arm and
4995        // strictly before every window-axis arm (zero / canonical /
4996        // cap), so the offending value the diagnostic names matches
4997        // the order the author would discover the gates by reading
4998        // top-to-bottom through `SupervisorSpec::validate`. Pin the
4999        // order so a future refactor that reorders the arms surfaces
5000        // here as a test failure rather than a silent diagnostic
5001        // regression. Peer of
5002        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
5003        // on the sibling zero / canonical window arms.
5004        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5005        let s = SupervisorSpec {
5006            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5007            restart_window: Some(w),
5008            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5009            ..SupervisorSpec::default()
5010        };
5011        assert_eq!(
5012            s.validate().unwrap_err(),
5013            SupervisorError::MaxRestartsExceedsCap {
5014                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5015            },
5016            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5017        );
5018    }
5019
5020    #[test]
5021    fn restart_window_cap_diagnostic_carries_offending_value() {
5022        // The diagnostic-shape pin: the offending `Duration` is
5023        // carried verbatim into the
5024        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
5025        // surfaced error message names the value the author wrote,
5026        // not just the cap. Same self-locating diagnostic shape every
5027        // other typed-cap arm on this surface carries
5028        // (`WallClockExceedsCap` carries the offending `Duration`
5029        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
5030        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
5031        // the offending `Duration` verbatim).
5032        let w = Duration::from_secs(7200); // 2h
5033        let s = SupervisorSpec {
5034            restart_window: Some(w),
5035            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5036            ..SupervisorSpec::default()
5037        };
5038        let err = s.validate().unwrap_err();
5039        assert!(
5040            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
5041            "got {err:?}"
5042        );
5043        let msg = err.to_string();
5044        assert!(
5045            msg.contains("7200"),
5046            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
5047        );
5048    }
5049
5050    #[test]
5051    fn supervisor_restart_window_cap_pins_canonical_value() {
5052        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
5053        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
5054        // shared duration codec emits as a clean canonical string
5055        // (`"<n>h"`). Pinning the literal value here surfaces a future
5056        // drift (a relaxation to 24h, a tightening to 5m) as a
5057        // deliberate test edit, not a silent contract narrowing.
5058        //
5059        // The four typed-`Duration` caps on the validation surface
5060        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
5061        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
5062        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
5063        // single uniform top edge at the codec's largest emitted unit
5064        // — a structural-property invariant the equality assertions
5065        // here enshrine, so a future drift on any of the four
5066        // surfaces as a deliberate test edit. Same shape every other
5067        // typed-cap value pin uses
5068        // (`wall_clock_cap_pins_canonical_value`,
5069        // `policy_timeout_cap_pins_canonical_value`,
5070        // `circuit_breaker_window_cap_pins_canonical_value`).
5071        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
5072        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
5073        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
5074        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
5075        assert_eq!(
5076            SUPERVISOR_RESTART_WINDOW_MAX,
5077            crate::POLICY_BREAKER_WINDOW_MAX
5078        );
5079    }
5080
5081    #[test]
5082    fn restart_window_cap_value_round_trips_through_codec() {
5083        // The codec round-trip property the cap arm preserves: the
5084        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
5085        // through the shared duration codec — every value at the cap
5086        // serializes to the canonical `"1h"` form and parses back
5087        // identically. Pin the round-trip so a future change to the
5088        // codec's unit set or to the cap's magnitude that breaks the
5089        // round-trip property surfaces here. Peer of
5090        // `wall_clock_cap_value_round_trips_through_codec` on the
5091        // sibling `:limits :wall-clock` axis.
5092        let s = SupervisorSpec {
5093            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5094            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5095            ..SupervisorSpec::default()
5096        };
5097        s.validate().unwrap();
5098        let json = serde_json::to_string(&s).unwrap();
5099        assert!(
5100            json.contains("\"1h\""),
5101            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
5102        );
5103        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5104        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
5105    }
5106
5107    #[test]
5108    fn validate_rejects_duplicate_child_caixa() {
5109        // Two children with the same :caixa render to two ComputeUnits
5110        // with the same name in the cluster's HelmRelease values —
5111        // one silently overwrites the other. Erlang/OTP's child_spec.id
5112        // is required-unique per supervisor; same set-not-multiset
5113        // discipline applied here as for :membros / :placement
5114        // :clusters / :entrada :paths.
5115        let s = SupervisorSpec {
5116            children: vec![
5117                child("worker", "^0.1", RestartPolicy::Permanent),
5118                child("cache", "^0.1", RestartPolicy::Transient),
5119                child("worker", "^0.2", RestartPolicy::Permanent),
5120            ],
5121            ..SupervisorSpec::default()
5122        };
5123        let err = s.validate().unwrap_err();
5124        assert!(
5125            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
5126            "got {err:?}"
5127        );
5128    }
5129
5130    #[test]
5131    fn validate_duplicate_child_diagnostic_names_first_collision() {
5132        // Iteration walks the :children list in declaration order —
5133        // the diagnostic names the first repeat, deterministically,
5134        // even when multiple names duplicate.
5135        let s = SupervisorSpec {
5136            children: vec![
5137                child("a", "^0.1", RestartPolicy::Permanent),
5138                child("b", "^0.1", RestartPolicy::Permanent),
5139                child("a", "^0.1", RestartPolicy::Permanent),
5140                child("b", "^0.1", RestartPolicy::Permanent),
5141            ],
5142            ..SupervisorSpec::default()
5143        };
5144        let err = s.validate().unwrap_err();
5145        assert!(
5146            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
5147            "got {err:?}"
5148        );
5149    }
5150
5151    // ── self-supervision cross-slot gate ──────────────────────────
5152
5153    #[test]
5154    fn validate_no_self_supervision_rejects_self_referential_child() {
5155        // A supervisor whose `:children` lists its own `:nome` is a
5156        // one-node reconciliation cycle — rejected, naming the parent.
5157        let children = vec![
5158            child("worker", "^0.1", RestartPolicy::Permanent),
5159            child("orquestra", "^0.1", RestartPolicy::Permanent),
5160        ];
5161        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
5162        assert!(
5163            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
5164            "got {err:?}"
5165        );
5166    }
5167
5168    #[test]
5169    fn validate_no_self_supervision_accepts_distinct_children() {
5170        // Positive control: distinct child names (including a child that
5171        // is itself a supervisor — nested trees are valid OTP) pass.
5172        let children = vec![
5173            child("worker", "^0.1", RestartPolicy::Permanent),
5174            child("sub-tree", "^0.1", RestartPolicy::Permanent),
5175        ];
5176        validate_no_self_supervision(&children, "orquestra").unwrap();
5177    }
5178
5179    #[test]
5180    fn validate_no_self_supervision_empty_children_is_ok() {
5181        // SimpleOneForOne / no-static-children supervisors have nothing
5182        // to self-reference — the gate is vacuously satisfied.
5183        validate_no_self_supervision(&[], "orquestra").unwrap();
5184    }
5185
5186    #[test]
5187    fn validate_simple_one_for_one_skips_uniqueness_check() {
5188        // SimpleOneForOne supervisors carry no static children — the
5189        // duplicate-child loop never runs. A zero-window declaration
5190        // on a SimpleOneForOne supervisor still trips the window check
5191        // (window applies to dynamic children too).
5192        let s = SupervisorSpec {
5193            estrategia: RestartStrategy::SimpleOneForOne,
5194            restart_window: None,
5195            children: vec![],
5196            ..SupervisorSpec::default()
5197        };
5198        s.validate().unwrap();
5199        let s_zero = SupervisorSpec {
5200            estrategia: RestartStrategy::SimpleOneForOne,
5201            restart_window: Some(Duration::ZERO),
5202            children: vec![],
5203            ..SupervisorSpec::default()
5204        };
5205        assert_eq!(
5206            s_zero.validate().unwrap_err(),
5207            SupervisorError::RestartWindowZero
5208        );
5209    }
5210
5211    #[test]
5212    fn validate_zero_window_runs_after_max_restarts_check() {
5213        // Pin the order: max_restarts == 0 fires before
5214        // restart_window == 0s, so an author with both wrong sees the
5215        // counter-axis diagnostic first (matches the order in the
5216        // struct and in the doc comment).
5217        let s = SupervisorSpec {
5218            max_restarts: 0,
5219            restart_window: Some(Duration::ZERO),
5220            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5221            ..SupervisorSpec::default()
5222        };
5223        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5224    }
5225
5226    #[test]
5227    fn round_trip_all_strategies() {
5228        for &strat in RestartStrategy::ALL {
5229            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
5230            // shape partition through the [`gen_platform::IsVariant`]
5231            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
5232            // predicate rather than the raw
5233            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
5234            // open-coded pattern-match — same closed-set-typed-enum
5235            // arm-discriminator dispatch discipline the sibling
5236            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
5237            // (915a934) extended onto its two paired positive / negated
5238            // `matches!` filter sites, and the sibling
5239            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
5240            // predicate convergence (766ec63) extended onto the M3 mesh-
5241            // slot per-`:placement` distribution-strategy `matches!`
5242            // discriminator axis. See the sibling
5243            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
5244            // fixture and the peer `manifest::tests::
5245            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
5246            // fixture — all three sites (the last unlifted
5247            // `matches!`-based arm-discriminator axis on the OTP-shape
5248            // supervisor sibling-restart-strategy closed-set typed enum,
5249            // acknowledged in 915a934's Prior-commits footnote as the
5250            // outstanding follow-up) now consult one typed dispatch on
5251            // the substrate primitive.
5252            let s = SupervisorSpec {
5253                estrategia: strat,
5254                children: if strat.is_simple_one_for_one() {
5255                    vec![]
5256                } else {
5257                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
5258                },
5259                ..SupervisorSpec::default()
5260            };
5261            let json = serde_json::to_string(&s).unwrap();
5262            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5263            assert_eq!(s, back);
5264        }
5265    }
5266
5267    #[test]
5268    fn round_trip_all_restart_policies() {
5269        for policy in [
5270            RestartPolicy::Permanent,
5271            RestartPolicy::Temporary,
5272            RestartPolicy::Transient,
5273        ] {
5274            let c = child("w", "^0.1", policy);
5275            let json = serde_json::to_string(&c).unwrap();
5276            let back: ChildSpec = serde_json::from_str(&json).unwrap();
5277            assert_eq!(c, back);
5278        }
5279    }
5280
5281    #[test]
5282    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
5283        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
5284        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
5285        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
5286        // is the only variant that satisfies `.is_simple_one_for_one()`;
5287        // every static-children-bearing arm (`OneForOne` / `OneForAll`
5288        // / `RestForOne`) returns `false`. This pin makes the partition
5289        // invariant load-bearing at caixa-core test time so a future
5290        // derive regression (a hole that returns `false` for
5291        // `SimpleOneForOne` too, or a byte-collision that flips a second
5292        // variant to `true`) trips here rather than laundering the arm
5293        // at the three test-fixture builder sites (a hole flips the
5294        // `SimpleOneForOne` fixture to carry a non-empty children list
5295        // and the subsequent `SupervisorSpec::validate` would refuse the
5296        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
5297        // a collision flips a peer strategy's fixture to carry an empty
5298        // children list and the subsequent `validate` would refuse with
5299        // [`SupervisorError::NoChildren`] — either way, the pin fires
5300        // here, at the derive site, rather than at the fixture-refusal
5301        // site far away). Peer of the sibling
5302        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
5303        // (915a934) pin on the M2 OTP-appup axis and the sibling
5304        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
5305        // pin on the M0 `:kind` axis.
5306        let cases: &[(RestartStrategy, bool)] = &[
5307            (RestartStrategy::OneForOne, false),
5308            (RestartStrategy::OneForAll, false),
5309            (RestartStrategy::RestForOne, false),
5310            (RestartStrategy::SimpleOneForOne, true),
5311        ];
5312        for (variant, expected) in cases {
5313            assert_eq!(
5314                variant.is_simple_one_for_one(),
5315                *expected,
5316                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
5317                 return {expected} (partition invariant on the \
5318                 IsVariant-derived arm-discriminator predicate — every \
5319                 test-fixture site that partitions the `:children` slot \
5320                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
5321                 off this typed dispatch, so a derive regression must \
5322                 surface here rather than at the fixture-refusal site)"
5323            );
5324        }
5325    }
5326
5327    #[test]
5328    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
5329        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
5330        // fixture-shape partition against the pre-lift
5331        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
5332        // pattern-match every test-fixture builder site previously
5333        // coupled to inline. Asserts the two projections agree byte-for-
5334        // byte on every arm of the enum, so a future derive regression
5335        // that flipped either predicate's arm-set would surface here at
5336        // caixa-core test time rather than at the three fixture-builder
5337        // sites (`supervisor::tests::round_trip_all_strategies`,
5338        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
5339        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
5340        // far from the derive site. Same peer-shape byte-identity pin
5341        // every sibling `IsVariant`-derive-routed convergence carries on
5342        // the substrate's closed-set typed-enum surface (peer of
5343        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
5344        // on the M2 OTP-appup axis).
5345        for &strat in RestartStrategy::ALL {
5346            let via_predicate = strat.is_simple_one_for_one();
5347            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
5348            assert_eq!(
5349                via_predicate, via_matches,
5350                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
5351                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
5352                 the pre-lift open-coded pattern and the \
5353                 IsVariant-derived predicate are the same axis, \
5354                 one typed dispatch"
5355            );
5356        }
5357    }
5358
5359    #[test]
5360    fn duration_codec_round_trip_canonical_units() {
5361        // Note the canonical-form rule: durations serialize to the
5362        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
5363        // "60s" — but the round-trip preserves the underlying Duration.
5364        let cases = [
5365            ("30s", Duration::from_secs(30)),
5366            ("5m", Duration::from_secs(300)),
5367            ("1h", Duration::from_secs(3600)),
5368            ("500ms", Duration::from_millis(500)),
5369        ];
5370        for (lit, dur) in cases {
5371            let s = SupervisorSpec {
5372                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5373                restart_window: Some(dur),
5374                ..SupervisorSpec::default()
5375            };
5376            let json = serde_json::to_string(&s).unwrap();
5377            assert!(
5378                json.contains(&format!("\"{lit}\"")),
5379                "expected \"{lit}\" in {json}"
5380            );
5381            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5382            assert_eq!(back.restart_window, Some(dur));
5383        }
5384    }
5385
5386    #[test]
5387    fn duration_canonicalizes_to_largest_unit() {
5388        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
5389        // typed Duration still equals 60s on the way back.
5390        let s = SupervisorSpec {
5391            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5392            restart_window: Some(Duration::from_secs(60)),
5393            ..SupervisorSpec::default()
5394        };
5395        let json = serde_json::to_string(&s).unwrap();
5396        assert!(json.contains("\"1m\""), "{json}");
5397        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5398        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
5399    }
5400
5401    #[test]
5402    fn three_child_one_for_one_validates() {
5403        let s = SupervisorSpec {
5404            estrategia: RestartStrategy::OneForOne,
5405            max_restarts: 5,
5406            restart_window: Some(Duration::from_secs(60)),
5407            children: vec![
5408                child("worker", "^0.1", RestartPolicy::Permanent),
5409                child("cache", "^0.1", RestartPolicy::Transient),
5410                child("scratch", "^0.1", RestartPolicy::Temporary),
5411            ],
5412        };
5413        s.validate().unwrap();
5414    }
5415
5416    #[test]
5417    fn json_uses_pascal_case_for_strategy_and_policy() {
5418        // Variant names are PascalCase by default in serde, matching
5419        // tatara-lisp's enum convention (`:estrategia OneForOne`).
5420        let c = child("w", "^0.1", RestartPolicy::Permanent);
5421        let json = serde_json::to_string(&c).unwrap();
5422        assert!(json.contains("\"Permanent\""));
5423        assert!(!json.contains("\"permanent\""));
5424
5425        let s = SupervisorSpec {
5426            estrategia: RestartStrategy::OneForOne,
5427            children: vec![c],
5428            ..SupervisorSpec::default()
5429        };
5430        let json = serde_json::to_string(&s).unwrap();
5431        assert!(json.contains("\"estrategia\":\"OneForOne\""));
5432    }
5433
5434    // ── shared duration codec: integer-magnitude canonical-form gate ──
5435    //
5436    // The gate lifts the discipline `crate::limits::parse_duration`
5437    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
5438    // the shared codec backing the remaining three typed-duration
5439    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
5440    // `:politicas :circuit-breaker :window`. Every magnitude `render`
5441    // emits is a non-negative integer with no decimal point and no
5442    // leading sign, so the codec's accepted set must match for
5443    // serialize/deserialize to round-trip without canonical-form
5444    // drift.
5445
5446    #[test]
5447    fn parse_accepts_integer_canonical_units() {
5448        // Pin the happy-path: every canonical author shape `render`
5449        // ever emits parses to the same `Duration` value, so the
5450        // codec's accepted set is at least a superset of its emitted
5451        // set on the canonical-unit axis.
5452        for (lit, dur) in [
5453            ("30s", Duration::from_secs(30)),
5454            ("500ms", Duration::from_millis(500)),
5455            ("2m", Duration::from_secs(120)),
5456            ("1h", Duration::from_secs(3600)),
5457            ("0s", Duration::ZERO),
5458        ] {
5459            assert_eq!(
5460                duration_codec::parse(lit).unwrap(),
5461                dur,
5462                "parse({lit:?}) should be {dur:?}"
5463            );
5464        }
5465    }
5466
5467    #[test]
5468    fn parse_accepts_bare_integer_as_seconds() {
5469        // The `"s" | ""` arm: a bare integer with no unit is read as
5470        // seconds. Pin this so the unit-empty form keeps parsing (it
5471        // renders to `"<n>s"` on serialize — that's a unit-choice
5472        // drift the integer-magnitude gate does NOT close, matching
5473        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
5474        // the peer `:limits :memory` codec).
5475        assert_eq!(
5476            duration_codec::parse("30").unwrap(),
5477            Duration::from_secs(30)
5478        );
5479    }
5480
5481    #[test]
5482    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
5483        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
5484        // on first serialize — DRIFT. The integer-magnitude gate names
5485        // the offending `"1.5"` verbatim and points at the canonical
5486        // remediation `"1500ms"`.
5487        let err = duration_codec::parse("1.5s").unwrap_err();
5488        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
5489        assert!(
5490            err.contains("not a non-negative integer"),
5491            "missing canonical-form reason in {err:?}"
5492        );
5493        assert!(
5494            err.contains("\"1500ms\""),
5495            "missing canonical-form remediation in {err:?}"
5496        );
5497    }
5498
5499    #[test]
5500    fn parse_rejects_decimal_shaped_integer_seconds() {
5501        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
5502        // `1s` exactly, so the round-trip looks correct — but the
5503        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
5504        // decimal-shape-with-integer-value form so author intent is
5505        // never silently rewritten.
5506        let err = duration_codec::parse("1.0s").unwrap_err();
5507        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
5508        assert!(
5509            err.contains("not a non-negative integer"),
5510            "missing canonical-form reason in {err:?}"
5511        );
5512    }
5513
5514    #[test]
5515    fn parse_rejects_half_unit_minute() {
5516        // `"0.5m"` is the unit-fraction footgun — author writes a
5517        // human-readable half-minute, serde silently rewrites to
5518        // `"30s"` on next emit. The gate names the offending
5519        // magnitude `"0.5"` and points at the integer-in-smaller-unit
5520        // form.
5521        let err = duration_codec::parse("0.5m").unwrap_err();
5522        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
5523        assert!(
5524            err.contains("\"30s\""),
5525            "missing canonical-form remediation in {err:?}"
5526        );
5527    }
5528
5529    #[test]
5530    fn parse_rejects_leading_plus_sign() {
5531        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
5532        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
5533        // cleanly to 30s and round-tripped to `"30s"` on next emit
5534        // (DRIFT). The digit-only gate closes the leading-sign class
5535        // first; the diagnostic names `"+30"` verbatim.
5536        let err = duration_codec::parse("+30s").unwrap_err();
5537        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
5538        assert!(
5539            err.contains("not a non-negative integer"),
5540            "missing canonical-form reason in {err:?}"
5541        );
5542    }
5543
5544    #[test]
5545    fn parse_rejects_leading_minus_sign() {
5546        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
5547        // rejected with `"negative duration in \"-30s\""`. Under the
5548        // integer-magnitude gate the diagnostic is unified — `-30` is
5549        // non-digit-only, f64-numeric, and surfaces with the canonical-
5550        // form reason (no leading `+` / `-` sign) naming the offending
5551        // `"-30"` verbatim. Same diagnostic shape as every other
5552        // rejected non-integer magnitude.
5553        let err = duration_codec::parse("-30s").unwrap_err();
5554        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
5555        assert!(
5556            err.contains("not a non-negative integer"),
5557            "missing canonical-form reason in {err:?}"
5558        );
5559    }
5560
5561    #[test]
5562    fn parse_garbage_still_falls_through_to_bad_magnitude() {
5563        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
5564        // through to the narrower "bad duration magnitude" arm — the
5565        // canonical-form diagnostic is reserved for the parser-shape
5566        // footgun case, not the "not a number at all" case. Same
5567        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
5568        // the peer `:limits :memory` codec.
5569        let err = duration_codec::parse("--1s").unwrap_err();
5570        assert!(
5571            err.contains("bad duration magnitude"),
5572            "expected bad-magnitude wording in {err:?}"
5573        );
5574    }
5575
5576    #[test]
5577    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
5578        // The accepted set is now closed under `u64`-exact integer
5579        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
5580        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
5581        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
5582        // possible. Pin the integer-exact arms across the four unit
5583        // suffixes so a future refactor that reaches back for f64
5584        // (`from_secs_f64`, `mul_f64`) surfaces here.
5585        assert_eq!(
5586            duration_codec::parse("3600s").unwrap(),
5587            Duration::from_secs(3600)
5588        );
5589        assert_eq!(
5590            duration_codec::parse("60m").unwrap(),
5591            Duration::from_secs(3600)
5592        );
5593        assert_eq!(
5594            duration_codec::parse("1h").unwrap(),
5595            Duration::from_secs(3600)
5596        );
5597        assert_eq!(
5598            duration_codec::parse("999ms").unwrap(),
5599            Duration::from_millis(999)
5600        );
5601    }
5602
5603    #[test]
5604    fn restart_window_serde_rejects_fractional_seconds() {
5605        // The shared codec backs `SupervisorSpec::restart_window`
5606        // (`with = "duration_codec"`) — so the gate applies on serde
5607        // deserialize for the typed Supervisor slot. A
5608        // `{"restartWindow":"1.5s"}` payload that previously round-
5609        // tripped to a different canonical string on next serialize
5610        // is now refused at deserialize with the integer-magnitude
5611        // diagnostic.
5612        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5613            "restartWindow":"1.5s",
5614            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5615        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5616        let msg = err.to_string();
5617        assert!(
5618            msg.contains("not a non-negative integer"),
5619            "expected integer-magnitude diagnostic in {msg:?}"
5620        );
5621        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
5622    }
5623
5624    #[test]
5625    fn restart_window_serde_rejects_leading_plus() {
5626        // The `u64::from_str` leading-`+` permissiveness gap that
5627        // motivated the digit-only gate (the `f64`-side accepted
5628        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
5629        // is now closed on the shared codec — surfaces as a structured
5630        // diagnostic at the serde layer for every typed-duration slot.
5631        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5632            "restartWindow":"+30s",
5633            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5634        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5635        let msg = err.to_string();
5636        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
5637        assert!(
5638            msg.contains("not a non-negative integer"),
5639            "missing canonical-form reason in {msg:?}"
5640        );
5641    }
5642
5643    #[test]
5644    fn parse_rejects_leading_zero_magnitude() {
5645        // `"030s"` is digit-only, so the existing non-digit-only / sign
5646        // / fractional arm doesn't catch it — `u64::from_str("030")`
5647        // returns `Ok(30)`, so before this gate `"030s"` parsed to
5648        // `Duration::from_secs(30)` and round-tripped through `render`
5649        // to `"30s"` — a *different* canonical string on the next emit,
5650        // breaking the THEORY.md Part V render-determinism contract
5651        // exactly the way `"+30s"` did before the leading-`+` arm
5652        // landed. Peer with the `rate_limit_codec` leading-zero arm
5653        // (4f46830) on the same canonical-form-drift axis.
5654        let err = duration_codec::parse("030s").unwrap_err();
5655        assert!(
5656            err.contains("non-canonical leading zero"),
5657            "expected leading-zero diagnostic in {err:?}"
5658        );
5659        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5660        assert!(
5661            err.contains("\"30s\""),
5662            "missing canonical-form remediation in {err:?}"
5663        );
5664        assert!(
5665            err.contains("THEORY.md"),
5666            "missing render-determinism citation in {err:?}"
5667        );
5668    }
5669
5670    #[test]
5671    fn parse_rejects_multi_digit_zero_magnitude() {
5672        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
5673        // digit-only, parse losslessly to `Duration::ZERO`, but render
5674        // back to `"0s"` (the single-byte canonical form) on the next
5675        // emit. The leading-zero arm refuses the drift class at the
5676        // codec layer; the semantic-zero gate downstream
5677        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
5678        // the single-byte canonical form `"0s"` separately on the
5679        // typed-validate layer.
5680        let err = duration_codec::parse("00s").unwrap_err();
5681        assert!(
5682            err.contains("non-canonical leading zero"),
5683            "expected leading-zero diagnostic in {err:?}"
5684        );
5685        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
5686    }
5687
5688    #[test]
5689    fn parse_rejects_leading_zero_per_hour_window() {
5690        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
5691        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
5692        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
5693        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
5694        // `h` / bare-integer-as-seconds) inherits the same gate.
5695        let err = duration_codec::parse("01h").unwrap_err();
5696        assert!(
5697            err.contains("non-canonical leading zero"),
5698            "expected leading-zero diagnostic in {err:?}"
5699        );
5700        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
5701    }
5702
5703    #[test]
5704    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
5705        // The `parse_accepts_bare_integer_as_seconds` happy-path
5706        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
5707        // multi-byte starts-with-`0`, parses losslessly to
5708        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
5709        // bare-integer surface accepts permissive unit-empty
5710        // shorthand but still must reject leading-zero padding.
5711        let err = duration_codec::parse("030").unwrap_err();
5712        assert!(
5713            err.contains("non-canonical leading zero"),
5714            "expected leading-zero diagnostic in {err:?}"
5715        );
5716        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5717    }
5718
5719    #[test]
5720    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
5721        // The codec-layer / typed-validate-layer boundary: `"0s"` /
5722        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
5723        // each round-trips losslessly through `render`
5724        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
5725        // accepts them. The downstream semantic-zero gates
5726        // (`SupervisorError::ZeroRestartWindow`,
5727        // `AplicacaoError::PolicyTimeoutZero`,
5728        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
5729        // zero-magnitude authoring at the typed-validate layer above,
5730        // peer with the `rate_limit_codec` codec-layer / typed-
5731        // validate-layer partition for `"0/s"`.
5732        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
5733        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
5734        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
5735    }
5736
5737    #[test]
5738    fn parse_accepts_canonical_magnitude_with_leading_one() {
5739        // The complementary boundary: a future tightening cannot
5740        // drift into rejecting valid canonical magnitudes that
5741        // happen to start with `1` (or any digit `[1-9]`). Pin
5742        // every canonical-unit suffix so the leading-zero arm
5743        // remains strictly narrower than the digit-only arm.
5744        assert_eq!(
5745            duration_codec::parse("100ms").unwrap(),
5746            Duration::from_millis(100)
5747        );
5748        assert_eq!(
5749            duration_codec::parse("100s").unwrap(),
5750            Duration::from_secs(100)
5751        );
5752        assert_eq!(
5753            duration_codec::parse("10m").unwrap(),
5754            Duration::from_secs(600)
5755        );
5756        assert_eq!(
5757            duration_codec::parse("10h").unwrap(),
5758            Duration::from_secs(36_000)
5759        );
5760    }
5761
5762    #[test]
5763    fn restart_window_serde_rejects_leading_zero() {
5764        // The shared codec backs `SupervisorSpec::restart_window`
5765        // (`with = "duration_codec"`) — so the leading-zero arm
5766        // applies on serde deserialize for the typed Supervisor slot.
5767        // A `{"restartWindow":"030s"}` payload that previously round-
5768        // tripped to a different canonical string on next serialize
5769        // is now refused at deserialize with the leading-zero
5770        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
5771        // / `restart_window_serde_rejects_fractional_seconds` on the
5772        // same canonical-form-drift axis.
5773        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5774            "restartWindow":"030s",
5775            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5776        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5777        let msg = err.to_string();
5778        assert!(
5779            msg.contains("non-canonical leading zero"),
5780            "expected leading-zero diagnostic in {msg:?}"
5781        );
5782        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
5783    }
5784
5785    #[test]
5786    fn parse_rejects_leading_whitespace() {
5787        // `" 30s"` — the canonical paste-from-aligned-doc /
5788        // paste-from-YAML-quoted-plain-scalar footgun. Before this
5789        // gate the top-level `s.trim()` at parse entry silently ate
5790        // the leading space and parsed the value to
5791        // `Duration::from_secs(30)`, which then round-tripped through
5792        // `render` to `"30s"` (a *different* canonical string on the
5793        // next emit) — the exact canonical-form-drift class the
5794        // leading-`+` / leading-zero arms already close, extended
5795        // to the whitespace-byte class. Peer with the sibling
5796        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
5797        // the M3 `:politicas` axis.
5798        let err = duration_codec::parse(" 30s").unwrap_err();
5799        assert!(
5800            err.contains("contains whitespace byte"),
5801            "expected whitespace diagnostic in {err:?}"
5802        );
5803        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5804        assert!(
5805            err.contains("THEORY.md"),
5806            "missing render-determinism contract citation in {err:?}"
5807        );
5808    }
5809
5810    #[test]
5811    fn parse_rejects_trailing_whitespace() {
5812        // `"30s "` — the canonical shell-history / trailing-space
5813        // paste footgun. Before this gate the top-level `s.trim()`
5814        // silently ate the trailing space and parsed to
5815        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
5816        // next emit — same canonical-form drift as the leading-space
5817        // sibling, closed on the same whitespace-byte arm.
5818        let err = duration_codec::parse("30s ").unwrap_err();
5819        assert!(
5820            err.contains("contains whitespace byte"),
5821            "expected whitespace diagnostic in {err:?}"
5822        );
5823        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5824    }
5825
5826    #[test]
5827    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
5828        // `"30 s"` — the canonical typographically-spaced author
5829        // shape (the same idiom every prose reference to a duration
5830        // renders as, mistakenly retained when the value is pasted
5831        // into a codec-shaped slot). Before this gate the per-part
5832        // `num_part.trim()` / `unit.trim()` calls silently ate the
5833        // whitespace between the magnitude and the unit and parsed
5834        // the value to `Duration::from_secs(30)`, round-tripping to
5835        // `"30s"` — the codec's *internal* whitespace-tolerance
5836        // vector, orthogonal to the leading / trailing surface but
5837        // the same canonical-form-drift class. Pins the arm as
5838        // strictly stronger than the pre-existing top-level
5839        // `s.trim()` behavior: it fires on whitespace anywhere in
5840        // the value, not just at the string boundary.
5841        let err = duration_codec::parse("30 s").unwrap_err();
5842        assert!(
5843            err.contains("contains whitespace byte"),
5844            "expected whitespace diagnostic in {err:?}"
5845        );
5846        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5847    }
5848
5849    #[test]
5850    fn parse_rejects_tab_byte() {
5851        // `"\t30s"` — the canonical paste-from-indented-doc /
5852        // paste-from-YAML-block-scalar footgun where a tab byte leads
5853        // the magnitude. Pins that the gate covers tab (`0x09`) as
5854        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
5855        // members and both would be silently swallowed by `s.trim()`
5856        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
5857        // space alone to the full ASCII-whitespace set (space `0x20`,
5858        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
5859        // the tab arm as a representative of the non-space members.
5860        let err = duration_codec::parse("\t30s").unwrap_err();
5861        assert!(
5862            err.contains("contains whitespace byte"),
5863            "expected whitespace diagnostic in {err:?}"
5864        );
5865        assert!(
5866            err.contains("0x09"),
5867            "missing offending tab byte in {err:?}"
5868        );
5869    }
5870
5871    #[test]
5872    fn restart_window_serde_rejects_whitespace() {
5873        // The shared codec backs `SupervisorSpec::restart_window`
5874        // (`with = "duration_codec"`) — so the whitespace arm
5875        // applies on serde deserialize for the typed Supervisor slot.
5876        // A `{"restartWindow":" 30s"}` payload that previously round-
5877        // tripped to a different canonical string on next serialize
5878        // is now refused at deserialize with the whitespace-byte
5879        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
5880        // / `restart_window_serde_rejects_leading_plus` /
5881        // `restart_window_serde_rejects_fractional_seconds` on the
5882        // same canonical-form-drift axis.
5883        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5884            "restartWindow":" 30s",
5885            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5886        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5887        let msg = err.to_string();
5888        assert!(
5889            msg.contains("contains whitespace byte"),
5890            "expected whitespace diagnostic in {msg:?}"
5891        );
5892        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
5893    }
5894
5895    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
5896    //
5897    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
5898    // duration codec — closes the strictly-complementary class the
5899    // byte-scan cannot see, through the lifted
5900    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
5901    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
5902    // and `:politicas :circuit-breaker :window` simultaneously via
5903    // this shared codec.
5904
5905    #[test]
5906    fn duration_codec_parse_rejects_leading_nbsp() {
5907        // NBSP prefix — the strictly-complementary drift class the
5908        // ASCII byte-scan cannot see. `str::trim` strips it silently
5909        // and the value drifts to `"30s"` on next serialize.
5910        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
5911        assert!(
5912            err.contains("non-ASCII Unicode whitespace character"),
5913            "expected non-ASCII whitespace diagnostic in {err:?}"
5914        );
5915        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
5916    }
5917
5918    #[test]
5919    fn duration_codec_parse_rejects_trailing_line_separator() {
5920        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
5921        // footgun.
5922        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
5923        assert!(
5924            err.contains("non-ASCII Unicode whitespace character"),
5925            "expected non-ASCII whitespace diagnostic in {err:?}"
5926        );
5927        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
5928    }
5929
5930    #[test]
5931    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
5932        // Positive-control pin: every ASCII-only canonical form the
5933        // renderer emits stays accepted through the new arm.
5934        assert_eq!(
5935            duration_codec::parse("30s").unwrap(),
5936            Duration::from_secs(30)
5937        );
5938        assert_eq!(
5939            duration_codec::parse("500ms").unwrap(),
5940            Duration::from_millis(500)
5941        );
5942        assert_eq!(
5943            duration_codec::parse("1h").unwrap(),
5944            Duration::from_secs(3600)
5945        );
5946    }
5947
5948    #[test]
5949    fn restart_window_serde_rejects_non_ascii_whitespace() {
5950        // The shared codec backs `SupervisorSpec::restart_window` — so
5951        // the new non-ASCII Unicode whitespace arm applies on serde
5952        // deserialize for the typed Supervisor slot. A
5953        // `{"restartWindow":" 30s"}` payload that previously
5954        // survived the ASCII byte-scan (only ASCII whitespace was
5955        // refused) is now refused at deserialize with the
5956        // non-ASCII-whitespace-and-codepoint diagnostic.
5957        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
5958            \"restartWindow\":\"\u{00A0}30s\",\
5959            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
5960        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5961        let msg = err.to_string();
5962        assert!(
5963            msg.contains("non-ASCII Unicode whitespace character"),
5964            "expected non-ASCII whitespace diagnostic in {msg:?}"
5965        );
5966        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
5967    }
5968
5969    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
5970
5971    #[test]
5972    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
5973        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
5974        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
5975        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
5976        // name the exact camelCase JSON keys the
5977        // `#[serde(rename_all = "camelCase")]` attribute on
5978        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
5979        // field carries `Some(_)` / non-empty) and pin that each canonical
5980        // byte-sequence appears verbatim in the JSON — a future accidental
5981        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
5982        // name flip at the derive attribute (any of which would silently
5983        // break every downstream JSON consumer that reaches for one of the
5984        // four consts via `Value::get(...)`) surfaces here as a build-time
5985        // test failure at `supervisor.rs`, not as an apply-time
5986        // `.get(<stale-canonical-const>)` returning `None` far from the
5987        // derive-attr drift's commit. Peer with the sibling
5988        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
5989        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
5990        // M2 typed-slot family established, extended here to close the
5991        // top-level Supervisor axis.
5992        let spec = SupervisorSpec {
5993            estrategia: RestartStrategy::OneForOne,
5994            max_restarts: 5,
5995            restart_window: Some(Duration::from_secs(60)),
5996            children: vec![ChildSpec {
5997                caixa: "w".into(),
5998                versao: "^0.1".into(),
5999                restart: RestartPolicy::Permanent,
6000            }],
6001        };
6002        let json = serde_json::to_string(&spec).unwrap();
6003        for key in [
6004            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6005            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6006            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6007            crate::render::SUPERVISOR_KEY_CHILDREN,
6008        ] {
6009            let quoted = format!("\"{key}\"");
6010            assert!(
6011                json.contains(&quoted),
6012                "serialized SupervisorSpec must carry the lifted \
6013                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
6014                 the JSON emission (got: {json})",
6015            );
6016        }
6017    }
6018
6019    #[test]
6020    fn supervisor_key_consts_are_pairwise_distinct() {
6021        // Cross-axis drift-detection pin: a future collapse of two
6022        // canonical top-level byte-strings onto the same value (e.g. an
6023        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
6024        // also read `"estrategia"`) would silently reroute every
6025        // downstream probe on one axis onto the sibling axis's overlay
6026        // entry and pass every propagation-probe test that expected only
6027        // the stale axis's value. Peer of the sibling four-way distinct
6028        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
6029        let all = [
6030            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6031            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6032            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6033            crate::render::SUPERVISOR_KEY_CHILDREN,
6034        ];
6035        for (i, a) in all.iter().enumerate() {
6036            for b in all.iter().skip(i + 1) {
6037                assert_ne!(
6038                    a, b,
6039                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
6040                     canonical byte-sequences — got `{a}` == `{b}`",
6041                );
6042            }
6043        }
6044    }
6045
6046    #[test]
6047    fn supervisor_key_consts_are_lower_camel_case_shape() {
6048        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
6049        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6050        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6051        // capital, no whitespace / dots) — the canonical shape the
6052        // `#[serde(rename_all = "camelCase")]` derive produces on
6053        // `SupervisorSpec`. A future flip to a non-camelCase attribute
6054        // at the derive surfaces both here (this test fails on the
6055        // stale-constant shape) and at
6056        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6057        // (that test fails on the mismatch between const and derive).
6058        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
6059        // (d8b8b4f) on the sibling M2 `:limits` axis.
6060        for key in [
6061            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6062            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6063            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6064            crate::render::SUPERVISOR_KEY_CHILDREN,
6065        ] {
6066            assert!(
6067                !key.is_empty(),
6068                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
6069            );
6070            let first = key.chars().next().unwrap();
6071            assert!(
6072                first.is_ascii_lowercase(),
6073                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
6074                 (got {key:?}, leads with {first:?})",
6075            );
6076            assert!(
6077                key.chars().all(|c| c.is_ascii_alphanumeric()),
6078                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
6079                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6080            );
6081        }
6082    }
6083
6084    #[test]
6085    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
6086        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
6087        // (camelCase JSON keys, no leading colon) must never collide
6088        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
6089        // consts (kebab-case author-facing labels with leading colon)
6090        // that sit next to them at `caixa_core::render`. Both families
6091        // cover the same four typed Supervisor slots on two distinct
6092        // axes (author-side kebab vs renderer-side camelCase);
6093        // collapsing either family onto the other's byte-shape would
6094        // silently reroute the render-side probe onto the author-facing
6095        // surface, or vice versa. Peer of the byte-distinctness
6096        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
6097        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
6098        let pairs = [
6099            (
6100                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6101                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
6102            ),
6103            (
6104                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6105                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
6106            ),
6107            (
6108                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6109                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
6110            ),
6111            (
6112                crate::render::SUPERVISOR_KEY_CHILDREN,
6113                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
6114            ),
6115        ];
6116        for (json_key, author_key) in pairs {
6117            assert_ne!(
6118                json_key, author_key,
6119                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
6120                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
6121                 got JSON `{json_key}` == author `{author_key}`",
6122            );
6123        }
6124    }
6125
6126    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
6127
6128    #[test]
6129    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
6130        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
6131        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
6132        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
6133        // keys the `#[serde(rename_all = "camelCase")]` attribute on
6134        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
6135        // pin that each canonical byte-sequence appears verbatim in the
6136        // JSON — a future accidental `rename_all = "snake_case"` /
6137        // `"kebab-case"` / verbatim-field-name flip at the derive
6138        // attribute (any of which would silently break every downstream
6139        // JSON consumer that reaches for one of the three consts via
6140        // `Value::get(...)`) surfaces here as a build-time test failure at
6141        // `supervisor.rs`, not as an apply-time
6142        // `.get(<stale-canonical-const>)` returning `None` far from the
6143        // derive-attr drift's commit. Peer with the enclosing
6144        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6145        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
6146        // discipline the SupervisorSpec top-level lift established,
6147        // extended here to the sibling per-`:children` entry `ChildSpec`
6148        // derive so the last M2 typed-struct sub-block
6149        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
6150        // surface without a lifted serde-key peer joins the substrate's
6151        // "one canonical byte-string per typed serialized-key axis"
6152        // discipline.
6153        let c = ChildSpec {
6154            caixa: "worker".into(),
6155            versao: "^0.1".into(),
6156            restart: RestartPolicy::Permanent,
6157        };
6158        let json = serde_json::to_string(&c).unwrap();
6159        for key in [
6160            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6161            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6162            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6163        ] {
6164            let quoted = format!("\"{key}\"");
6165            assert!(
6166                json.contains(&quoted),
6167                "serialized ChildSpec must carry the lifted \
6168                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
6169                 in the JSON emission (got: {json})",
6170            );
6171        }
6172    }
6173
6174    #[test]
6175    fn supervisor_child_key_consts_are_pairwise_distinct() {
6176        // Cross-axis drift-detection pin: a future collapse of two
6177        // canonical `ChildSpec` per-entry byte-strings onto the same
6178        // value (e.g. an accidental copy-paste flip of
6179        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
6180        // silently reroute every downstream probe on one axis onto the
6181        // sibling axis's overlay entry and pass every propagation-probe
6182        // test that expected only the stale axis's value. Peer of the
6183        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
6184        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
6185        // pair (ce80ca0).
6186        let all = [
6187            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6188            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6189            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6190        ];
6191        for (i, a) in all.iter().enumerate() {
6192            for b in all.iter().skip(i + 1) {
6193                assert_ne!(
6194                    a, b,
6195                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
6196                     distinct canonical byte-sequences — got `{a}` == `{b}`",
6197                );
6198            }
6199        }
6200    }
6201
6202    #[test]
6203    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
6204        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
6205        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6206        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6207        // capital, no whitespace / dots) — the canonical shape the
6208        // `#[serde(rename_all = "camelCase")]` derive produces on
6209        // `ChildSpec`. A future flip to a non-camelCase attribute at the
6210        // derive surfaces both here (this test fails on the
6211        // stale-constant shape) and at
6212        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
6213        // (that test fails on the mismatch between const and derive).
6214        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
6215        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
6216        for key in [
6217            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6218            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6219            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6220        ] {
6221            assert!(
6222                !key.is_empty(),
6223                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
6224            );
6225            let first = key.chars().next().unwrap();
6226            assert!(
6227                first.is_ascii_lowercase(),
6228                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
6229                 byte (got {key:?}, leads with {first:?})",
6230            );
6231            assert!(
6232                key.chars().all(|c| c.is_ascii_alphanumeric()),
6233                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
6234                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6235            );
6236        }
6237    }
6238
6239    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
6240
6241    #[test]
6242    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
6243        // The fail-before-pass-after pin: pre-lift there was no
6244        // single-source binding between the [`RestartStrategy`] variant
6245        // name the un-`rename`d `Serialize` derive emits under
6246        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
6247        // every downstream cluster-side dispatcher (the future
6248        // wasm-operator's per-supervisor sibling-restart branch, the
6249        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
6250        // admission-time enum-arm bind, the `caixa-operator`'s
6251        // hierarchical reconciliation scheduler's per-strategy fan-out)
6252        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
6253        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
6254        // override, or a variant rename in the source — would silently
6255        // rebrand the emitted scalar under one spelling while every
6256        // downstream dispatcher still probed the other, with the failure
6257        // surfacing at the operator's reconcile posture (subtrees coming
6258        // up under the `default()` `OneForOne` arm rather than the typed
6259        // slot's declared strategy — a bad child would then only take
6260        // itself down instead of the sibling set the author intended, so
6261        // shared-state children fall out of sync) far from the source
6262        // rebrand commit and with no field naming the drift. Pinning the
6263        // two paths (the `Serialize` derive's serialized string AND the
6264        // [`RestartStrategy::as_str`] helper) to the same four lifted
6265        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
6266        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
6267        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
6268        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
6269        // byte-strings makes any future drift on either endpoint fail
6270        // here at caixa-core build time. Peer of the M3
6271        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
6272        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
6273        // three-path-convergence discipline, extended to close the
6274        // OTP-shaped per-supervisor sibling-restart axis.
6275        for (variant, expected) in [
6276            (
6277                RestartStrategy::OneForOne,
6278                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6279            ),
6280            (
6281                RestartStrategy::OneForAll,
6282                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6283            ),
6284            (
6285                RestartStrategy::RestForOne,
6286                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6287            ),
6288            (
6289                RestartStrategy::SimpleOneForOne,
6290                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6291            ),
6292        ] {
6293            let json = serde_json::to_string(&variant).unwrap();
6294            assert_eq!(
6295                json,
6296                format!("\"{expected}\""),
6297                "RestartStrategy::{variant:?} must serialize to {expected:?}"
6298            );
6299            assert_eq!(
6300                variant.as_str(),
6301                expected,
6302                "RestartStrategy::{variant:?}.as_str() must return the lifted \
6303                 SUPERVISOR_ESTRATEGIA_* constant"
6304            );
6305        }
6306    }
6307
6308    #[test]
6309    fn supervisor_estrategia_consts_are_pairwise_distinct() {
6310        // Cross-arm drift-detection pin: a future collapse of two
6311        // canonical variant byte-strings onto the same value (e.g. an
6312        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
6313        // to also read `"OneForOne"`) would silently reroute every
6314        // downstream operator's per-strategy dispatch onto the sibling
6315        // arm's reconcile branch and pass every propagation-probe test
6316        // that expected only the stale arm's value — the mis-strategied
6317        // subtree would come up with the wrong sibling-restart posture
6318        // on every subsequent failure. Peer of the sibling four-way
6319        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
6320        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
6321        let all = [
6322            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6323            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6324            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6325            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6326        ];
6327        for (i, a) in all.iter().enumerate() {
6328            for (j, b) in all.iter().enumerate() {
6329                if i != j {
6330                    assert_ne!(
6331                        a, b,
6332                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
6333                         — got duplicate {a:?} at indices {i} and {j}",
6334                    );
6335                }
6336            }
6337        }
6338    }
6339
6340    #[test]
6341    fn restart_strategy_display_routes_through_as_str_helper() {
6342        // The fail-before-pass-after pin on the first half of the
6343        // three-path convergence: pre-convergence the sibling
6344        // OTP-shape typed enum [`RestartStrategy`] carried a
6345        // [`std::fmt::Display`] surface via its
6346        // `#[discriminant(also_display)]` gen-platform derive route,
6347        // which arrived kebab-case as `"one-for-one"` /
6348        // `"one-for-all"` / `"rest-for-one"` /
6349        // `"simple-one-for-one"` while the wire format ran as
6350        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
6351        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
6352        // Every consumer reaching for a strategy byte-string past the
6353        // wire format had to pick between three paths
6354        // ([`RestartStrategy::as_str`], the `Serialize` derive's
6355        // serialized string, or `format!("{v}")` on the
6356        // discriminant-Display route), any two of which a future
6357        // variant rename or `#[serde(rename_all = "kebab-case")]`
6358        // attribute would silently desynchronize. Wiring
6359        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
6360        // closes the third path: every `format!("{v}")` call reaches
6361        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6362        // const the wire format and the [`RestartStrategy::as_str`]
6363        // helper already route through, so a future variant rename
6364        // lands at exactly one place. Pin the routing here so a future
6365        // `impl std::fmt::Display for RestartStrategy`
6366        // reimplementation that hand-rolls the arms instead of
6367        // delegating to [`RestartStrategy::as_str`] fails at
6368        // caixa-core build time. Peer of the M3
6369        // `placement_strategy_display_routes_through_as_str_helper`
6370        // (cc8f749) which the M3 axis converged first.
6371        for &variant in RestartStrategy::ALL {
6372            assert_eq!(
6373                variant.to_string(),
6374                variant.as_str(),
6375                "RestartStrategy::{variant:?} Display must route through \
6376                 RestartStrategy::as_str (single source of truth: the lifted \
6377                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
6378            );
6379        }
6380    }
6381
6382    #[test]
6383    fn restart_strategy_display_matches_serialized_wire_byte_string() {
6384        // The fail-before-pass-after pin on the second half of the
6385        // three-path convergence: `Display` (user-facing text) agrees
6386        // byte-for-byte with the `Serialize` derive's wire format
6387        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
6388        // scalar) on every variant. Pre-convergence the two paths
6389        // were structurally independent — a future
6390        // `#[serde(rename_all = "kebab-case")]` attribute on the
6391        // enum would silently rebrand the emitted wire scalar
6392        // (`one-for-one`, `one-for-all`, `rest-for-one`,
6393        // `simple-one-for-one`) while every consumer that
6394        // pretty-prints the strategy (the future wasm-operator's
6395        // per-supervisor sibling-restart-strategy diagnostic line,
6396        // the future `feira app graph` per-supervisor strategy line,
6397        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
6398        // materializer's admission-webhook rejection body) would
6399        // still emit the PascalCase form the `as_str` / `Display`
6400        // route returns, with the mismatch surfacing at consumer
6401        // parse time / operator dispatch time far from the source
6402        // rebrand commit. Pin the two paths byte-for-byte here so any
6403        // future serde-attribute or variant-rename drift is a
6404        // caixa-core-build-time test failure at this call, not a
6405        // silent per-consumer dispatch miss. Peer of the M3
6406        // `placement_strategy_display_matches_serialized_wire_byte_string`
6407        // (cc8f749) which the M3 axis converged first.
6408        for &variant in RestartStrategy::ALL {
6409            let wire = serde_json::to_string(&variant).unwrap();
6410            let unquoted = wire
6411                .strip_prefix('"')
6412                .and_then(|s| s.strip_suffix('"'))
6413                .expect("serialized RestartStrategy is a JSON string");
6414            assert_eq!(
6415                variant.to_string(),
6416                unquoted,
6417                "RestartStrategy::{variant:?} Display byte-string must match the \
6418                 Serialize derive's wire byte-string (three-path convergence: \
6419                 Display + as_str + Serialize all resolve to the same \
6420                 SUPERVISOR_ESTRATEGIA_* const)"
6421            );
6422        }
6423    }
6424
6425    #[test]
6426    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
6427        // Fail-before-pass-after byte-parity pin on the lifted
6428        // `impl AsRef<str> for RestartStrategy` — asserts the
6429        // standard-library trait impl and the substrate-primitive
6430        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
6431        // to the same `&str` per instance across the four-arm
6432        // closed set, so any future silent detour that routes the
6433        // impl through a divergent projection (a per-arm inline
6434        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
6435        // re-inlining that opens a compile-time link to the un-lifted
6436        // arm-literal, a swap onto the kebab-case
6437        // [`gen_platform::Discriminant`] catalog identity that would
6438        // collide the wire axis with the dispatcher-catalog axis) trips
6439        // at caixa-core test time under `PartialEq` rather than at a
6440        // downstream `impl AsRef<str>`-bound consumer's silent split.
6441        // Sweeps every one of the four arms
6442        // [`RestartStrategy::ALL`] carries so no arm's projection is
6443        // covered only by the sibling wire-format `Serialize` derive
6444        // path. Peer of the sibling
6445        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
6446        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
6447        // top-level `:versao` typed newtype — the two pins together
6448        // cover the substrate primitive's `AsRef<str>` projection axis
6449        // on the paired newtype + closed-set-typed-enum surface.
6450        for &variant in RestartStrategy::ALL {
6451            assert_eq!(
6452                <RestartStrategy as AsRef<str>>::as_ref(&variant),
6453                variant.as_str(),
6454                "AsRef<str> impl on RestartStrategy::{variant:?} must \
6455                 byte-equal RestartStrategy::as_str on the same instance \
6456                 — divergence signals a silent detour off the substrate-\
6457                 primitive accessor"
6458            );
6459        }
6460    }
6461
6462    #[test]
6463    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
6464        // Fail-before-pass-after byte-parity pin on the three-path
6465        // convergence discipline the M2 sibling-restart primitive now
6466        // carries on the `&str`-projection axis:
6467        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
6468        // lifted impl), `format!("{s}")` (the pre-existing
6469        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
6470        // primitive `pub const fn` accessor both trait impls delegate
6471        // through) must resolve to the same byte-string on every
6472        // instance across the four-arm closed set. Refuses any future
6473        // divergence between the two trait impls (a stray
6474        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
6475        // rather than delegating through the shared accessor; a
6476        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
6477        // literal cascade) that would silently split the two
6478        // projection paths of the same closed-set typed enum. Mirrors
6479        // the sibling three-path-convergence discipline the peer
6480        // [`crate::CaixaVersion`] typed newtype carries on its
6481        // `AsRef<str>` / `Display` / `as_str` triple
6482        // (version.rs pin
6483        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
6484        // 16d5c7e).
6485        for &variant in RestartStrategy::ALL {
6486            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
6487            let via_display: String = format!("{variant}");
6488            let via_accessor: &str = variant.as_str();
6489            assert_eq!(via_as_ref, via_accessor);
6490            assert_eq!(via_display, via_accessor);
6491            assert_eq!(via_as_ref, via_display.as_str());
6492        }
6493    }
6494
6495    #[test]
6496    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
6497        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
6498        // exhaustive-iteration surface: every variant appears exactly
6499        // once, and the slice length matches the arm count of the
6500        // closed set. Every consumer that walks the accepted-strategy
6501        // set (a future `feira supervisor --estrategia …` CLI-side
6502        // arg-parse's "did you mean" hint, a future M4 admission-
6503        // webhook's rejection body naming the accepted-`:estrategia`
6504        // list, the [`RestartStrategy::from_wire`] reverse-projection
6505        // consumers that iterate the accept-set for diagnostic
6506        // rendering) reads through this slice, so a future arm addition
6507        // that grows the enum but forgets to grow [`Self::ALL`]
6508        // silently truncates every downstream consumer's accept-set at
6509        // the same pre-addition boundary — this pin fails at caixa-core
6510        // build time on the pairwise-distinct + arm-count invariants.
6511        //
6512        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
6513        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
6514        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
6515        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6516        // pins on the peer closed-set typed-enum axes.
6517        let all: &[RestartStrategy] = RestartStrategy::ALL;
6518        assert_eq!(
6519            all.len(),
6520            4,
6521            "RestartStrategy::ALL must enumerate every variant of the \
6522             four-arm closed set (OneForOne, OneForAll, RestForOne, \
6523             SimpleOneForOne); got {all:?}"
6524        );
6525        for (i, a) in all.iter().enumerate() {
6526            for (j, b) in all.iter().enumerate() {
6527                if i != j {
6528                    assert_ne!(
6529                        a, b,
6530                        "RestartStrategy::ALL must carry every variant exactly \
6531                         once — got duplicate {a:?} at indices {i} and {j}"
6532                    );
6533                }
6534            }
6535        }
6536        for variant in [
6537            RestartStrategy::OneForOne,
6538            RestartStrategy::OneForAll,
6539            RestartStrategy::RestForOne,
6540            RestartStrategy::SimpleOneForOne,
6541        ] {
6542            assert!(
6543                all.contains(&variant),
6544                "RestartStrategy::ALL must contain {variant:?} — a future arm \
6545                 addition that grows the enum but forgets to grow the ALL slice \
6546                 silently truncates every downstream consumer's accept-set at \
6547                 the pre-addition boundary"
6548            );
6549        }
6550    }
6551
6552    #[test]
6553    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
6554        // Fail-before-pass-after pin on the forward accept-set of the
6555        // [`RestartStrategy::from_wire`] reverse projection: every
6556        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6557        // constant the [`RestartStrategy::as_str`] emitter walks parses
6558        // back to its paired variant. Any future arm addition that
6559        // grows the emitter's `as_str` match but forgets to grow the
6560        // parser's `from_wire` match silently splits the two halves of
6561        // the round-trip — the wire byte-string one non-serde consumer
6562        // parses from the one the emitter wrote — with the failure
6563        // surfacing at parse time far from the rebrand commit. Pinning
6564        // the four-arm accept-set here catches the drift at caixa-core
6565        // build time.
6566        //
6567        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
6568        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
6569        // accept-set pins on the peer closed-set typed-enum `str → Self`
6570        // axes.
6571        for (wire, expected) in [
6572            (
6573                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6574                RestartStrategy::OneForOne,
6575            ),
6576            (
6577                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6578                RestartStrategy::OneForAll,
6579            ),
6580            (
6581                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6582                RestartStrategy::RestForOne,
6583            ),
6584            (
6585                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6586                RestartStrategy::SimpleOneForOne,
6587            ),
6588        ] {
6589            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6590                panic!(
6591                    "RestartStrategy::from_wire({wire:?}) must accept every \
6592                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
6593                     lifted canonical byte-string that RestartStrategy::{expected:?} \
6594                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
6595                )
6596            });
6597            assert_eq!(
6598                parsed, expected,
6599                "RestartStrategy::from_wire({wire:?}) must return \
6600                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
6601            );
6602        }
6603    }
6604
6605    #[test]
6606    fn restart_strategy_from_wire_round_trips_through_as_str() {
6607        // Fail-before-pass-after pin on the closed round-trip between
6608        // the forward [`RestartStrategy::as_str`] emitter and the
6609        // reverse [`RestartStrategy::from_wire`] parser: for every
6610        // variant in [`RestartStrategy::ALL`], parsing the emitter's
6611        // output must return exactly the same variant. Any per-arm
6612        // divergence — a future arm added to `as_str` but not
6613        // `from_wire`, an accidental copy-paste flip in one but not
6614        // the other — silently splits the emit and parse halves and
6615        // the failure surfaces at consumer parse time far from the
6616        // drift site. The `ALL`-iterating shape means a future arm
6617        // addition picks up the coverage by construction.
6618        //
6619        // Peer of the sibling
6620        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
6621        // (18c7342) round-trip pin on
6622        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
6623        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
6624        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
6625        for &variant in RestartStrategy::ALL {
6626            let wire = variant.as_str();
6627            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6628                panic!(
6629                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6630                     must be Some({variant:?}) — the two halves of the round-trip \
6631                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
6632                     got None on wire byte-string {wire:?}"
6633                )
6634            });
6635            assert_eq!(
6636                parsed, variant,
6637                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6638                 must round-trip to the same variant; got {parsed:?}"
6639            );
6640        }
6641    }
6642
6643    #[test]
6644    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
6645        // Fail-before-pass-after pin on the closed-set refusal
6646        // discipline of [`RestartStrategy::from_wire`]: every
6647        // byte-string outside the four-arm accept-set returns `None`
6648        // rather than silently collapsing onto the [`Default`]
6649        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
6650        // exercised here sweeps the load-bearing drift shapes: the
6651        // empty string (a stripped serde-attribute drift), all-
6652        // whitespace strings (the canonical text-editor accidental
6653        // padding shape), the kebab-case dispatcher-catalog identities
6654        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
6655        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
6656        // derived [`std::str::FromStr`] accept-set, which parses the
6657        // *other* axis of this enum's two-axis split and must not leak
6658        // into the `from_wire` PascalCase-wire accept-set), the
6659        // lowercased single-word forms (`"oneforone"`), the padded
6660        // canonical scalar (`" OneForOne "`), the trailing-newline
6661        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
6662        // (`"AllForOne"` — the canonical typo direction).
6663        //
6664        // Peer of the sibling
6665        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
6666        // (2aa6d23) +
6667        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
6668        // (18c7342) refusal pins on the peer closed-set typed-enum
6669        // axes.
6670        for bad in [
6671            "",
6672            " ",
6673            "\n",
6674            "\t",
6675            "one-for-one",
6676            "one-for-all",
6677            "rest-for-one",
6678            "simple-one-for-one",
6679            "oneforone",
6680            "OneForOnes",
6681            "one_for_one",
6682            "one for one",
6683            "ONEFORONE",
6684            "OneForOne ",
6685            " OneForOne",
6686            " SimpleOneForOne ",
6687            "OneForOne\n",
6688            "restforone",
6689            "REST_FOR_ONE",
6690            "AllForOne",
6691            "Simple",
6692            "?",
6693        ] {
6694            assert!(
6695                RestartStrategy::from_wire(bad).is_none(),
6696                "RestartStrategy::from_wire({bad:?}) must return None — the \
6697                 parser's accept-set is exactly the four RestartStrategy::as_str \
6698                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
6699                 and this byte-string is outside that closed set"
6700            );
6701        }
6702    }
6703
6704    #[test]
6705    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
6706        // Fail-before-pass-after pin on the fourth path of the four-path
6707        // convergence: `from_wire` (the reverse projection) inverts the
6708        // `Serialize` derive's wire byte-string on every variant.
6709        // Together with the pre-existing three-path convergence
6710        // (`Display` + `as_str` + `Serialize` all resolve to the same
6711        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
6712        // pinned by
6713        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
6714        // this closes the round-trip: the wire byte-string the
6715        // `Serialize` derive emits parses back to the same variant
6716        // through `from_wire`, so any future serde-attribute or variant-
6717        // rename drift on the emit half now surfaces as a matched drift
6718        // on the parse half at caixa-core build time — the two halves
6719        // migrate as a unit through the lifted consts on any future
6720        // rename, and the round-trip cannot silently split.
6721        //
6722        // Peer of the sibling
6723        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6724        // (18c7342) wire-format pin on
6725        // [`crate::aplicacao::PlacementStrategy::from_wire`].
6726        for &variant in RestartStrategy::ALL {
6727            let wire = serde_json::to_string(&variant).unwrap();
6728            let unquoted = wire
6729                .strip_prefix('"')
6730                .and_then(|s| s.strip_suffix('"'))
6731                .expect("serialized RestartStrategy is a JSON string");
6732            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
6733                panic!(
6734                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
6735                     Serialize derive's wire byte-string for \
6736                     RestartStrategy::{variant:?} — the four-path convergence \
6737                     (Display + as_str + Serialize + from_wire) resolves through \
6738                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
6739                )
6740            });
6741            assert_eq!(
6742                parsed, variant,
6743                "RestartStrategy::from_wire of the Serialize derive's wire \
6744                 byte-string for RestartStrategy::{variant:?} must round-trip \
6745                 to the same variant; got {parsed:?}"
6746            );
6747        }
6748    }
6749
6750    #[test]
6751    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
6752        // Fail-before-pass-after byte-parity pin on the newly lifted
6753        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
6754        // library trait impl and the substrate-primitive
6755        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
6756        // the same four-arm accept-set across every arm the exhaustive
6757        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
6758        // detour that routes the trait impl through a divergent projection
6759        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
6760        // … }` re-inlining that opens a compile-time link to the un-
6761        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
6762        // attribute drift that silently splits the wire byte-string from
6763        // every consumer that reaches for this typed dispatch, an
6764        // accidental swap onto the kebab-case dispatcher-catalog axis the
6765        // pre-existing [`std::str::FromStr`] impl parses through and which
6766        // would collide the two-axis wire/catalog split the sibling
6767        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
6768        // trips at caixa-core test time under `assert_eq!` rather than at
6769        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
6770        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
6771        // carries so no arm's projection is covered only by the sibling
6772        // method-named `from_wire` path. Peer of the sibling
6773        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
6774        // (3c83606),
6775        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
6776        // (bf33136), and the M3
6777        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
6778        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
6779        // onto the first M2-OTP-shape closed-set typed enum on the caixa
6780        // surface.
6781        for &variant in RestartStrategy::ALL {
6782            let wire = variant.as_str();
6783            assert_eq!(
6784                <RestartStrategy as TryFrom<&str>>::try_from(wire),
6785                Ok(variant),
6786                "TryFrom<&str> impl on RestartStrategy must round-trip \
6787                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
6788                 Ok(RestartStrategy::{variant:?}) — divergence from \
6789                 RestartStrategy::from_wire signals a silent detour off \
6790                 the substrate-primitive accessor"
6791            );
6792            assert_eq!(
6793                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
6794                RestartStrategy::from_wire(wire),
6795                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
6796                 RestartStrategy::from_wire on the same input"
6797            );
6798        }
6799    }
6800
6801    #[test]
6802    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
6803        // Rejection witness on the `impl TryFrom<&str> for
6804        // RestartStrategy` — sweeps a candidate set of byte-strings
6805        // outside the four-arm PascalCase wire accept-set the sibling
6806        // [`RestartStrategy::as_str`] emits and asserts every one lands on
6807        // `Err(())`, so a future accidental widening of the trait impl's
6808        // accept-set (a stray additional
6809        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
6810        // path, a silent inclusion of the kebab-case dispatcher-catalog
6811        // byte-string the pre-existing [`std::str::FromStr`] impl the
6812        // [`gen_platform::FromStrKind`] derive installs parses onto the
6813        // wire axis — which would collide the two-axis
6814        // wire/dispatcher-catalog split the sibling
6815        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
6816        // an English-rebrand or plural-arm silent alias that would
6817        // widen the wire accept-set past the OTP-canonical four) trips at
6818        // caixa-core test time. The candidate set includes the empty
6819        // string, whitespace-only padding, the kebab-case dispatcher-
6820        // catalog byte-strings on the sibling axis (a caller who confuses
6821        // the two axes trips here rather than at a downstream consumer's
6822        // silent reject), a lowercase / uppercase / mixed-case fold of
6823        // each PascalCase arm (a caller who assumes case-fold acceptance
6824        // trips here), leading/trailing whitespace padding, the trailing-
6825        // newline shape, quote-wrapped candidates, and a residual set of
6826        // plausible-but-wrong English rebrand candidates. Peer of the
6827        // sibling
6828        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
6829        // (3c83606) and
6830        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
6831        // (6fd00cd) rejection witnesses.
6832        let rejected: &[&str] = &[
6833            "",
6834            " ",
6835            "\n",
6836            "\t",
6837            "one-for-one",
6838            "one-for-all",
6839            "rest-for-one",
6840            "simple-one-for-one",
6841            "oneforone",
6842            "one_for_one",
6843            "OneForOnes",
6844            "ONEFORONE",
6845            "oneforall",
6846            "restforone",
6847            "simpleoneforone",
6848            "OneForOne ",
6849            " OneForOne",
6850            " OneForAll ",
6851            "OneForOne\n",
6852            "RestForOne\t",
6853            "OneForEach",
6854            "AllForOne",
6855            "one for one",
6856            "\"OneForOne\"",
6857            "?",
6858        ];
6859        for &input in rejected {
6860            assert_eq!(
6861                <RestartStrategy as TryFrom<&str>>::try_from(input),
6862                Err(()),
6863                "TryFrom<&str> impl on RestartStrategy must reject the \
6864                 non-wire byte-string {input:?} — silent acceptance signals \
6865                 an accept-set widening off the paired \
6866                 RestartStrategy::from_wire resolver"
6867            );
6868        }
6869    }
6870
6871    #[test]
6872    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
6873        // Cross-axis partition pin: the paired `TryFrom<&str>` and
6874        // `from_wire` reverse projections must resolve identically on
6875        // *every* input, not just the ones [`RestartStrategy::ALL`]
6876        // enumerates. Sweeps a mixed candidate set spanning accepted
6877        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
6878        // dispatcher-catalog byte-strings, empty, whitespace-padded,
6879        // quoted, English-rebrand candidates) inputs and asserts the
6880        // trait's `Result::ok()` projection byte-equals the method-named
6881        // resolver's `Option<Self>` return-shape on each, locking the two
6882        // paths together by construction so any future detour (a stray
6883        // `try_from` special-case that widens or narrows the accept-set
6884        // outside the paired `from_wire` resolver, an accidental swap
6885        // onto the kebab-case [`std::str::FromStr`] impl the
6886        // [`gen_platform::FromStrKind`] derive installs on the sibling
6887        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
6888        // the sibling
6889        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
6890        // pin — extends the round-trip discipline onto the M2-OTP-shape
6891        // sibling-restart axis.
6892        let candidates: &[&str] = &[
6893            "OneForOne",
6894            "OneForAll",
6895            "RestForOne",
6896            "SimpleOneForOne",
6897            "",
6898            "one-for-one",
6899            "one-for-all",
6900            "rest-for-one",
6901            "simple-one-for-one",
6902            "oneforone",
6903            "unknown",
6904            "OneForOne ",
6905            " OneForOne",
6906            "\"OneForOne\"",
6907            "OneForEach",
6908            "?",
6909        ];
6910        for &input in candidates {
6911            let via_trait: Option<RestartStrategy> =
6912                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
6913            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
6914            assert_eq!(
6915                via_trait, via_method,
6916                "TryFrom<&str> and from_wire must resolve identically on \
6917                 input {input:?} — divergence signals the two reverse-\
6918                 projection paths have drifted onto different accept-sets"
6919            );
6920        }
6921    }
6922
6923    #[test]
6924    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
6925        // Fail-before-pass-after byte-parity pin on the newly lifted
6926        // `impl From<RestartStrategy> for &'static str` — asserts the
6927        // standard-library trait impl and the substrate-primitive
6928        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
6929        // the same four-arm emit-set across every arm the exhaustive
6930        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
6931        // detour that routes the trait impl through a divergent
6932        // projection (a per-arm inline `match strategy { OneForOne =>
6933        // "OneForOne", … }` re-inlining that opens a compile-time link to
6934        // the un-lifted arm-literal, an accidental swap onto the sibling
6935        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
6936        // would collide the two-axis wire/catalog split the sibling
6937        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
6938        // at caixa-core test time under `assert_eq!` rather than at a
6939        // downstream `impl Into<&'static str>`-bound consumer's silent
6940        // split. Sweeps every one of the four arms
6941        // [`RestartStrategy::ALL`] carries so no arm's projection is
6942        // covered only by the sibling method-named `as_str` /
6943        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
6944        // `<&'static str as From<RestartStrategy>>::from` output in a
6945        // `const`-shape binding to make the `'static` lifetime promise a
6946        // build-time invariant — a future accidental downgrade of any of
6947        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6948        // constants to a non-`&'static str` (a `String::leak()`-produced
6949        // return, a `Box::leak`-cast) trips at caixa-core build time
6950        // rather than at a downstream `'static`-bound consumer.
6951        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
6952        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
6953        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
6954        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
6955        for &variant in RestartStrategy::ALL {
6956            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
6957            let via_method: &'static str = variant.as_str();
6958            assert_eq!(
6959                via_trait, via_method,
6960                "From<RestartStrategy> for &'static str impl must round-trip \
6961                 RestartStrategy::{variant:?} to the same lifted \
6962                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
6963                 divergence signals a silent detour off the substrate-primitive \
6964                 accessor"
6965            );
6966            let via_into: &'static str = variant.into();
6967            assert_eq!(
6968                via_into, via_method,
6969                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
6970                 byte-equal RestartStrategy::as_str on the same input — the \
6971                 blanket-derived Into shape must resolve to the same as_str \
6972                 dispatch as the explicit From impl"
6973            );
6974        }
6975        assert_eq!(
6976            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
6977            [
6978                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6979                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6980                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6981                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6982            ],
6983            "const-context RestartStrategy::as_str must resolve to the four \
6984             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
6985             downgrade of any arm to a non-const or non-static byte-string \
6986             breaks the `&'static str`-lifetime promise the paired \
6987             From<RestartStrategy> for &'static str impl carries by \
6988             construction"
6989        );
6990    }
6991
6992    #[test]
6993    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
6994        // Cross-axis partition pin: the paired trait-idiomatic
6995        // `From<RestartStrategy> for &'static str` forward projection and
6996        // the method-named [`RestartStrategy::as_str`] forward projection
6997        // must resolve identically on *every* arm, not just the ones
6998        // named in the primary byte-parity pin above. Sweeps every
6999        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
7000        // output byte-equals the method-named accessor's return-value on
7001        // each, locking the two forward-projection paths together by
7002        // construction so any future detour (a stray `From` special-case
7003        // that lands on a divergent per-arm literal outside the paired
7004        // `as_str` dispatch, a hypothetical rebrand touching one axis
7005        // without the other) trips at caixa-core test time. Peer of the
7006        // sibling reverse-projection partition pin
7007        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7008        // — extends the round-trip discipline onto the trait-idiomatic
7009        // *forward* axis, closing the two-way `Self ↔ &'static str`
7010        // round-trip on the trait-idiomatic pair
7011        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
7012        // well as the pre-existing method-named pair
7013        // (`as_str` + `from_wire`).
7014        for &variant in RestartStrategy::ALL {
7015            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7016            let via_method: &'static str = variant.as_str();
7017            assert_eq!(
7018                via_trait, via_method,
7019                "From<RestartStrategy> for &'static str and \
7020                 RestartStrategy::as_str must resolve identically on \
7021                 RestartStrategy::{variant:?} — divergence signals the \
7022                 two forward-projection paths have drifted onto different \
7023                 emit-sets"
7024            );
7025        }
7026        // Round-trip witness: every arm's forward `From` output re-parses
7027        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
7028        // to the original variant. Closes the two-way `RestartStrategy ↔
7029        // &'static str` round-trip on the trait-idiomatic axis pair,
7030        // mirroring the pre-existing method-named `as_str` + `from_wire`
7031        // round-trip on the substrate-primitive axis pair.
7032        for &variant in RestartStrategy::ALL {
7033            let emitted: &'static str = variant.into();
7034            let re_parsed: Result<RestartStrategy, ()> =
7035                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7036            assert_eq!(
7037                re_parsed,
7038                Ok(variant),
7039                "trait-idiomatic axis pair must round-trip \
7040                 RestartStrategy::{variant:?} through `.into::<&'static \
7041                 str>()` and back through `TryFrom<&str>` — a break signals \
7042                 the forward-emit and reverse-parse axes have drifted onto \
7043                 different vocabularies"
7044            );
7045        }
7046    }
7047
7048    #[test]
7049    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
7050        // Fail-before-pass-after byte-parity pin on the newly lifted
7051        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
7052        // library trait impl and the substrate-primitive
7053        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
7054        // the same three-arm accept-set across every arm the exhaustive
7055        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
7056        // detour that routes the trait impl through a divergent
7057        // projection (a per-arm inline `match s { "Permanent" =>
7058        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
7059        // link to the un-lifted arm-literal, a hypothetical
7060        // `#[serde(rename_all = "…")]` attribute drift that silently
7061        // splits the wire byte-string from every consumer that reaches
7062        // for this typed dispatch, an accidental swap onto the kebab-case
7063        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
7064        // impl parses through and which would collide the two-axis
7065        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
7066        // doc block makes load-bearing) trips at caixa-core test time
7067        // under `assert_eq!` rather than at a downstream
7068        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
7069        // every one of the three arms [`RestartPolicy::ALL`] carries so
7070        // no arm's projection is covered only by the sibling method-
7071        // named `from_wire` path. Peer of the sibling
7072        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
7073        // (5b828ed) — extends the trait-idiomatic reverse-projection
7074        // axis onto the third and final M2-OTP-shape closed-set typed
7075        // enum on the caixa surface (the paired per-child restart-
7076        // decision-policy sibling on the same M2 `:supervisor` slot).
7077        for &variant in RestartPolicy::ALL {
7078            let wire = variant.as_str();
7079            assert_eq!(
7080                <RestartPolicy as TryFrom<&str>>::try_from(wire),
7081                Ok(variant),
7082                "TryFrom<&str> impl on RestartPolicy must round-trip \
7083                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
7084                 Ok(RestartPolicy::{variant:?}) — divergence from \
7085                 RestartPolicy::from_wire signals a silent detour off \
7086                 the substrate-primitive accessor"
7087            );
7088            assert_eq!(
7089                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
7090                RestartPolicy::from_wire(wire),
7091                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
7092                 equal RestartPolicy::from_wire on the same input"
7093            );
7094        }
7095    }
7096
7097    #[test]
7098    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
7099        // Rejection witness on the `impl TryFrom<&str> for
7100        // RestartPolicy` — sweeps a candidate set of byte-strings
7101        // outside the three-arm PascalCase wire accept-set the sibling
7102        // [`RestartPolicy::as_str`] emits and asserts every one lands on
7103        // `Err(())`, so a future accidental widening of the trait impl's
7104        // accept-set (a stray additional
7105        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
7106        // path, a silent inclusion of the kebab-case dispatcher-catalog
7107        // byte-string the pre-existing [`std::str::FromStr`] impl the
7108        // [`gen_platform::FromStrKind`] derive installs parses onto the
7109        // wire axis — which would collide the two-axis
7110        // wire/dispatcher-catalog split the sibling
7111        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
7112        // an English-rebrand or plural-arm silent alias that would widen
7113        // the wire accept-set past the OTP-canonical three) trips at
7114        // caixa-core test time. The candidate set includes the empty
7115        // string, whitespace-only padding, the kebab-case dispatcher-
7116        // catalog byte-strings on the sibling axis (a caller who
7117        // confuses the two axes trips here rather than at a downstream
7118        // consumer's silent reject), a lowercase / uppercase / mixed-case
7119        // fold of each PascalCase arm (a caller who assumes case-fold
7120        // acceptance trips here), leading/trailing whitespace padding,
7121        // the trailing-newline shape, quote-wrapped candidates, and a
7122        // residual set of plausible-but-wrong English rebrand
7123        // candidates. Peer of the sibling
7124        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
7125        // (5b828ed) rejection witness.
7126        let rejected: &[&str] = &[
7127            "",
7128            " ",
7129            "\n",
7130            "\t",
7131            "permanent",
7132            "temporary",
7133            "transient",
7134            "PERMANENT",
7135            "TEMPORARY",
7136            "TRANSIENT",
7137            "Permanents",
7138            "Permanent ",
7139            " Permanent",
7140            " Temporary ",
7141            "Permanent\n",
7142            "Transient\t",
7143            "\"Permanent\"",
7144            "Ephemeral",
7145            "Always",
7146            "Never",
7147            "OnAbnormalExit",
7148            "intrinsic",
7149            "?",
7150        ];
7151        for &input in rejected {
7152            assert_eq!(
7153                <RestartPolicy as TryFrom<&str>>::try_from(input),
7154                Err(()),
7155                "TryFrom<&str> impl on RestartPolicy must reject the \
7156                 non-wire byte-string {input:?} — silent acceptance \
7157                 signals an accept-set widening off the paired \
7158                 RestartPolicy::from_wire resolver"
7159            );
7160        }
7161    }
7162
7163    #[test]
7164    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
7165        // Cross-axis partition pin: the paired `TryFrom<&str>` and
7166        // `from_wire` reverse projections must resolve identically on
7167        // *every* input, not just the ones [`RestartPolicy::ALL`]
7168        // enumerates. Sweeps a mixed candidate set spanning accepted
7169        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
7170        // case dispatcher-catalog byte-strings, empty, whitespace-
7171        // padded, quoted, English-rebrand candidates) inputs and asserts
7172        // the trait's `Result::ok()` projection byte-equals the method-
7173        // named resolver's `Option<Self>` return-shape on each, locking
7174        // the two paths together by construction so any future detour
7175        // (a stray `try_from` special-case that widens or narrows the
7176        // accept-set outside the paired `from_wire` resolver, an
7177        // accidental swap onto the kebab-case [`std::str::FromStr`]
7178        // impl the [`gen_platform::FromStrKind`] derive installs on the
7179        // sibling dispatcher-catalog axis) trips at caixa-core test
7180        // time. Peer of the sibling
7181        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7182        // pin — extends the round-trip discipline onto the M2-OTP-shape
7183        // per-child restart-policy axis.
7184        let candidates: &[&str] = &[
7185            "Permanent",
7186            "Temporary",
7187            "Transient",
7188            "",
7189            "permanent",
7190            "temporary",
7191            "transient",
7192            "PERMANENT",
7193            "unknown",
7194            "Permanent ",
7195            " Permanent",
7196            "\"Permanent\"",
7197            "Ephemeral",
7198            "OnAbnormalExit",
7199            "?",
7200        ];
7201        for &input in candidates {
7202            let via_trait: Option<RestartPolicy> =
7203                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
7204            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
7205            assert_eq!(
7206                via_trait, via_method,
7207                "TryFrom<&str> and from_wire must resolve identically on \
7208                 input {input:?} — divergence signals the two reverse-\
7209                 projection paths have drifted onto different accept-sets"
7210            );
7211        }
7212    }
7213
7214    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
7215
7216    #[test]
7217    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
7218        // The fail-before-pass-after pin: pre-lift there was no
7219        // single-source binding between the [`RestartPolicy`] variant
7220        // name the un-`rename`d `Serialize` derive emits under
7221        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
7222        // byte-string every downstream cluster-side dispatcher (the
7223        // future wasm-operator's per-child post-exit restart-decision
7224        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7225        // materializer's admission-time enum-arm bind, the
7226        // `caixa-operator`'s hierarchical reconciliation scheduler's
7227        // per-child-policy fan-out) probes verbatim. A future
7228        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
7229        // or a per-variant `#[serde(rename = "…")]` override, or a
7230        // variant rename in the source — would silently rebrand the
7231        // emitted scalar under one spelling while every downstream
7232        // dispatcher still probed the other, with the failure surfacing
7233        // at the operator's reconcile posture (children coming up under
7234        // the `default()` `Permanent` arm rather than the typed slot's
7235        // declared policy — a `:temporary` `oneShot` child would be
7236        // restarted on clean exit, treating the successful-completion
7237        // signal as failure and re-running the completion-terminal
7238        // one-shot indefinitely; a `:transient` child that clean-exited
7239        // would be restarted, masking the clean-completion contract)
7240        // far from the source rebrand commit and with no field naming
7241        // the drift. Pinning the two paths (the `Serialize` derive's
7242        // serialized string AND the [`RestartPolicy::as_str`] helper)
7243        // to the same three lifted
7244        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
7245        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
7246        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
7247        // byte-strings makes any future drift on either endpoint fail
7248        // here at caixa-core build time. Peer of the sibling
7249        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
7250        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
7251        // and the M3
7252        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7253        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
7254        // same three-path-convergence discipline, extended to close the
7255        // third OTP-shaped closed-enum discriminator axis on the caixa
7256        // typed surface (per-child restart-decision policy).
7257        for (variant, expected) in [
7258            (
7259                RestartPolicy::Permanent,
7260                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7261            ),
7262            (
7263                RestartPolicy::Temporary,
7264                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7265            ),
7266            (
7267                RestartPolicy::Transient,
7268                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7269            ),
7270        ] {
7271            let json = serde_json::to_string(&variant).unwrap();
7272            assert_eq!(
7273                json,
7274                format!("\"{expected}\""),
7275                "RestartPolicy::{variant:?} must serialize to {expected:?}"
7276            );
7277            assert_eq!(
7278                variant.as_str(),
7279                expected,
7280                "RestartPolicy::{variant:?}.as_str() must return the lifted \
7281                 SUPERVISOR_CHILD_RESTART_* constant"
7282            );
7283        }
7284    }
7285
7286    #[test]
7287    fn supervisor_child_restart_consts_are_pairwise_distinct() {
7288        // Cross-arm drift-detection pin: a future collapse of two
7289        // canonical variant byte-strings onto the same value (e.g. an
7290        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
7291        // to also read `"Permanent"`) would silently reroute every
7292        // downstream operator's per-child-policy dispatch onto the
7293        // sibling arm's reconcile branch and pass every propagation-probe
7294        // test that expected only the stale arm's value — a `:transient`
7295        // child would come up under the `:permanent` restart-decision
7296        // posture on every subsequent clean exit, so a completion-terminal
7297        // child would be restarted indefinitely against its declared
7298        // policy. Peer of the sibling
7299        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
7300        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
7301        // and the four-way distinct pin
7302        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
7303        // top-level `SUPERVISOR_KEY_*` axis.
7304        let all = [
7305            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7306            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7307            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7308        ];
7309        for (i, a) in all.iter().enumerate() {
7310            for (j, b) in all.iter().enumerate() {
7311                if i != j {
7312                    assert_ne!(
7313                        a, b,
7314                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
7315                         — got duplicate {a:?} at indices {i} and {j}",
7316                    );
7317                }
7318            }
7319        }
7320    }
7321
7322    #[test]
7323    fn restart_policy_display_routes_through_as_str_helper() {
7324        // The fail-before-pass-after pin on the first half of the
7325        // three-path convergence: pre-convergence [`RestartPolicy`]
7326        // carried a [`std::fmt::Display`] surface via its
7327        // `#[discriminant(also_display)]` gen-platform derive route,
7328        // which arrived kebab-case as `"permanent"` / `"temporary"`
7329        // / `"transient"` on this three-arm enum (whose variant
7330        // names each collapse to their own lowercase form under the
7331        // kebab-case transform) while the wire format ran as
7332        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
7333        // through the un-`rename`d serde derive. Every consumer
7334        // reaching for a policy byte-string past the wire format had
7335        // to pick between three paths ([`RestartPolicy::as_str`],
7336        // the `Serialize` derive's serialized string, or
7337        // `format!("{v}")` on the discriminant-Display route), any
7338        // two of which a future variant rename or
7339        // `#[serde(rename_all = "kebab-case")]` attribute would
7340        // silently desynchronize. Wiring [`std::fmt::Display`]
7341        // through [`RestartPolicy::as_str`] closes the third path:
7342        // every `format!("{v}")` call reaches the same lifted
7343        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
7344        // wire format and the [`RestartPolicy::as_str`] helper
7345        // already route through, so a future variant rename lands at
7346        // exactly one place. Pin the routing here so a future
7347        // `impl std::fmt::Display for RestartPolicy`
7348        // reimplementation that hand-rolls the arms instead of
7349        // delegating to [`RestartPolicy::as_str`] fails at
7350        // caixa-core build time. Peer of the sibling
7351        // [`restart_strategy_display_routes_through_as_str_helper`]
7352        // on the per-supervisor sibling-restart-strategy axis and
7353        // the M3
7354        // `placement_strategy_display_routes_through_as_str_helper`
7355        // (cc8f749) — the third of three OTP-shape closed-enum
7356        // discriminator axes on the caixa typed surface now
7357        // converged onto the same three-path
7358        // (Display → as_str → lifted const) discipline.
7359        for variant in [
7360            RestartPolicy::Permanent,
7361            RestartPolicy::Temporary,
7362            RestartPolicy::Transient,
7363        ] {
7364            assert_eq!(
7365                variant.to_string(),
7366                variant.as_str(),
7367                "RestartPolicy::{variant:?} Display must route through \
7368                 RestartPolicy::as_str (single source of truth: the lifted \
7369                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
7370            );
7371        }
7372    }
7373
7374    #[test]
7375    fn restart_policy_display_matches_serialized_wire_byte_string() {
7376        // The fail-before-pass-after pin on the second half of the
7377        // three-path convergence: `Display` (user-facing text) agrees
7378        // byte-for-byte with the `Serialize` derive's wire format
7379        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
7380        // scalar) on every variant. Pre-convergence the two paths
7381        // were structurally independent — a future
7382        // `#[serde(rename_all = "kebab-case")]` attribute on the
7383        // enum would silently rebrand the emitted wire scalar
7384        // (`permanent`, `temporary`, `transient`) while every
7385        // consumer that pretty-prints the policy (the future
7386        // wasm-operator's per-child post-exit restart-decision
7387        // diagnostic line, the future `feira app graph` per-child
7388        // restart column, the future M4
7389        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7390        // per-child admission-webhook rejection body) would still
7391        // emit the PascalCase form the `as_str` / `Display` route
7392        // returns, with the mismatch surfacing at consumer parse
7393        // time / operator dispatch time far from the source rebrand
7394        // commit. Pin the two paths byte-for-byte here so any future
7395        // serde-attribute or variant-rename drift is a
7396        // caixa-core-build-time test failure at this call, not a
7397        // silent per-consumer dispatch miss. Peer of the sibling
7398        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
7399        // on the per-supervisor sibling-restart-strategy axis and
7400        // the M3
7401        // `placement_strategy_display_matches_serialized_wire_byte_string`
7402        // (cc8f749).
7403        for variant in [
7404            RestartPolicy::Permanent,
7405            RestartPolicy::Temporary,
7406            RestartPolicy::Transient,
7407        ] {
7408            let wire = serde_json::to_string(&variant).unwrap();
7409            let unquoted = wire
7410                .strip_prefix('"')
7411                .and_then(|s| s.strip_suffix('"'))
7412                .expect("serialized RestartPolicy is a JSON string");
7413            assert_eq!(
7414                variant.to_string(),
7415                unquoted,
7416                "RestartPolicy::{variant:?} Display byte-string must match the \
7417                 Serialize derive's wire byte-string (three-path convergence: \
7418                 Display + as_str + Serialize all resolve to the same \
7419                 SUPERVISOR_CHILD_RESTART_* const)"
7420            );
7421        }
7422    }
7423
7424    #[test]
7425    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
7426        // Fail-before-pass-after byte-parity pin on the lifted
7427        // `impl AsRef<str> for RestartPolicy` — asserts the
7428        // standard-library trait impl and the substrate-primitive
7429        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
7430        // to the same `&str` per instance across the three-arm
7431        // closed set, so any future silent detour that routes the
7432        // impl through a divergent projection (a per-arm inline
7433        // `match self { RestartPolicy::Permanent => "Permanent", … }`
7434        // re-inlining that opens a compile-time link to the un-lifted
7435        // arm-literal, a swap onto the kebab-case
7436        // [`gen_platform::Discriminant`] catalog identity that would
7437        // collide the wire axis with the dispatcher-catalog axis) trips
7438        // at caixa-core test time under `PartialEq` rather than at a
7439        // downstream `impl AsRef<str>`-bound consumer's silent split.
7440        // Sweeps every one of the three arms
7441        // [`RestartPolicy::ALL`] carries so no arm's projection is
7442        // covered only by the sibling wire-format `Serialize` derive
7443        // path. Peer of the sibling
7444        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
7445        // (63eb1a4) on the paired per-supervisor sibling-restart-
7446        // strategy axis and the [`crate::CaixaVersion`]
7447        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
7448        // top-level `:versao` typed newtype — the three pins together
7449        // cover the substrate primitive's `AsRef<str>` projection axis
7450        // on the paired newtype + M2 closed-set-typed-enum surface.
7451        for &variant in RestartPolicy::ALL {
7452            assert_eq!(
7453                <RestartPolicy as AsRef<str>>::as_ref(&variant),
7454                variant.as_str(),
7455                "AsRef<str> impl on RestartPolicy::{variant:?} must \
7456                 byte-equal RestartPolicy::as_str on the same instance \
7457                 — divergence signals a silent detour off the substrate-\
7458                 primitive accessor"
7459            );
7460        }
7461    }
7462
7463    #[test]
7464    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
7465        // Fail-before-pass-after byte-parity pin on the three-path
7466        // convergence discipline the M2 per-child-restart-policy
7467        // primitive now carries on the `&str`-projection axis:
7468        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
7469        // lifted impl), `format!("{v}")` (the pre-existing
7470        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
7471        // primitive `pub const fn` accessor both trait impls delegate
7472        // through) must resolve to the same byte-string on every
7473        // instance across the three-arm closed set. Refuses any future
7474        // divergence between the two trait impls (a stray
7475        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7476        // rather than delegating through the shared accessor; a
7477        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7478        // literal cascade) that would silently split the two
7479        // projection paths of the same closed-set typed enum. Mirrors
7480        // the sibling three-path-convergence discipline the peer
7481        // [`RestartStrategy`] typed enum carries on its
7482        // `AsRef<str>` / `Display` / `as_str` triple
7483        // (supervisor.rs pin
7484        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
7485        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
7486        // carries on the same triple (version.rs pin
7487        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7488        // 16d5c7e).
7489        for &variant in RestartPolicy::ALL {
7490            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
7491            let via_display: String = format!("{variant}");
7492            let via_accessor: &str = variant.as_str();
7493            assert_eq!(via_as_ref, via_accessor);
7494            assert_eq!(via_display, via_accessor);
7495            assert_eq!(via_as_ref, via_display.as_str());
7496        }
7497    }
7498
7499    #[test]
7500    fn restart_policy_all_enumerates_every_variant_exactly_once() {
7501        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
7502        // exhaustive-iteration surface: every variant appears exactly
7503        // once, and the slice length matches the arm count of the
7504        // closed set. Every consumer that walks the accepted-policy
7505        // set (a future `feira supervisor --restart …` CLI-side
7506        // arg-parse's "did you mean" hint, a future M4 admission-
7507        // webhook's per-child rejection body naming the accepted-
7508        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
7509        // projection consumers that iterate the accept-set for
7510        // diagnostic rendering) reads through this slice, so a future
7511        // arm addition that grows the enum but forgets to grow
7512        // [`Self::ALL`] silently truncates every downstream consumer's
7513        // accept-set at the same pre-addition boundary — this pin
7514        // fails at caixa-core build time on the pairwise-distinct +
7515        // arm-count invariants.
7516        //
7517        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
7518        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
7519        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7520        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7521        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7522        // pins on the peer closed-set typed-enum axes.
7523        let all: &[RestartPolicy] = RestartPolicy::ALL;
7524        assert_eq!(
7525            all.len(),
7526            3,
7527            "RestartPolicy::ALL must enumerate every variant of the \
7528             three-arm closed set (Permanent, Temporary, Transient); \
7529             got {all:?}"
7530        );
7531        for (i, a) in all.iter().enumerate() {
7532            for (j, b) in all.iter().enumerate() {
7533                if i != j {
7534                    assert_ne!(
7535                        a, b,
7536                        "RestartPolicy::ALL must carry every variant exactly \
7537                         once — got duplicate {a:?} at indices {i} and {j}"
7538                    );
7539                }
7540            }
7541        }
7542        for variant in [
7543            RestartPolicy::Permanent,
7544            RestartPolicy::Temporary,
7545            RestartPolicy::Transient,
7546        ] {
7547            assert!(
7548                all.contains(&variant),
7549                "RestartPolicy::ALL must contain {variant:?} — a future arm \
7550                 addition that grows the enum but forgets to grow the ALL slice \
7551                 silently truncates every downstream consumer's accept-set at \
7552                 the pre-addition boundary"
7553            );
7554        }
7555    }
7556
7557    #[test]
7558    fn restart_policy_from_wire_accepts_every_lifted_constant() {
7559        // Fail-before-pass-after pin on the forward accept-set of the
7560        // [`RestartPolicy::from_wire`] reverse projection: every
7561        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
7562        // constant the [`RestartPolicy::as_str`] emitter walks parses
7563        // back to its paired variant. Any future arm addition that
7564        // grows the emitter's `as_str` match but forgets to grow the
7565        // parser's `from_wire` match silently splits the two halves of
7566        // the round-trip — the wire byte-string one non-serde consumer
7567        // parses from the one the emitter wrote — with the failure
7568        // surfacing at the operator's reconcile posture (a `:temporary`
7569        // `oneShot` child restarted on clean exit, a `:transient` child
7570        // restarted after clean completion) far from the rebrand
7571        // commit. Pinning the three-arm accept-set here catches the
7572        // drift at caixa-core build time.
7573        //
7574        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
7575        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
7576        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
7577        // accept-set pins on the peer closed-set typed-enum `str → Self`
7578        // axes.
7579        for (wire, expected) in [
7580            (
7581                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7582                RestartPolicy::Permanent,
7583            ),
7584            (
7585                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7586                RestartPolicy::Temporary,
7587            ),
7588            (
7589                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7590                RestartPolicy::Transient,
7591            ),
7592        ] {
7593            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
7594                panic!(
7595                    "RestartPolicy::from_wire({wire:?}) must accept every \
7596                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
7597                     lifted canonical byte-string that RestartPolicy::{expected:?} \
7598                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
7599                )
7600            });
7601            assert_eq!(
7602                parsed, expected,
7603                "RestartPolicy::from_wire({wire:?}) must return \
7604                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
7605            );
7606        }
7607    }
7608
7609    #[test]
7610    fn restart_policy_from_wire_round_trips_through_as_str() {
7611        // Fail-before-pass-after pin on the closed round-trip between
7612        // the forward [`RestartPolicy::as_str`] emitter and the
7613        // reverse [`RestartPolicy::from_wire`] parser: for every
7614        // variant in [`RestartPolicy::ALL`], parsing the emitter's
7615        // output must return exactly the same variant. Any per-arm
7616        // divergence — a future arm added to `as_str` but not
7617        // `from_wire`, an accidental copy-paste flip in one but not
7618        // the other — silently splits the emit and parse halves and
7619        // the failure surfaces at consumer parse time far from the
7620        // drift site. The `ALL`-iterating shape means a future arm
7621        // addition picks up the coverage by construction.
7622        //
7623        // Peer of the sibling
7624        // [`restart_strategy_from_wire_round_trips_through_as_str`]
7625        // (4eec29c) round-trip pin on
7626        // [`RestartStrategy::from_wire`] and the M3
7627        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
7628        // (18c7342) round-trip pin on
7629        // [`crate::aplicacao::PlacementStrategy::from_wire`].
7630        for &variant in RestartPolicy::ALL {
7631            let wire = variant.as_str();
7632            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
7633                panic!(
7634                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
7635                     must be Some({variant:?}) — the two halves of the round-trip \
7636                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
7637                     got None on wire byte-string {wire:?}"
7638                )
7639            });
7640            assert_eq!(
7641                parsed, variant,
7642                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
7643                 must round-trip to the same variant; got {parsed:?}"
7644            );
7645        }
7646    }
7647
7648    #[test]
7649    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
7650        // Fail-before-pass-after pin on the closed-set refusal
7651        // discipline of [`RestartPolicy::from_wire`]: every
7652        // byte-string outside the three-arm accept-set returns `None`
7653        // rather than silently collapsing onto the [`Default`]
7654        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
7655        // exercised here sweeps the load-bearing drift shapes: the
7656        // empty string (a stripped serde-attribute drift), all-
7657        // whitespace strings (the canonical text-editor accidental
7658        // padding shape), the kebab-case dispatcher-catalog identities
7659        // (`"permanent"` / `"temporary"` / `"transient"` — the
7660        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
7661        // accept-set, which parses the *other* axis of this enum's
7662        // two-axis split and must not leak into the `from_wire`
7663        // PascalCase-wire accept-set — a lowercase leak here would
7664        // silently accept the operator's kebab-case
7665        // dispatcher-catalog probe under the wire-axis parser and mis-
7666        // route a `:permanent` intent), the padded canonical scalar
7667        // (`" Permanent "`), the trailing-newline shapes
7668        // (`"Permanent\n"`), the uppercase-single-word forms
7669        // (`"PERMANENT"`), and neighboring-but-unknown arms
7670        // (`"Restart"` — the canonical typo direction toward the
7671        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
7672        //
7673        // Peer of the sibling
7674        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
7675        // (4eec29c) +
7676        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
7677        // (2aa6d23) +
7678        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
7679        // (18c7342) refusal pins on the peer closed-set typed-enum
7680        // axes.
7681        for bad in [
7682            "",
7683            " ",
7684            "\n",
7685            "\t",
7686            "permanent",
7687            "temporary",
7688            "transient",
7689            "PERMANENT",
7690            "TEMPORARY",
7691            "TRANSIENT",
7692            "Permanents",
7693            "Permanent ",
7694            " Permanent",
7695            " Transient ",
7696            "Permanent\n",
7697            "perma",
7698            "Trans",
7699            "OneForOne",
7700            "Restart",
7701            "?",
7702        ] {
7703            assert!(
7704                RestartPolicy::from_wire(bad).is_none(),
7705                "RestartPolicy::from_wire({bad:?}) must return None — the \
7706                 parser's accept-set is exactly the three RestartPolicy::as_str \
7707                 outputs (Permanent, Temporary, Transient), and this \
7708                 byte-string is outside that closed set"
7709            );
7710        }
7711    }
7712
7713    #[test]
7714    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
7715        // Fail-before-pass-after pin on the fourth path of the four-path
7716        // convergence: `from_wire` (the reverse projection) inverts the
7717        // `Serialize` derive's wire byte-string on every variant.
7718        // Together with the pre-existing three-path convergence
7719        // (`Display` + `as_str` + `Serialize` all resolve to the same
7720        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
7721        // pinned by
7722        // [`restart_policy_display_matches_serialized_wire_byte_string`])
7723        // this closes the round-trip: the wire byte-string the
7724        // `Serialize` derive emits parses back to the same variant
7725        // through `from_wire`, so any future serde-attribute or variant-
7726        // rename drift on the emit half now surfaces as a matched drift
7727        // on the parse half at caixa-core build time — the two halves
7728        // migrate as a unit through the lifted consts on any future
7729        // rename, and the round-trip cannot silently split.
7730        //
7731        // Peer of the sibling
7732        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7733        // (4eec29c) wire-format pin on
7734        // [`RestartStrategy::from_wire`] and the M3
7735        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7736        // (18c7342) wire-format pin on
7737        // [`crate::aplicacao::PlacementStrategy::from_wire`].
7738        for &variant in RestartPolicy::ALL {
7739            let wire = serde_json::to_string(&variant).unwrap();
7740            let unquoted = wire
7741                .strip_prefix('"')
7742                .and_then(|s| s.strip_suffix('"'))
7743                .expect("serialized RestartPolicy is a JSON string");
7744            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
7745                panic!(
7746                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
7747                     Serialize derive's wire byte-string for \
7748                     RestartPolicy::{variant:?} — the four-path convergence \
7749                     (Display + as_str + Serialize + from_wire) resolves through \
7750                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
7751                )
7752            });
7753            assert_eq!(
7754                parsed, variant,
7755                "RestartPolicy::from_wire of the Serialize derive's wire \
7756                 byte-string for RestartPolicy::{variant:?} must round-trip \
7757                 to the same variant; got {parsed:?}"
7758            );
7759        }
7760    }
7761
7762    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
7763    //
7764    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
7765    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
7766    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
7767    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
7768    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
7769    // the peer per-`:upgrade-from :from` axis. The three pins jointly
7770    // brace the accessor against every future silent detour that would
7771    // desynchronize it from the raw `.caixa` field access every consumer
7772    // previously open-coded.
7773
7774    #[test]
7775    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
7776        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
7777        // [`ChildSpec::nome`] must return the `:children :caixa` field
7778        // byte-for-byte across every DNS-1123-label value the upstream
7779        // [`crate::render::require_valid_dns_1123_label`] gate at
7780        // `SupervisorSpec::validate` admits. Peer of the sibling
7781        // `membro_nome_returns_caixa_byte_equal_across_permutations`
7782        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
7783        // substrate-primitive accessor must byte-equal the raw field
7784        // access verbatim across every author-declared value" discipline
7785        // extended to the M2 supervisor-tree per-`:children` arm. Pins
7786        // against a future silent detour that re-normalized the child
7787        // identity (an accidental `.to_lowercase()` — every `:children
7788        // :caixa` is validated as a DNS-1123 label upstream, so any
7789        // re-normalization is redundant + a drift surface between the
7790        // validator and the accessor), a namespace-prefix rewrite (an
7791        // accidental `format!("{namespace}/{caixa}")` per-CR
7792        // fully-qualified rewrite that didn't land on the peer axes), or
7793        // a per-cluster alias stamp the future wasm-operator's
7794        // hierarchical reconciliation scheduler authors on one consumer
7795        // without the others. Five values sweep the accept-set the
7796        // DNS-1123 gate upstream admits (short single-word / dashed /
7797        // v-suffixed / mixed-digit child names).
7798        for name in [
7799            "worker",
7800            "cache-server",
7801            "scratch-job",
7802            "orders-v2",
7803            "session-8080",
7804        ] {
7805            let c = ChildSpec {
7806                caixa: name.into(),
7807                versao: "^0.1".into(),
7808                restart: RestartPolicy::Permanent,
7809            };
7810            assert_eq!(
7811                c.nome(),
7812                name,
7813                "ChildSpec::nome must return :children :caixa verbatim \
7814                 (got {:?}, expected {name:?})",
7815                c.nome(),
7816            );
7817            assert_eq!(
7818                c.nome(),
7819                c.caixa.as_str(),
7820                "ChildSpec::nome must byte-equal the .caixa field access",
7821            );
7822        }
7823    }
7824
7825    #[test]
7826    fn child_spec_nome_borrows_from_caixa_storage() {
7827        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
7828        // `&str` slice that borrows from the typed slot's own [`String`]
7829        // storage — same-address invariant with `c.caixa.as_str()`. Pins
7830        // against a future silent detour that allocated a fresh `String`
7831        // (`self.caixa.clone()` in the body would type-check but silently
7832        // drop the borrow, and every downstream consumer that assumed
7833        // the returned slice outlives `&self` would break on a stale-
7834        // reference use-after-free — the [`crate::render::insert_first_seen`]
7835        // dedup key at [`SupervisorSpec::validate`], the
7836        // [`validate_no_self_supervision`] equality check against the
7837        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
7838        // borrow — each would silently misbehave if this accessor
7839        // produced a detached copy). Peer of the sibling
7840        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
7841        // M3 per-`:membros` axis and the
7842        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
7843        // first M2 slot scalar accessor.
7844        let c = ChildSpec {
7845            caixa: "worker".into(),
7846            versao: "^0.1".into(),
7847            restart: RestartPolicy::Permanent,
7848        };
7849        let name = c.nome();
7850        let caixa_slice = c.caixa.as_str();
7851        assert_eq!(
7852            name.as_ptr(),
7853            caixa_slice.as_ptr(),
7854            "ChildSpec::nome must borrow from the .caixa String's backing \
7855             storage — a fresh allocation here means the accessor no \
7856             longer names the substrate-primitive typed dispatch and \
7857             every downstream consumer would silently carry a detached \
7858             copy",
7859        );
7860        assert_eq!(
7861            name.len(),
7862            caixa_slice.len(),
7863            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
7864             as well as in address",
7865        );
7866    }
7867
7868    #[test]
7869    fn validate_gates_child_nome_through_lifted_accessor() {
7870        // Bilateral coherence pin: every `:children :caixa` that
7871        // [`SupervisorSpec::validate`] accepts is one
7872        // [`crate::render::require_valid_dns_1123_label`] accepts on the
7873        // accessor-projected value, and vice versa on the reject side.
7874        // This closes the "the validator reads through the accessor"
7875        // contract structurally — a future silent detour that made the
7876        // accessor return a different byte-string than the validator
7877        // gates against would surface here as a coverage mismatch, not
7878        // as an apply-time DNS-1123 rejection at
7879        // `metadata.name: Invalid value` far from the caixa.lisp source.
7880        // Peer of the M2 sibling
7881        // `validate_parses_prior_versao_through_lifted_accessor`
7882        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
7883        // `validate_membros` peer discipline.
7884        //
7885        // Accept-set sweep: five DNS-1123-label values the upstream gate
7886        // admits.
7887        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
7888            let s = SupervisorSpec {
7889                children: vec![ChildSpec {
7890                    caixa: ok_name.into(),
7891                    versao: "^0.1".into(),
7892                    restart: RestartPolicy::Permanent,
7893                }],
7894                ..SupervisorSpec::default()
7895            };
7896            s.validate().unwrap_or_else(|e| {
7897                panic!(
7898                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
7899                     (upstream DNS-1123 gate accepts it): got {e:?}",
7900                );
7901            });
7902            let c = ChildSpec {
7903                caixa: ok_name.into(),
7904                versao: "^0.1".into(),
7905                restart: RestartPolicy::Permanent,
7906            };
7907            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
7908                .unwrap_or_else(|()| {
7909                    panic!(
7910                        "require_valid_dns_1123_label must accept the accessor-projected \
7911                     :children :caixa {ok_name:?}",
7912                    );
7913                });
7914        }
7915        // Reject-set sweep: five DNS-1123-label-violating shapes the
7916        // upstream gate refuses (empty / uppercase / underscore / dot /
7917        // leading-hyphen). Every rejection at the validator must
7918        // correspond to a rejection when the accessor's projected value
7919        // is fed back through the shared gate.
7920        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
7921            let s = SupervisorSpec {
7922                children: vec![ChildSpec {
7923                    caixa: bad_name.into(),
7924                    versao: "^0.1".into(),
7925                    restart: RestartPolicy::Permanent,
7926                }],
7927                ..SupervisorSpec::default()
7928            };
7929            let err = s.validate().unwrap_err();
7930            assert!(
7931                matches!(
7932                    err,
7933                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
7934                ),
7935                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
7936                 via the DNS-1123 gate: got {err:?}",
7937            );
7938            let c = ChildSpec {
7939                caixa: bad_name.into(),
7940                versao: "^0.1".into(),
7941                restart: RestartPolicy::Permanent,
7942            };
7943            assert!(
7944                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
7945                    .is_err(),
7946                "require_valid_dns_1123_label must reject the accessor-projected \
7947                 :children :caixa {bad_name:?}",
7948            );
7949        }
7950    }
7951
7952    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
7953    //
7954    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
7955    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
7956    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
7957    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
7958    // trio on the peer per-`:children` `String`-carry axis. The three pins
7959    // jointly brace the accessor against every future silent detour that
7960    // would desynchronize it from the raw `.versao` field access the
7961    // requirement gate + error carrier previously open-coded.
7962    //
7963    // Closes the last unlifted per-`:children` `String`-carry axis: the
7964    // pair (`nome`, `versao_requirement`) now jointly projects the
7965    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
7966    // consumer that fans on per-child identity + version pin reads,
7967    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
7968    // pair discipline verbatim.
7969    #[test]
7970    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
7971        // The canonical per-`:children` child-`:versao`-scalar pin:
7972        // [`ChildSpec::versao_requirement`] must return the `:children
7973        // :versao` field byte-for-byte across every Cargo-shaped semver
7974        // requirement value the upstream
7975        // [`crate::render::require_valid_versao_requirement`] gate admits.
7976        // Peer of the sibling
7977        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
7978        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
7979        // substrate-primitive accessor must byte-equal the raw field
7980        // access verbatim across every author-declared value" discipline
7981        // extended to the M2 supervisor-tree per-`:children` arm. Pins
7982        // against a future silent detour that re-canonicalized the
7983        // requirement (an accidental `.to_string()` via
7984        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
7985        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
7986        // silently drifted the error carrier's quoted requirement away
7987        // from the source `caixa.lisp`, an accidental whitespace trim on
7988        // `"^ 0.1"` that no consumer ever produced from the field-access
7989        // side, an accidental per-cluster lacre-projected concrete-version
7990        // rewrite that didn't land on the peer requirement-gate call).
7991        // Five values sweep the accept-set the shared
7992        // [`crate::render::require_valid_versao_requirement`] gate admits
7993        // (caret / tilde / exact / wildcard / bare-major).
7994        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
7995            let c = ChildSpec {
7996                caixa: "worker".into(),
7997                versao: req.into(),
7998                restart: RestartPolicy::Permanent,
7999            };
8000            assert_eq!(
8001                c.versao_requirement(),
8002                req,
8003                "ChildSpec::versao_requirement must return :children :versao \
8004                 verbatim (got {:?}, expected {req:?})",
8005                c.versao_requirement(),
8006            );
8007            assert_eq!(
8008                c.versao_requirement(),
8009                c.versao.as_str(),
8010                "ChildSpec::versao_requirement must byte-equal the .versao \
8011                 field access",
8012            );
8013        }
8014    }
8015
8016    #[test]
8017    fn child_spec_versao_requirement_borrows_from_versao_storage() {
8018        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
8019        // return a `&str` slice that borrows from the typed slot's own
8020        // [`String`] storage — same-address invariant with
8021        // `c.versao.as_str()`. Pins against a future silent detour that
8022        // allocated a fresh `String` (`self.versao.clone()` in the body
8023        // would type-check but silently drop the borrow, and every
8024        // downstream consumer that assumed the returned slice outlives
8025        // `&self` — the [`crate::render::require_valid_versao_requirement`]
8026        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
8027        // `.to_string()` carrier's byte-length assumption — would silently
8028        // misbehave if this accessor produced a detached copy). Peer of
8029        // the sibling `child_spec_nome_borrows_from_caixa_storage`
8030        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
8031        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
8032        // pin on the peer per-`:membros` `:versao` axis.
8033        let c = ChildSpec {
8034            caixa: "worker".into(),
8035            versao: "^0.1".into(),
8036            restart: RestartPolicy::Permanent,
8037        };
8038        let req = c.versao_requirement();
8039        let versao_slice = c.versao.as_str();
8040        assert_eq!(
8041            req.as_ptr(),
8042            versao_slice.as_ptr(),
8043            "ChildSpec::versao_requirement must borrow from the .versao \
8044             String's backing storage — a fresh allocation here means the \
8045             accessor no longer names the substrate-primitive typed \
8046             dispatch and every downstream consumer would silently carry \
8047             a detached copy",
8048        );
8049        assert_eq!(
8050            req.len(),
8051            versao_slice.len(),
8052            "ChildSpec::versao_requirement and .versao.as_str() must \
8053             byte-equal in length as well as in address",
8054        );
8055    }
8056
8057    #[test]
8058    fn validate_gates_child_versao_through_lifted_accessor() {
8059        // Bilateral coherence pin: every `:children :versao` that
8060        // [`SupervisorSpec::validate`] accepts is one
8061        // [`crate::render::require_valid_versao_requirement`] accepts on
8062        // the accessor-projected value, and vice versa on the reject side.
8063        // This closes the "the validator reads through the accessor"
8064        // contract structurally — a future silent detour that made the
8065        // accessor return a different byte-string than the validator gates
8066        // against would surface here as a coverage mismatch, not as a
8067        // resolver-time semver-parse rejection at lacre-closure time far
8068        // from the caixa.lisp source. Peer of the sibling
8069        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
8070        // the per-`:children :caixa` axis and the M2
8071        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
8072        // on the peer per-`:upgrade-from :from` axis.
8073        //
8074        // Accept-set sweep: five Cargo-shaped semver requirement values
8075        // the upstream gate admits (caret / tilde / exact / wildcard /
8076        // bare-major).
8077        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
8078            let s = SupervisorSpec {
8079                children: vec![ChildSpec {
8080                    caixa: "worker".into(),
8081                    versao: ok_req.into(),
8082                    restart: RestartPolicy::Permanent,
8083                }],
8084                ..SupervisorSpec::default()
8085            };
8086            s.validate().unwrap_or_else(|e| {
8087                panic!(
8088                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
8089                     (upstream versao-requirement gate accepts it): got {e:?}",
8090                );
8091            });
8092            let c = ChildSpec {
8093                caixa: "worker".into(),
8094                versao: ok_req.into(),
8095                restart: RestartPolicy::Permanent,
8096            };
8097            crate::render::require_valid_versao_requirement(
8098                c.versao_requirement(),
8099                || (),
8100                |_reason| (),
8101            )
8102            .unwrap_or_else(|()| {
8103                panic!(
8104                    "require_valid_versao_requirement must accept the accessor-projected \
8105                     :children :versao {ok_req:?}",
8106                );
8107            });
8108        }
8109        // Reject-set sweep: five requirement-violating shapes the upstream
8110        // gate refuses. The empty string closes the empty-first arm of the
8111        // shared [`crate::render::require_valid_versao_requirement`]
8112        // cascade; the four non-empty arms exercise distinct semver-parse
8113        // failure modes the M3 peer per-`:membros` reject-set already pins
8114        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
8115        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
8116        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
8117        // shared parser routing means the same reject-set must fail
8118        // identically at the M2 supervisor-tree per-`:children` accessor
8119        // arm here. Every rejection at the validator must correspond to a
8120        // rejection when the accessor's projected value is fed back
8121        // through the shared gate.
8122        //
8123        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
8124        // `"not-a-semver"` are intentionally *not* in the reject-set: the
8125        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
8126        // and the identifier-tail arm's grammar admits some non-canonical
8127        // shapes — matching what the M3 peer test suite already documents
8128        // as the shared parser's accept-set edges.)
8129        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
8130            let s = SupervisorSpec {
8131                children: vec![ChildSpec {
8132                    caixa: "worker".into(),
8133                    versao: bad_req.into(),
8134                    restart: RestartPolicy::Permanent,
8135                }],
8136                ..SupervisorSpec::default()
8137            };
8138            let err = s.validate().unwrap_err();
8139            assert!(
8140                matches!(
8141                    err,
8142                    SupervisorError::EmptyChildVersion { .. }
8143                        | SupervisorError::ChildVersaoInvalid { .. }
8144                ),
8145                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
8146                 via the versao-requirement gate: got {err:?}",
8147            );
8148            let c = ChildSpec {
8149                caixa: "worker".into(),
8150                versao: bad_req.into(),
8151                restart: RestartPolicy::Permanent,
8152            };
8153            assert!(
8154                crate::render::require_valid_versao_requirement(
8155                    c.versao_requirement(),
8156                    || (),
8157                    |_reason| (),
8158                )
8159                .is_err(),
8160                "require_valid_versao_requirement must reject the accessor-projected \
8161                 :children :versao {bad_req:?}",
8162            );
8163        }
8164    }
8165
8166    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
8167    //
8168    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
8169    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
8170    // already project the `String`-carry `(caixa, versao)` fields; the
8171    // `Copy`-composite-enum `restart` field is the third and final axis).
8172    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
8173    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
8174    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
8175    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
8176    // strategy scalar accessor — same "one typed dispatch on the substrate
8177    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
8178    // extended onto the M2 supervisor-slot per-`:children` restart-decision
8179    // axis. The pin below covers the accessor's byte-equal projection
8180    // against the raw field access across every variant in the closed
8181    // accept-set (`Permanent`, `Transient`, `Temporary`).
8182
8183    #[test]
8184    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
8185        // The canonical per-`:children` restart-decision-policy-scalar
8186        // pin: [`ChildSpec::restart`] must return the `:children :restart`
8187        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
8188        // typed slot's own [`RestartPolicy`] storage across every variant
8189        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
8190        // Pins against a future silent detour that re-derived the policy
8191        // from a peer axis (an accidental fallback to
8192        // `if is_supervisor_child { Permanent } else { Temporary }` that
8193        // collapsed the child's kind axis into the restart discriminator),
8194        // a variant remap the operator authors on one consumer without the
8195        // other, or a stale-derive detour that substituted
8196        // [`RestartPolicy::default`] when the field held any explicit
8197        // variant (which would silently collapse the distinction between
8198        // "author explicitly declared `:restart Permanent`" and "author
8199        // omitted the slot and inherited the default" the future
8200        // per-cluster restart-decision override slot depends on).
8201        //
8202        // Peer of the sibling per-`:supervisor`
8203        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
8204        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
8205        // axis and the M3
8206        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
8207        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
8208        // — same "the substrate-primitive accessor must byte-equal the raw
8209        // field access verbatim across every author-declared value"
8210        // discipline extended onto the M2 supervisor-slot per-`:children`
8211        // restart-decision-policy axis, closing the last unlifted axis on
8212        // the per-`:children` [`ChildSpec`] type.
8213        for restart in [
8214            RestartPolicy::Permanent,
8215            RestartPolicy::Transient,
8216            RestartPolicy::Temporary,
8217        ] {
8218            let c = ChildSpec {
8219                caixa: "worker".into(),
8220                versao: "^0.1".into(),
8221                restart,
8222            };
8223            assert_eq!(
8224                c.restart(),
8225                restart,
8226                "ChildSpec::restart must return :children :restart \
8227                 verbatim (got {:?}, expected {restart:?})",
8228                c.restart(),
8229            );
8230            assert_eq!(
8231                c.restart(),
8232                c.restart,
8233                "ChildSpec::restart accessor and .restart field access \
8234                 must byte-equal — the accessor is the substrate-primitive \
8235                 typed dispatch every downstream per-child restart-\
8236                 decision consumer must route through",
8237            );
8238        }
8239    }
8240
8241    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
8242    //
8243    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
8244    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
8245    // distribution-strategy accessor discipline onto the M2 supervisor-slot
8246    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
8247    // scalar axis. The two pins below cover (1) the accessor's byte-equal
8248    // projection against the raw field access across every variant in the
8249    // closed accept-set, and (2) the two-consumer coherence between the
8250    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
8251    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
8252    // carrier's `estrategia:` field — peer of the sibling M3
8253    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
8254    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
8255    // pair on the per-`:placement` distribution-strategy axis.
8256
8257    #[test]
8258    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
8259        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
8260        // pin: [`SupervisorSpec::estrategia`] must return the
8261        // `:supervisor :estrategia` field verbatim as a
8262        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
8263        // [`RestartStrategy`] storage across every variant in the closed
8264        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
8265        // `SimpleOneForOne`). Pins against a future silent detour that
8266        // re-derived the strategy from a peer axis (an accidental
8267        // fallback to `if children.is_empty() { SimpleOneForOne } else {
8268        // OneForOne }` collapse that read the children-count axis into
8269        // the strategy discriminator), a variant remap the operator
8270        // authors on one consumer without the other, or a stale-derive
8271        // detour that substituted [`RestartStrategy::default`] when the
8272        // field held any explicit variant (which would silently collapse
8273        // the distinction between "author explicitly declared
8274        // `:estrategia OneForOne`" and "author omitted the slot and
8275        // inherited the default" the future per-cluster strategy override
8276        // slot depends on). Peer of the sibling M3
8277        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
8278        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
8279        // axis — same "the substrate-primitive accessor must byte-equal
8280        // the raw field access verbatim across every author-declared
8281        // value" discipline extended onto the M2 supervisor-slot
8282        // per-`:supervisor` sibling-restart-strategy axis.
8283        for &estrategia in RestartStrategy::ALL {
8284            // `SimpleOneForOne` requires `children.is_empty()`; the peer
8285            // three strategies require a non-empty static children list.
8286            // Build each shape coherently so the pin's fixture would
8287            // itself pass [`SupervisorSpec::validate`] once fed through
8288            // the sibling coherence pin below — the byte-equal projection
8289            // asserted here is a strictly weaker property (a `Copy` field
8290            // read) that does not depend on `validate` running, but
8291            // keeping the fixture validate-clean means a future extension
8292            // of the pin to exercise `validate` end-to-end does not have
8293            // to re-author the children shape.
8294            //
8295            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
8296            // shape partition through the [`gen_platform::IsVariant`]
8297            // derive-generated
8298            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
8299            // than the raw `matches!(estrategia, RestartStrategy::
8300            // SimpleOneForOne)` open-coded pattern-match — same closed-
8301            // set-typed-enum arm-discriminator dispatch discipline the
8302            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
8303            // convergence (915a934) extended onto its two paired positive
8304            // / negated `matches!` sites and the peer
8305            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
8306            // predicate convergence (766ec63) extended onto the M3 mesh-
8307            // slot per-`:placement` distribution-strategy discriminator
8308            // axis. See the sibling `round_trip_all_strategies` and the
8309            // peer `manifest::tests::
8310            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
8311            // fixture for the two peer sites the same lift closes on.
8312            let children = if estrategia.is_simple_one_for_one() {
8313                Vec::new()
8314            } else {
8315                vec![ChildSpec {
8316                    caixa: "worker".into(),
8317                    versao: "^0.1".into(),
8318                    restart: RestartPolicy::Permanent,
8319                }]
8320            };
8321            let s = SupervisorSpec {
8322                estrategia,
8323                children,
8324                ..SupervisorSpec::default()
8325            };
8326            assert_eq!(
8327                s.estrategia(),
8328                estrategia,
8329                "SupervisorSpec::estrategia must return :supervisor :estrategia \
8330                 verbatim (got {:?}, expected {estrategia:?})",
8331                s.estrategia(),
8332            );
8333            assert_eq!(
8334                s.estrategia(),
8335                s.estrategia,
8336                "SupervisorSpec::estrategia accessor and .estrategia field \
8337                 access must byte-equal — the accessor is the substrate-\
8338                 primitive typed dispatch every downstream sibling-restart-\
8339                 strategy consumer must route through",
8340            );
8341        }
8342    }
8343
8344    #[test]
8345    fn validate_reads_through_lifted_estrategia_accessor() {
8346        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
8347        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
8348        // dispatch (which reads through [`SupervisorSpec::estrategia`]
8349        // to fan across the strategy-arm shape-gate cascades) and the
8350        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
8351        // error carrier's `estrategia:` field (which reads through
8352        // [`SupervisorSpec::estrategia`] to name the strategy the empty
8353        // `:children` list was declared against) must both key off the
8354        // lifted accessor, so any future rebrand on the typed slot's
8355        // reader shape lands at exactly one place. Pins the two-site
8356        // coherence by exercising the `NoChildren` error surface end-to-
8357        // end across every non-`SimpleOneForOne` variant and asserting
8358        // the surfaced `estrategia:` field byte-equals the accessor's
8359        // return. Peer of the sibling M3
8360        // `validate_placement_reads_through_lifted_estrategia_accessor`
8361        // (921fe1b) three-consumer coherence pin on the per-`:placement`
8362        // distribution-strategy axis.
8363        for estrategia in [
8364            RestartStrategy::OneForOne,
8365            RestartStrategy::OneForAll,
8366            RestartStrategy::RestForOne,
8367        ] {
8368            let s = SupervisorSpec {
8369                estrategia,
8370                children: Vec::new(),
8371                ..SupervisorSpec::default()
8372            };
8373            let err = s.validate().unwrap_err();
8374            match err {
8375                SupervisorError::NoChildren { estrategia: e } => {
8376                    assert_eq!(
8377                        e,
8378                        s.estrategia(),
8379                        "NoChildren.estrategia must byte-equal \
8380                         SupervisorSpec::estrategia() — the empty-`:children` \
8381                         refusal reads through the lifted accessor",
8382                    );
8383                    assert_eq!(
8384                        e, estrategia,
8385                        "NoChildren.estrategia must carry the author-declared \
8386                         :supervisor :estrategia variant verbatim (got {e:?}, \
8387                         expected {estrategia:?})",
8388                    );
8389                }
8390                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
8391            }
8392        }
8393    }
8394
8395    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
8396    //
8397    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
8398    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
8399    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
8400    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
8401    // The two pins below cover (1) the accessor's byte-equal projection
8402    // against the raw field access across every representative value in
8403    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
8404    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
8405    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
8406    // zero-floor / cap composition — the validate gate and the accessor
8407    // must route through the same substrate-primitive typed dispatch, so
8408    // any future silent detour that had the accessor perform a
8409    // bounds-collapsing clamp would fail here at caixa-core build time.
8410    // Peer of the sibling M3
8411    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
8412    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
8413
8414    #[test]
8415    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
8416        // The canonical per-`:supervisor` restart-budget-count scalar pin:
8417        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
8418        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
8419        // typed slot's own `u32` storage, byte-equal to the raw field
8420        // access across every representative value in the accept-set —
8421        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
8422        // accept-set the surrounding [`SupervisorSpec::validate`] gate
8423        // carves out on the sibling `ZeroMaxRestarts` refusal),
8424        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
8425        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
8426        // (a past-the-guard sentinel that pins the accessor doesn't
8427        // perform a silent bounds-collapse into `1` on the zero arm —
8428        // validate rejects zero but the accessor must ship the raw slot
8429        // verbatim so a validate-time gate regression surfaces at the
8430        // emit boundary rather than being silently absorbed), `u32::MAX`
8431        // (a past-the-guard sentinel that pins the accessor doesn't
8432        // perform a silent bounds-collapse through
8433        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
8434        //
8435        // Peer of the sibling M3
8436        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
8437        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
8438        // required-scalar axis — same "the substrate-primitive accessor
8439        // must byte-equal the raw field access verbatim across every
8440        // value in the `u32` accept-set" discipline extended onto the M2
8441        // supervisor-slot per-`:supervisor` restart-budget-count axis.
8442        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
8443            let s = SupervisorSpec {
8444                max_restarts,
8445                ..SupervisorSpec::default()
8446            };
8447            assert_eq!(
8448                s.max_restarts(),
8449                max_restarts,
8450                "SupervisorSpec::max_restarts must return :supervisor \
8451                 :max-restarts verbatim (got {}, expected {max_restarts})",
8452                s.max_restarts(),
8453            );
8454            assert_eq!(
8455                s.max_restarts(),
8456                s.max_restarts,
8457                "SupervisorSpec::max_restarts accessor and .max_restarts \
8458                 field access must byte-equal — the accessor is the \
8459                 substrate-primitive typed dispatch every downstream \
8460                 restart-budget-count consumer must route through",
8461            );
8462        }
8463    }
8464
8465    #[test]
8466    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
8467        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
8468        // zero-floor + upper-cap bracket must key off
8469        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
8470        // field access. Structurally: a `SupervisorSpec { max_restarts:
8471        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
8472        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
8473        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
8474        // (with the offending count carried verbatim from the accessor
8475        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
8476        // lower boundary of the accept-set) plus a `SupervisorSpec {
8477        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
8478        // boundary) must pass validate. The four together jointly pin the
8479        // accessor + validate-gate composition: any future silent detour
8480        // that had the accessor return a fresh `1` on the zero arm (a
8481        // `.max_restarts().max(1)` collapse) would silently absorb the
8482        // `ZeroMaxRestarts` refusal at the accessor boundary and the
8483        // validate gate would accept a struct-literal `SupervisorSpec {
8484        // max_restarts: 0, .. }` — the composition pin catches that at
8485        // caixa-core build time.
8486        //
8487        // Peer of the sibling M3
8488        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
8489        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
8490        // composition axis — same "the validate / shape-gate predicate
8491        // must route through the substrate-primitive typed dispatch"
8492        // discipline extended onto the peer M2 supervisor-slot
8493        // required-`u32` composition axis.
8494        let child = ChildSpec {
8495            caixa: "worker".into(),
8496            versao: "^0.1".into(),
8497            restart: RestartPolicy::Permanent,
8498        };
8499        // Zero-floor arm.
8500        let s = SupervisorSpec {
8501            max_restarts: 0,
8502            children: vec![child.clone()],
8503            ..SupervisorSpec::default()
8504        };
8505        assert_eq!(
8506            s.validate().unwrap_err(),
8507            SupervisorError::ZeroMaxRestarts,
8508            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
8509             — the accessor and the validate gate must route through the \
8510             same substrate-primitive typed dispatch on the zero-floor arm",
8511        );
8512        // Cap arm — the surfaced `max_restarts:` field must byte-equal
8513        // the accessor's return so a future rebrand on the accessor
8514        // lands in the diagnostic without a coordinated rewrite.
8515        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
8516        let s = SupervisorSpec {
8517            max_restarts: over_cap,
8518            children: vec![child.clone()],
8519            ..SupervisorSpec::default()
8520        };
8521        match s.validate().unwrap_err() {
8522            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
8523                assert_eq!(
8524                    max_restarts,
8525                    s.max_restarts(),
8526                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
8527                     SupervisorSpec::max_restarts() — the cap-arm refusal \
8528                     reads through the lifted accessor",
8529                );
8530                assert_eq!(
8531                    max_restarts, over_cap,
8532                    "MaxRestartsExceedsCap.max_restarts must carry the \
8533                     author-declared :supervisor :max-restarts value \
8534                     verbatim (got {max_restarts}, expected {over_cap})",
8535                );
8536            }
8537            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
8538        }
8539        // Lower + upper accept-set boundaries.
8540        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
8541            let s = SupervisorSpec {
8542                max_restarts,
8543                children: vec![child.clone()],
8544                ..SupervisorSpec::default()
8545            };
8546            assert!(
8547                s.validate().is_ok(),
8548                "validate must accept max_restarts == {max_restarts} \
8549                 (an accept-set boundary of \
8550                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
8551            );
8552        }
8553    }
8554
8555    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
8556    //
8557    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
8558    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
8559    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
8560    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
8561    // supervisor-slot per-`:supervisor` restart-intensity-denominator
8562    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
8563    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
8564    // per-`:supervisor` scalar-value axis. The three pins below cover
8565    // (1) the accessor's byte-equal projection against the raw field
8566    // access across every representative value in the `Option<Duration>`
8567    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
8568    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
8569    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
8570    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
8571    // `if let Some(w) = self.restart_window() { … }` bracket-arm
8572    // composition — the validate gate and the accessor must route through
8573    // the same substrate-primitive typed dispatch, so any future silent
8574    // detour that had the accessor perform a bounds-collapsing clamp
8575    // would fail here at caixa-core build time, and (3) the accessor's
8576    // by-copy idempotence pin — the returned `Option<Duration>` must
8577    // outlive `&self` and two successive calls must return byte-equal
8578    // values. Peer of the sibling M2
8579    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
8580    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
8581    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
8582    // (7073d0f) pin on the per-`:politicas :timeout` axis.
8583
8584    #[test]
8585    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
8586        // The canonical per-`:supervisor` restart-intensity-denominator
8587        // scalar pin: [`SupervisorSpec::restart_window`] must return the
8588        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
8589        // `Option<Duration>`, `Copy`-projected from the typed slot's own
8590        // `Option<Duration>` storage, byte-equal to the raw field access
8591        // across every representative value in the accept-set — `None`
8592        // (the "never reset — every restart across the supervisor's
8593        // lifetime counts against the sibling `:max-restarts` budget"
8594        // sentinel the field's own docstring names and the peer
8595        // `validate_accepts_none_restart_window` pin locks in on the
8596        // [`SupervisorSpec::validate`] entry-side),
8597        // `Some(Duration::from_millis(1))` (the structural minimum a
8598        // validated `:restart-window` may carry, the integer-millisecond
8599        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
8600        // everything sub-ms; `Duration::ZERO` is separately rejected by
8601        // [`SupervisorError::RestartWindowZero`]),
8602        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
8603        // surrounding [`SupervisorSpec::validate`] gate carves out on the
8604        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
8605        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
8606        // accessor doesn't perform a silent bounds-collapse into `None` on
8607        // the zero-Duration arm — validate rejects zero but the accessor
8608        // must ship the raw slot verbatim so a validate-time gate
8609        // regression surfaces at the emit boundary rather than being
8610        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
8611        // sentinel that pins the accessor doesn't perform a silent
8612        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
8613        // return path).
8614        //
8615        // Peer of the sibling M2
8616        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
8617        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
8618        // sibling M3
8619        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
8620        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
8621        // substrate-primitive accessor must byte-equal the raw field
8622        // access verbatim across every value in the `Option<Duration>`
8623        // accept-set" discipline extended onto the M2 supervisor-slot
8624        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
8625        // silent detour that re-derived the restart-window from a peer
8626        // axis (an accidental `.max_restarts.into()` collapse that read
8627        // the restart-budget-count as a duration — the two axes serve
8628        // different halves of the `MaxIntensity / Period` restart-
8629        // intensity ratio, and confusing them silently inverts the
8630        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
8631        // "zero means never reset" collapse (the canonical
8632        // `Option<Duration>` → `Duration` collapse footgun the
8633        // [`SupervisorError::RestartWindowZero`] validate arm guards on
8634        // the peer zero-floor axis; a zero period either trips on the
8635        // first failure or never trips depending on operator
8636        // interpretation, neither of which is the author's "never reset"
8637        // intent that `None` expresses structurally), or a per-arm
8638        // variant swap that landed on one consumer without the other.
8639        for restart_window in [
8640            None,
8641            Some(Duration::from_millis(1)),
8642            Some(SUPERVISOR_RESTART_WINDOW_MAX),
8643            Some(Duration::ZERO),
8644            Some(Duration::MAX),
8645        ] {
8646            let s = SupervisorSpec {
8647                restart_window,
8648                ..SupervisorSpec::default()
8649            };
8650            assert_eq!(
8651                s.restart_window(),
8652                restart_window,
8653                "SupervisorSpec::restart_window must return :supervisor \
8654                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
8655                s.restart_window(),
8656            );
8657            assert_eq!(
8658                s.restart_window(),
8659                s.restart_window,
8660                "SupervisorSpec::restart_window accessor and \
8661                 .restart_window field access must byte-equal — the \
8662                 accessor is the substrate-primitive typed dispatch every \
8663                 downstream restart-intensity-denominator consumer must \
8664                 route through",
8665            );
8666        }
8667    }
8668
8669    #[test]
8670    fn validate_restart_window_bracket_arm_routes_through_accessor() {
8671        // Composition pin: [`SupervisorSpec::validate`]'s
8672        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
8673        // zero-floor + integer-millisecond canonical-form + upper-cap
8674        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
8675        // the raw `.restart_window` field access. Structurally: a
8676        // `SupervisorSpec { restart_window: None, .. }` must pass the
8677        // arm gate structurally (the `if let Some(_)` shape returns
8678        // early on the `None` arm — the accessor and the validate gate
8679        // must agree on `None → skip the bracket cascade` so an authored
8680        // `:restart-window ()` structurally routes through the "never
8681        // reset" sentinel path), a `SupervisorSpec { restart_window:
8682        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
8683        // refusal exactly, a `SupervisorSpec { restart_window:
8684        // Some(Duration::from_micros(1500)), .. }` must surface the
8685        // `RestartWindowNotCanonical` refusal exactly (with the offending
8686        // duration carried verbatim from the accessor return), a
8687        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
8688        // + Duration::from_millis(1)), .. }` must surface the
8689        // `RestartWindowExceedsCap` refusal exactly (with the offending
8690        // duration carried verbatim from the accessor return), and a
8691        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
8692        // .. }` (the lower boundary of the accept-set) plus a
8693        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
8694        // .. }` (the upper boundary) must pass validate. The six together
8695        // jointly pin the accessor + validate-gate composition: any future
8696        // silent detour that had the accessor return a fresh `None` on any
8697        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
8698        // collapse) would silently absorb the `RestartWindowZero` refusal
8699        // at the accessor boundary and the validate gate would accept a
8700        // struct-literal `SupervisorSpec { restart_window:
8701        // Some(Duration::ZERO), .. }` — the composition pin catches that
8702        // at caixa-core build time.
8703        //
8704        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
8705        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
8706        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
8707        // accessor-composition pin on the per-`:politicas :timeout` axis —
8708        // same "the validate / shape-gate predicate must route through
8709        // the substrate-primitive typed dispatch" discipline extended
8710        // onto the peer M2 supervisor-slot optional-`Duration` axis.
8711        let child = ChildSpec {
8712            caixa: "worker".into(),
8713            versao: "^0.1".into(),
8714            restart: RestartPolicy::Permanent,
8715        };
8716        // None arm — must not surface any :restart-window-shaped refusal;
8717        // the `if let Some(_)` bracket returns early on `None` structurally.
8718        let s = SupervisorSpec {
8719            restart_window: None,
8720            children: vec![child.clone()],
8721            ..SupervisorSpec::default()
8722        };
8723        assert!(
8724            s.validate().is_ok(),
8725            "validate must accept restart_window: None (the never-reset \
8726             sentinel) — the `if let Some(_)` bracket returns early on \
8727             the None arm and the accessor must agree",
8728        );
8729        // Zero-floor arm.
8730        let s = SupervisorSpec {
8731            restart_window: Some(Duration::ZERO),
8732            children: vec![child.clone()],
8733            ..SupervisorSpec::default()
8734        };
8735        assert_eq!(
8736            s.validate().unwrap_err(),
8737            SupervisorError::RestartWindowZero,
8738            "validate must reject restart_window == Some(Duration::ZERO) \
8739             with RestartWindowZero — the accessor and the validate gate \
8740             must route through the same substrate-primitive typed \
8741             dispatch on the zero-floor arm",
8742        );
8743        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
8744        // byte-equal the accessor's return so a future rebrand on the
8745        // accessor lands in the diagnostic without a coordinated rewrite.
8746        let sub_ms = Duration::from_micros(1500);
8747        let s = SupervisorSpec {
8748            restart_window: Some(sub_ms),
8749            children: vec![child.clone()],
8750            ..SupervisorSpec::default()
8751        };
8752        match s.validate().unwrap_err() {
8753            SupervisorError::RestartWindowNotCanonical { window } => {
8754                assert_eq!(
8755                    Some(window),
8756                    s.restart_window(),
8757                    "RestartWindowNotCanonical.window must byte-equal \
8758                     SupervisorSpec::restart_window().unwrap() — the \
8759                     non-canonical-arm refusal reads through the lifted \
8760                     accessor",
8761                );
8762                assert_eq!(
8763                    window, sub_ms,
8764                    "RestartWindowNotCanonical.window must carry the \
8765                     author-declared :supervisor :restart-window value \
8766                     verbatim (got {window:?}, expected {sub_ms:?})",
8767                );
8768            }
8769            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
8770        }
8771        // Cap arm — the surfaced `window:` field must byte-equal the
8772        // accessor's return.
8773        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
8774        let s = SupervisorSpec {
8775            restart_window: Some(over_cap),
8776            children: vec![child.clone()],
8777            ..SupervisorSpec::default()
8778        };
8779        match s.validate().unwrap_err() {
8780            SupervisorError::RestartWindowExceedsCap { window } => {
8781                assert_eq!(
8782                    Some(window),
8783                    s.restart_window(),
8784                    "RestartWindowExceedsCap.window must byte-equal \
8785                     SupervisorSpec::restart_window().unwrap() — the \
8786                     cap-arm refusal reads through the lifted accessor",
8787                );
8788                assert_eq!(
8789                    window, over_cap,
8790                    "RestartWindowExceedsCap.window must carry the \
8791                     author-declared :supervisor :restart-window value \
8792                     verbatim (got {window:?}, expected {over_cap:?})",
8793                );
8794            }
8795            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
8796        }
8797        // Lower + upper accept-set boundaries.
8798        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
8799            let s = SupervisorSpec {
8800                restart_window: Some(restart_window),
8801                children: vec![child.clone()],
8802                ..SupervisorSpec::default()
8803            };
8804            assert!(
8805                s.validate().is_ok(),
8806                "validate must accept restart_window == Some({restart_window:?}) \
8807                 (an accept-set boundary of \
8808                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
8809            );
8810        }
8811    }
8812
8813    #[test]
8814    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
8815        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
8816        // `Option<Duration>` by copy — `Duration` is `Copy` (so
8817        // `Option<Duration>` is `Copy`) and the accessor must return by
8818        // value, not by reference. Peer of the sibling M2
8819        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
8820        // per-`:limits :wall-clock` axis and the sibling M3
8821        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
8822        // per-`:politicas :timeout` axis, extended onto the peer M2
8823        // supervisor-slot `Option<Duration>` copy-invariant shape — the
8824        // accessor's returned `Option<Duration>` must outlive `&self`
8825        // (multiple calls must return equal values from a dropped-`&self`
8826        // copy, since the returned Option carries no borrow), and calling
8827        // the accessor twice on the same SupervisorSpec must yield the
8828        // same `Option<Duration>` verbatim (idempotent, no side effects
8829        // on `&self`).
8830        //
8831        // Pins against a future silent detour that returned
8832        // `Option<&Duration>` (which would type-check but silently break
8833        // every downstream caller — the future wasm-operator's
8834        // per-supervisor restart-intensity counter consumes `Duration` by
8835        // value and `&Duration` would fold to a detached copy at the call
8836        // site), an accidental `Option::as_ref()` projection
8837        // (`self.restart_window.as_ref()` would also type-check but
8838        // return `Option<&Duration>`), or a one-arm-only accessor that
8839        // reads `Some(*w)` in the Some arm but reads a fresh
8840        // `Default::default()` (which would collapse to `Duration::ZERO`,
8841        // not `None`) in the None arm — a footgun the
8842        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
8843        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
8844        // requires `Period > 0` and `None` structurally expresses "never
8845        // reset" instead.
8846        for restart_window in [
8847            None,
8848            Some(Duration::from_millis(1)),
8849            Some(Duration::from_secs(60)),
8850            Some(SUPERVISOR_RESTART_WINDOW_MAX),
8851        ] {
8852            let s = SupervisorSpec {
8853                restart_window,
8854                ..SupervisorSpec::default()
8855            };
8856            let first = s.restart_window();
8857            let second = s.restart_window();
8858            assert_eq!(
8859                first, second,
8860                "SupervisorSpec::restart_window must be idempotent — two \
8861                 successive calls on the same &self must return the \
8862                 same Option<Duration>",
8863            );
8864            assert_eq!(
8865                first, restart_window,
8866                "SupervisorSpec::restart_window must return :supervisor \
8867                 :restart-window verbatim by copy — got {first:?}, \
8868                 expected {restart_window:?}",
8869            );
8870        }
8871    }
8872
8873    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
8874    //
8875    // The [`SupervisorSpec::children`] accessor lift is the seed of the
8876    // slice-return (`&[T]`) accessor discipline on the substrate — the four
8877    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
8878    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
8879    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
8880    // access at the time of this seed, and inherit this pin family's
8881    // discipline as future compounding runs migrate their consumers. The
8882    // three pins below cover (1) the accessor's byte-equal projection
8883    // against the raw field access across the empty / singleton / cohort
8884    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
8885    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
8886    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
8887    // consumer routing through the accessor on both arms, and (3) the
8888    // per-child validate loop's traversal reading the same slice-view the
8889    // accessor projects. Peer of the sibling M2
8890    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
8891    // two-consumer coherence pin on the per-`:supervisor`
8892    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
8893    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
8894
8895    #[test]
8896    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
8897        // The canonical per-`:supervisor` static-child-list scalar-shape
8898        // pin: [`SupervisorSpec::children`] must return the `:supervisor
8899        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
8900        // slice-view over the same backing buffer the raw
8901        // `self.children.as_slice()` field access borrows from, byte-
8902        // equal across every representative fixture in the accept-set —
8903        // the empty slice (the `SimpleOneForOne`-arm sentinel),
8904        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
8905        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
8906        // with the peer three restart-policy variants in play).
8907        //
8908        // Pins against a future silent detour that returned
8909        // `&Vec<ChildSpec>` (which would type-check but leak the
8910        // storage-side `Vec`'s grow/push/reserve surface no consumer of
8911        // the typed view reaches for), a fresh-allocated
8912        // `Vec<ChildSpec>` copy (which would type-check via a coercion
8913        // but silently break every downstream caller that relied on the
8914        // slice sharing the backing buffer's identity), or an
8915        // out-of-order or length-drifted projection (which would silently
8916        // split the per-child validate loop's traversal input from the
8917        // paired partition-dispatch `.is_empty()` probe's input).
8918        //
8919        // Peer of the sibling
8920        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
8921        // (eafb619) `Copy`-composite-enum byte-equal pin on the
8922        // per-`:supervisor` sibling-restart-strategy axis, extended onto
8923        // the per-`:supervisor` static-child-list `Vec`-carry axis.
8924        let fixtures: Vec<Vec<ChildSpec>> = vec![
8925            Vec::new(),
8926            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
8927            vec![
8928                child("worker", "^0.1", RestartPolicy::Permanent),
8929                child("cache-server", "^0.1", RestartPolicy::Transient),
8930            ],
8931            vec![
8932                child("worker", "^0.1", RestartPolicy::Permanent),
8933                child("cache-server", "^0.1", RestartPolicy::Transient),
8934                child("scratch-job", "^0.1", RestartPolicy::Temporary),
8935            ],
8936        ];
8937        for children in fixtures {
8938            let s = SupervisorSpec {
8939                children: children.clone(),
8940                ..SupervisorSpec::default()
8941            };
8942            assert_eq!(
8943                s.children(),
8944                children.as_slice(),
8945                "SupervisorSpec::children must return :supervisor \
8946                 :children verbatim (got {:?}, expected {:?})",
8947                s.children(),
8948                children.as_slice(),
8949            );
8950            assert_eq!(
8951                s.children(),
8952                s.children.as_slice(),
8953                "SupervisorSpec::children accessor and \
8954                 .children.as_slice() field access must byte-equal — \
8955                 the accessor is the substrate-primitive typed \
8956                 dispatch every downstream static-child-list consumer \
8957                 must route through",
8958            );
8959            assert_eq!(
8960                s.children().len(),
8961                s.children.len(),
8962                "SupervisorSpec::children().len() must byte-equal \
8963                 self.children.len() — a length-drift would silently \
8964                 split the paired partition-dispatch `.is_empty()` \
8965                 probe input from the per-child validate loop's \
8966                 traversal input",
8967            );
8968        }
8969    }
8970
8971    #[test]
8972    fn validate_reads_through_lifted_children_accessor() {
8973        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
8974        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
8975        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
8976        // when the accessor projects a non-empty slice under a
8977        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
8978        // `self.children().is_empty()` refusal probe (which must trip
8979        // [`SupervisorError::NoChildren`] when the accessor projects the
8980        // empty slice under any peer estrategia), and the per-child
8981        // validate loop's `for child in self.children()` traversal
8982        // (which must reach every entry in the same order the accessor
8983        // projects) must all key off the lifted accessor, so any future
8984        // rebrand on the typed slot's reader shape lands at exactly one
8985        // place. Pins the three-site coherence by exercising each
8986        // production consumer end-to-end: (1) the
8987        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
8988        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
8989        // refusal under the empty slice + non-`SimpleOneForOne`
8990        // estrategia across every peer variant, and (3) the per-child
8991        // duplicate-detection surface fires on the second entry of a
8992        // two-child cohort that shares a `:caixa` name (which requires
8993        // the loop to reach both entries — a first-entry-only projection
8994        // would silently pass since the dedup HashSet has room for the
8995        // first insert).
8996        //
8997        // Peer of the sibling M2
8998        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
8999        // two-consumer coherence pin on the per-`:supervisor`
9000        // sibling-restart-strategy axis, extended onto the
9001        // per-`:supervisor` static-child-list `Vec`-carry axis.
9002
9003        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
9004        // `SimpleOneForOne` estrategia must trip
9005        // `SimpleOneForOneWithStaticChildren`.
9006        let s = SupervisorSpec {
9007            estrategia: RestartStrategy::SimpleOneForOne,
9008            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
9009            ..SupervisorSpec::default()
9010        };
9011        assert_eq!(
9012            s.validate().unwrap_err(),
9013            SupervisorError::SimpleOneForOneWithStaticChildren,
9014            "SimpleOneForOne + non-empty children must trip \
9015             SimpleOneForOneWithStaticChildren — the accessor projects \
9016             a non-empty slice, and the SimpleOneForOne-arm refusal \
9017             probe reads through the lifted accessor",
9018        );
9019        assert!(
9020            !s.children().is_empty(),
9021            "the SimpleOneForOne-arm refusal input must be a non-empty \
9022             slice per the accessor's projection",
9023        );
9024
9025        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
9026        // under any peer estrategia must trip `NoChildren`.
9027        for estrategia in [
9028            RestartStrategy::OneForOne,
9029            RestartStrategy::OneForAll,
9030            RestartStrategy::RestForOne,
9031        ] {
9032            let s = SupervisorSpec {
9033                estrategia,
9034                children: Vec::new(),
9035                ..SupervisorSpec::default()
9036            };
9037            match s.validate().unwrap_err() {
9038                SupervisorError::NoChildren { estrategia: e } => {
9039                    assert_eq!(
9040                        e, estrategia,
9041                        "NoChildren.estrategia must carry the author-\
9042                         declared :supervisor :estrategia variant \
9043                         verbatim (got {e:?}, expected {estrategia:?})",
9044                    );
9045                }
9046                other => panic!(
9047                    "expected NoChildren, got {other:?} for \
9048                     estrategia={estrategia:?}"
9049                ),
9050            }
9051            assert!(
9052                s.children().is_empty(),
9053                "the non-SimpleOneForOne-arm refusal input must be the \
9054                 empty slice per the accessor's projection",
9055            );
9056        }
9057
9058        // (3) Per-child validate loop: a two-child cohort that shares a
9059        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
9060        // reach both entries through the accessor.
9061        let s = SupervisorSpec {
9062            estrategia: RestartStrategy::OneForOne,
9063            children: vec![
9064                child("worker", "^0.1", RestartPolicy::Permanent),
9065                child("worker", "^0.2", RestartPolicy::Transient),
9066            ],
9067            ..SupervisorSpec::default()
9068        };
9069        match s.validate().unwrap_err() {
9070            SupervisorError::DuplicateChildCaixa { caixa } => {
9071                assert_eq!(
9072                    caixa, "worker",
9073                    "DuplicateChildCaixa.caixa must carry the shared \
9074                     child `:caixa` name verbatim",
9075                );
9076            }
9077            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
9078        }
9079        assert_eq!(
9080            s.children().len(),
9081            2,
9082            "the per-child validate loop's traversal input must be a \
9083             two-element slice per the accessor's projection",
9084        );
9085    }
9086
9087    // Shared helper for the M2 per-`:children` per-slot-gate ≡
9088    // `validate` equivalence pins: builds an `OneForOne`-estrategia
9089    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
9090    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
9091    // bracket all pass cleanly so the sole failing surface is the
9092    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
9093    // pins the two-altitude equivalence on the paired probe.
9094    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
9095        let s = SupervisorSpec {
9096            estrategia: RestartStrategy::OneForOne,
9097            children,
9098            ..SupervisorSpec::default()
9099        };
9100        let via_gate = s.validate_children().unwrap_err();
9101        let via_validate = s.validate().unwrap_err();
9102        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
9103        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
9104        assert_eq!(
9105            via_gate, via_validate,
9106            "per-slot gate ≡ validate() must discriminate the same \
9107             refusal shape",
9108        );
9109    }
9110
9111    #[test]
9112    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
9113        // Fail-before-pass-after equivalence pin on the M2
9114        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
9115        // convergence — sibling of the M3 mesh-slot
9116        // `validate_membros_*` / `validate_contratos_*` /
9117        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
9118        // peer per-entry axes. Sweeps four of the five refusal shapes
9119        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
9120        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
9121        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
9122        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
9123        // duplicate-`:caixa` fan-out. Companion pin
9124        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
9125        // covers `ChildVersaoInvalid` (whose parser-owned reason string
9126        // needs pattern-matching, not equality) and the clean-pass
9127        // canonical fixture; together the two pins guarantee the
9128        // per-slot gate and `validate` discriminate the same set on
9129        // every per-child-covered input.
9130        assert_validate_children_matches_gate(
9131            vec![child("", "^0.1", RestartPolicy::Permanent)],
9132            &SupervisorError::EmptyChildName,
9133        );
9134        assert_validate_children_matches_gate(
9135            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
9136            &SupervisorError::ChildCaixaInvalid {
9137                caixa: "Worker".into(),
9138                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
9139            },
9140        );
9141        assert_validate_children_matches_gate(
9142            vec![child("worker", "", RestartPolicy::Permanent)],
9143            &SupervisorError::EmptyChildVersion {
9144                caixa: "worker".into(),
9145            },
9146        );
9147        assert_validate_children_matches_gate(
9148            vec![
9149                child("worker", "^0.1", RestartPolicy::Permanent),
9150                child("worker", "^0.2", RestartPolicy::Transient),
9151            ],
9152            &SupervisorError::DuplicateChildCaixa {
9153                caixa: "worker".into(),
9154            },
9155        );
9156    }
9157
9158    #[test]
9159    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
9160        // Second half of the two-altitude equivalence pin — covers the
9161        // one refusal shape whose reason string is parser-owned
9162        // (`ChildVersaoInvalid`, whose reason comes from the shared
9163        // [`crate::version::parse_requirement`] impl and may drift) and
9164        // the clean-pass canonical fixture. Sibling pin
9165        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
9166        // covers the four equality-comparable refusal shapes.
9167        let s_bad_versao = SupervisorSpec {
9168            estrategia: RestartStrategy::OneForOne,
9169            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
9170            ..SupervisorSpec::default()
9171        };
9172        let via_gate = s_bad_versao.validate_children().unwrap_err();
9173        let via_validate = s_bad_versao.validate().unwrap_err();
9174        match (&via_gate, &via_validate) {
9175            (
9176                SupervisorError::ChildVersaoInvalid {
9177                    caixa: cg,
9178                    versao: vg,
9179                    ..
9180                },
9181                SupervisorError::ChildVersaoInvalid {
9182                    caixa: cv,
9183                    versao: vv,
9184                    ..
9185                },
9186            ) => {
9187                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
9188                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
9189                assert_eq!(cv, "worker", "validate() :caixa carrier");
9190                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
9191            }
9192            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
9193        }
9194        assert_eq!(
9195            via_gate, via_validate,
9196            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
9197        );
9198
9199        let s_ok = SupervisorSpec {
9200            estrategia: RestartStrategy::OneForOne,
9201            children: vec![
9202                child("worker-a", "^0.1", RestartPolicy::Permanent),
9203                child("worker-b", "~0.2.3", RestartPolicy::Transient),
9204                child("collector", "*", RestartPolicy::Temporary),
9205            ],
9206            ..SupervisorSpec::default()
9207        };
9208        s_ok.validate_children()
9209            .expect("per-slot gate must accept the clean-pass fixture");
9210        s_ok.validate()
9211            .expect("validate() must accept the clean-pass fixture");
9212    }
9213
9214    #[test]
9215    fn validate_children_is_self_contained_on_children_slot() {
9216        // Self-containment pin: [`SupervisorSpec::validate_children`]
9217        // resolves the per-child cascade against `&self` alone, without
9218        // depending on the peer `:estrategia`/`:max-restarts`/
9219        // `:restart-window` gates having run first — same posture the M3
9220        // peer per-slot gates carry (`validate_membros`,
9221        // `validate_contratos`, `validate_entrada`, `validate_placement`,
9222        // routing through their own oracles rather than borrowing state
9223        // threaded down from `validate`). A future consumer that reaches
9224        // the per-slot gate directly on a spec whose peer slots would
9225        // fail `validate` still surfaces the per-child refusal, not the
9226        // peer refusal.
9227        //
9228        // Construct a spec whose `:max-restarts` is `0` (which would
9229        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
9230        // the partition-dispatch) and whose `:children` carries a
9231        // `DuplicateChildCaixa` shape: the per-slot gate called directly
9232        // must surface `DuplicateChildCaixa`, proving it does not depend
9233        // on the peer `:max-restarts` gate running first.
9234        let s = SupervisorSpec {
9235            estrategia: RestartStrategy::OneForOne,
9236            max_restarts: 0,
9237            restart_window: Some(Duration::from_secs(60)),
9238            children: vec![
9239                child("worker", "^0.1", RestartPolicy::Permanent),
9240                child("worker", "^0.2", RestartPolicy::Transient),
9241            ],
9242        };
9243        assert_eq!(
9244            s.validate_children().unwrap_err(),
9245            SupervisorError::DuplicateChildCaixa {
9246                caixa: "worker".into(),
9247            },
9248            "per-slot gate must resolve per-child refusal directly against \
9249             `&self` — a dependency on the peer `:max-restarts` gate \
9250             running first would surface ZeroMaxRestarts here instead",
9251        );
9252        // The peer gate is still the surface `validate` reaches — pin
9253        // the ordering to establish that `validate_children` truly runs
9254        // last in `validate`'s dispatch, so a direct call bypasses the
9255        // peer gates on any spec whose per-child cascade would fail.
9256        assert_eq!(
9257            s.validate().unwrap_err(),
9258            SupervisorError::ZeroMaxRestarts,
9259            "validate() must surface the peer `:max-restarts` gate before \
9260             reaching the per-child cascade — this pins the dispatch \
9261             ordering the per-slot gate's self-containment complements",
9262        );
9263    }
9264
9265    #[test]
9266    fn child_spec_restart_accessor_is_const_fn() {
9267        // The [`ChildSpec::restart`] per-`:children` restart-decision-
9268        // policy `Copy`-return scalar accessor is declared
9269        // `#[must_use] pub const fn` — matching the sibling M2
9270        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
9271        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
9272        // both converted in this commit), the sibling M2
9273        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
9274        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
9275        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
9276        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
9277        // `Copy`-return `pub const fn` scalar accessors on the sibling
9278        // M3 surface. Pin the `const`-eval posture here so a future
9279        // accidental downgrade to non-`const` (an added runtime helper
9280        // reachable only from a non-`const` context, an
9281        // `Option<RestartPolicy>`-shape migration on the per-child
9282        // restart-decision axis once heterogeneous per-cluster
9283        // restart-policy overlays land that would silently drop the
9284        // `const` qualifier, a manual hand-rolled shadow) trips at
9285        // caixa-core build time rather than surfacing as a downstream
9286        // `const`-context regression far from the declaration.
9287        //
9288        // Same shape as the sibling M3
9289        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
9290        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
9291        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
9292        // accessor axis — the load-bearing witness lives in the
9293        // module-scope `const fn` wrapper `restart_via_const_fn` below:
9294        // a body that calls [`ChildSpec::restart`] under a `const fn`
9295        // signature is well-formed only when the callee is itself
9296        // `const fn`, so any future accidental downgrade of
9297        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
9298        // build time (const-eval E0015 `cannot call non-const method`),
9299        // strictly stronger than a runtime `assert!(CONST)` and
9300        // side-stepping the destructor-in-const restriction that
9301        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
9302        // items on `ChildSpec`'s `String` carriers.
9303        //
9304        // The runtime body sweeps every closed-set [`RestartPolicy`]
9305        // arm and asserts the wrapped and direct dispatches agree.
9306        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
9307            c.restart()
9308        }
9309        for restart in [
9310            RestartPolicy::Permanent,
9311            RestartPolicy::Transient,
9312            RestartPolicy::Temporary,
9313        ] {
9314            let c = ChildSpec {
9315                caixa: "worker".into(),
9316                versao: "^0.1".into(),
9317                restart,
9318            };
9319            assert_eq!(
9320                restart_via_const_fn(&c),
9321                c.restart(),
9322                "const-fn-wrapped and direct dispatch on \
9323                 ChildSpec::restart must agree for {restart:?}",
9324            );
9325            assert_eq!(
9326                c.restart(),
9327                restart,
9328                "ChildSpec::restart must return the storage-side \
9329                 RestartPolicy verbatim for {restart:?} (a violation \
9330                 means the accessor stopped being a raw field-return \
9331                 copy)",
9332            );
9333        }
9334    }
9335
9336    #[test]
9337    fn supervisor_spec_estrategia_accessor_is_const_fn() {
9338        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
9339        // sibling-restart-strategy `Copy`-return scalar accessor is
9340        // declared `#[must_use] pub const fn` — matching the sibling M2
9341        // per-`:children` [`ChildSpec::restart`] (pinned by
9342        // [`child_spec_restart_accessor_is_const_fn`] above, both
9343        // converted in this commit), the sibling M2 per-`:supervisor`
9344        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
9345        // accessor already `pub const fn`, and mirroring the peer M3
9346        // mesh-slot per-`:placement`
9347        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
9348        // `pub const fn` scalar accessor whose method-name discipline
9349        // the [`SupervisorSpec::estrategia`] method was authored to
9350        // match. Pin the `const`-eval posture here so a future
9351        // accidental downgrade to non-`const` (an added runtime helper
9352        // reachable only from a non-`const` context, an
9353        // `Option<RestartStrategy>`-shape migration once the substrate
9354        // grows per-cluster strategy overlays that would silently drop
9355        // the `const` qualifier, a manual hand-rolled shadow) trips at
9356        // caixa-core build time rather than surfacing as a downstream
9357        // `const`-context regression far from the declaration.
9358        //
9359        // Same shape as the sibling
9360        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
9361        // load-bearing witness lives in the module-scope `const fn`
9362        // wrapper `estrategia_via_const_fn` below: a body that calls
9363        // [`SupervisorSpec::estrategia`] under a `const fn` signature
9364        // is well-formed only when the callee is itself `const fn`,
9365        // side-stepping the destructor-in-const restriction that would
9366        // otherwise block a direct
9367        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
9368        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
9369        // carriers.
9370        //
9371        // The runtime body sweeps every closed-set [`RestartStrategy`]
9372        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
9373        // direct dispatches agree.
9374        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
9375            s.estrategia()
9376        }
9377        for &estrategia in RestartStrategy::ALL {
9378            let s = SupervisorSpec {
9379                estrategia,
9380                max_restarts: 5,
9381                restart_window: Some(Duration::from_secs(60)),
9382                children: Vec::new(),
9383            };
9384            assert_eq!(
9385                estrategia_via_const_fn(&s),
9386                s.estrategia(),
9387                "const-fn-wrapped and direct dispatch on \
9388                 SupervisorSpec::estrategia must agree for {estrategia:?}",
9389            );
9390            assert_eq!(
9391                s.estrategia(),
9392                estrategia,
9393                "SupervisorSpec::estrategia must return the storage-side \
9394                 RestartStrategy verbatim for {estrategia:?} (a violation \
9395                 means the accessor stopped being a raw field-return \
9396                 copy)",
9397            );
9398        }
9399    }
9400
9401    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
9402    // macro definition (see the paired doc-block above the macro
9403    // definition) — every generated `<ctor>(caixa: &str) -> Self`
9404    // constructor folds the uniform `Self::<Variant> { caixa:
9405    // caixa.to_string() }` one-field struct-literal onto one substrate
9406    // primitive. The three per-variant equivalence pins below
9407    // (fail-before-pass-after by construction — a byte-mismatched macro
9408    // arm would trip its equivalence pin first) lock each generated
9409    // constructor to its struct-literal peer under `PartialEq`, so
9410    // every wire-up in [`SupervisorSpec::validate_children`] and
9411    // [`validate_no_self_supervision`] on that variant produces a
9412    // byte-equal `SupervisorError` to the pre-lift open-coded
9413    // struct-literal. The cross-axis pin that follows (non-default
9414    // caixa name) routes the sole constructor input axis through
9415    // `.to_string()`, so the fold does not silently collapse onto a
9416    // fixed name.
9417    //
9418    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
9419    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
9420    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
9421    // `missing_entry_ctor_matches_struct_literal_wrap` /
9422    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
9423    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
9424    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
9425    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
9426    // on the six sibling ctor families the recent trajectory closed
9427    // on the peer `LayoutError` / `AplicacaoError` envelopes.
9428
9429    #[test]
9430    fn empty_child_version_ctor_matches_struct_literal_wrap() {
9431        assert_eq!(
9432            SupervisorError::empty_child_version("worker"),
9433            SupervisorError::EmptyChildVersion {
9434                caixa: "worker".to_string(),
9435            },
9436            "generated empty_child_version ctor must produce byte-equal \
9437             SupervisorError to the open-coded struct-literal wrap on the \
9438             same &str fixture",
9439        );
9440    }
9441
9442    #[test]
9443    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
9444        assert_eq!(
9445            SupervisorError::duplicate_child_caixa("worker"),
9446            SupervisorError::DuplicateChildCaixa {
9447                caixa: "worker".to_string(),
9448            },
9449            "generated duplicate_child_caixa ctor must produce byte-equal \
9450             SupervisorError to the open-coded struct-literal wrap on the \
9451             same &str fixture",
9452        );
9453    }
9454
9455    #[test]
9456    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
9457        assert_eq!(
9458            SupervisorError::child_supervises_self("orquestra"),
9459            SupervisorError::ChildSupervisesSelf {
9460                caixa: "orquestra".to_string(),
9461            },
9462            "generated child_supervises_self ctor must produce byte-equal \
9463             SupervisorError to the open-coded struct-literal wrap on the \
9464             same &str fixture",
9465        );
9466    }
9467
9468    // Per-variant equivalence pins for the two lifted
9469    // [`SupervisorError::child_caixa_invalid`] /
9470    // [`SupervisorError::child_versao_invalid`] inherent constructors
9471    // (fail-before-pass-after by construction — a byte-mismatched ctor body
9472    // would trip its equivalence pin first). Each pins the ctor output to
9473    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
9474    // in [`SupervisorSpec::validate_children`] on the two variants
9475    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
9476    // struct-literal on the same scalar fixtures. Peers of the sibling
9477    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
9478    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
9479    // the peer `AplicacaoError` envelope's
9480    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
9481
9482    #[test]
9483    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
9484        let caixa = "Worker";
9485        let reason = "sample reason text";
9486        assert_eq!(
9487            SupervisorError::child_caixa_invalid(caixa, reason),
9488            SupervisorError::ChildCaixaInvalid {
9489                caixa: caixa.to_string(),
9490                reason: reason.to_string(),
9491            },
9492            "lifted child_caixa_invalid ctor must produce byte-equal \
9493             SupervisorError to the open-coded struct-literal wrap on the \
9494             same (&str, reason) fixture",
9495        );
9496    }
9497
9498    #[test]
9499    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
9500        let caixa = "worker";
9501        let versao = "not-a-req";
9502        let reason = "sample reason text";
9503        assert_eq!(
9504            SupervisorError::child_versao_invalid(caixa, versao, reason),
9505            SupervisorError::ChildVersaoInvalid {
9506                caixa: caixa.to_string(),
9507                versao: versao.to_string(),
9508                reason: reason.to_string(),
9509            },
9510            "lifted child_versao_invalid ctor must produce byte-equal \
9511             SupervisorError to the open-coded struct-literal wrap on the \
9512             same (&str, &str, reason) fixture",
9513        );
9514    }
9515
9516    #[test]
9517    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
9518        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
9519        // against a `&str`-literal vs. `format!(…)` reason input to pin
9520        // both constructors accept the `impl Into<String>` bound
9521        // uniformly, so neither wire-up site drifts under a per-arm
9522        // wrapper transformation on the caller-side `reason` axis. Peer
9523        // of the sibling
9524        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
9525        // sweep on the peer `AplicacaoError` envelope.
9526        let via_literal = "literal reason text";
9527        let via_format = format!("{} reason text", "literal");
9528        assert_eq!(
9529            SupervisorError::child_caixa_invalid("Worker", via_literal),
9530            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
9531        );
9532        assert_eq!(
9533            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
9534            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
9535        );
9536    }
9537
9538    #[test]
9539    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
9540        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
9541        // &str`) through a non-default fixture name against every
9542        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
9543        // so any wrapper-side lowercase / trim / truncate / re-order on
9544        // the `caixa.to_string()` sole-field construction surfaces
9545        // here rather than at a downstream diagnostic-shape mismatch.
9546        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
9547        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
9548        // through_to_string` / `contrato_target_ctors_route_edge_
9549        // triple_through_verbatim` / `contrato_empty_pair_ctors_
9550        // route_edge_pair_through_verbatim` cross-axis routing pins on
9551        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
9552        // here onto the `SupervisorError` `{ caixa: String }` envelope
9553        // so every substrate-primitive ctor family in caixa-core
9554        // guarantees the sole-field construction routes the caller's
9555        // `&str` through `.to_string()` verbatim.
9556        let name = "cache-v2";
9557        assert_eq!(
9558            SupervisorError::empty_child_version(name),
9559            SupervisorError::EmptyChildVersion {
9560                caixa: name.to_string(),
9561            },
9562        );
9563        assert_eq!(
9564            SupervisorError::duplicate_child_caixa(name),
9565            SupervisorError::DuplicateChildCaixa {
9566                caixa: name.to_string(),
9567            },
9568        );
9569        assert_eq!(
9570            SupervisorError::child_supervises_self(name),
9571            SupervisorError::ChildSupervisesSelf {
9572                caixa: name.to_string(),
9573            },
9574        );
9575    }
9576
9577    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
9578    //
9579    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
9580    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
9581    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
9582    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
9583    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
9584    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
9585    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
9586    // / silent constant-substitution on any one variant surfaces here rather
9587    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
9588    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
9589    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
9590    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
9591    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
9592    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
9593    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
9594    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
9595    #[test]
9596    fn no_children_ctor_matches_struct_literal_wrap() {
9597        let estrategia = RestartStrategy::OneForAll;
9598        assert_eq!(
9599            SupervisorError::no_children(estrategia),
9600            SupervisorError::NoChildren { estrategia },
9601            "generated no_children ctor must produce byte-equal \
9602             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
9603             on the same `Copy`-`RestartStrategy` fixture",
9604        );
9605    }
9606
9607    #[test]
9608    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
9609        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
9610        assert_eq!(
9611            SupervisorError::max_restarts_exceeds_cap(max_restarts),
9612            SupervisorError::MaxRestartsExceedsCap { max_restarts },
9613            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
9614             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
9615             struct-literal wrap on the same `Copy`-`u32` fixture",
9616        );
9617    }
9618
9619    #[test]
9620    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
9621        let window = Duration::from_micros(1_500);
9622        assert_eq!(
9623            SupervisorError::restart_window_not_canonical(window),
9624            SupervisorError::RestartWindowNotCanonical { window },
9625            "generated restart_window_not_canonical ctor must produce \
9626             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
9627             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
9628        );
9629    }
9630
9631    #[test]
9632    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
9633        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
9634        assert_eq!(
9635            SupervisorError::restart_window_exceeds_cap(window),
9636            SupervisorError::RestartWindowExceedsCap { window },
9637            "generated restart_window_exceeds_cap ctor must produce \
9638             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
9639             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
9640        );
9641    }
9642
9643    #[test]
9644    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
9645        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
9646        // constructor input axis through a non-default `Copy` fixture against
9647        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
9648        // side silent `.into()` / silent constant-substitution / silent field
9649        // re-name away from the canonical `estrategia | max_restarts | window`
9650        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
9651        // axis silently rerouted through some other `Copy` coercion, surfaces
9652        // here rather than at a downstream per-`:supervisor` diagnostic-shape
9653        // drift. Peer of the sibling
9654        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
9655        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
9656        // envelope's per-`:politicas` per-axis ctor family, extended here onto
9657        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
9658        // variant family folded onto a substrate primitive.
9659        //
9660        // Fixtures picked out of each variant's accept-set boundary rather
9661        // than the default value so a silent constant-substitution to a per-
9662        // variant sentinel surfaces here on the structural-equality assertion.
9663        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
9664        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
9665        // isn't the `SimpleOneForOne` arm the sibling
9666        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
9667        // `max_restarts` fixture picks an above-cap magnitude the cap arm
9668        // rejects; the two `Duration` fixtures pick the sub-millisecond and
9669        // above-cap ends of the `:restart-window` canonical-form + cap
9670        // bracket respectively.
9671        let estrategia = RestartStrategy::RestForOne;
9672        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
9673        let sub_ms = Duration::from_micros(1_500);
9674        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
9675        assert_eq!(
9676            SupervisorError::no_children(estrategia),
9677            SupervisorError::NoChildren { estrategia },
9678        );
9679        assert_eq!(
9680            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
9681            SupervisorError::MaxRestartsExceedsCap {
9682                max_restarts: above_cap_restarts,
9683            },
9684        );
9685        assert_eq!(
9686            SupervisorError::restart_window_not_canonical(sub_ms),
9687            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
9688        );
9689        assert_eq!(
9690            SupervisorError::restart_window_exceeds_cap(above_hour),
9691            SupervisorError::RestartWindowExceedsCap { window: above_hour },
9692        );
9693    }
9694
9695    #[test]
9696    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
9697        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
9698        // generated ctor `const fn` so a caller can pin a `SupervisorError`
9699        // at compile time — the same zero-runtime-work property the pre-lift
9700        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
9701        // its `Copy`-pass-through construction path (no `.to_string()` /
9702        // `.into()` allocation, no branching). If any future edit silently
9703        // drops the `const` qualifier from the macro body the per-arm `const`
9704        // bindings below fail to compile, which surfaces the regression at
9705        // the substrate-primitive definition rather than at some downstream
9706        // consumer that had come to rely on the `const`-constructibility.
9707        // Peer of the sibling
9708        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
9709        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
9710        // per-`:politicas` per-axis ctor family.
9711        const NO_CHILDREN: SupervisorError =
9712            SupervisorError::no_children(RestartStrategy::OneForAll);
9713        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
9714        const WINDOW_NC: SupervisorError =
9715            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
9716        const WINDOW_CAP: SupervisorError =
9717            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
9718        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
9719        assert!(matches!(
9720            MAX_RESTARTS_CAP,
9721            SupervisorError::MaxRestartsExceedsCap { .. }
9722        ));
9723        assert!(matches!(
9724            WINDOW_NC,
9725            SupervisorError::RestartWindowNotCanonical { .. }
9726        ));
9727        assert!(matches!(
9728            WINDOW_CAP,
9729            SupervisorError::RestartWindowExceedsCap { .. }
9730        ));
9731    }
9732}