Skip to main content

caixa_core/
supervisor.rs

1//! OTP-shaped supervisor trees, encoded as a typed `:kind Supervisor`
2//! caixa with a strategy + restart-policy children list.
3//!
4//! See `theory/INSPIRATIONS.md` §II.2 + §III.2 for the prior-art frame
5//! (Erlang OTP supervisor + Lunatic supervisor strategies as Rust types).
6//!
7//! ```lisp
8//! (defcaixa
9//!   :nome           "my-app-root"
10//!   :versao         "0.1.0"
11//!   :kind           Supervisor
12//!   :estrategia     OneForOne
13//!   :max-restarts   5
14//!   :restart-window "60s"
15//!   :children       ((:caixa "worker"       :versao "^0.1" :restart Permanent)
16//!                    (:caixa "cache-server" :versao "^0.1" :restart Transient)
17//!                    (:caixa "scratch-job"  :versao "^0.1" :restart Temporary)))
18//! ```
19//!
20//! wasm-operator (M3) walks the tree, materializes one ComputeUnit per
21//! child, and applies the strategy on child failure. The Rust types
22//! here are the typed contract; the runtime owns lifecycle.
23
24use std::time::Duration;
25
26use serde::{Deserialize, Serialize};
27use thiserror::Error;
28
29/// One of the four canonical Erlang/OTP restart strategies.
30///
31/// The strategy decides what happens to *sibling* children when one
32/// child dies. Per-child behaviour is governed by [`RestartPolicy`].
33#[derive(
34    Serialize,
35    Deserialize,
36    Debug,
37    Clone,
38    Copy,
39    PartialEq,
40    Eq,
41    Hash,
42    gen_platform::TypedDispatcher,
43    gen_platform::Discriminant,
44    gen_platform::IsVariant,
45    gen_platform::FromStrKind,
46)]
47pub enum RestartStrategy {
48    /// On child failure, restart only that child. Default; matches
49    /// most "tree of independent workers" use cases.
50    OneForOne,
51    /// On child failure, restart every child. Used when children
52    /// share state and must be in sync.
53    OneForAll,
54    /// On child failure, restart the failed child and every child
55    /// started *after* it (preserving startup order). Used when later
56    /// children depend on earlier ones.
57    RestForOne,
58    /// Dynamic children of the same shape, started on demand. The
59    /// supervisor doesn't know its children at boot; they're added as
60    /// they're needed (e.g. one child per session).
61    SimpleOneForOne,
62}
63
64impl Default for RestartStrategy {
65    fn default() -> Self {
66        // Route the [`Default for RestartStrategy`] impl through the
67        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
68        // `pub const` rather than a raw `Self::OneForOne` arm — one
69        // source of truth for the Erlang/OTP `one_for_one` half of Learn
70        // You Some Erlang's `{one_for_one, intensity, 5, 60}` worker-
71        // supervisor canonical default, paired with the sibling
72        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `MaxIntensity` half (b698ec0)
73        // and `SUPERVISOR_RESTART_WINDOW_DEFAULT` `Period` half (f7dcd0e).
74        // Pinned by `restart_strategy_default_routes_through_lifted_default`.
75        SUPERVISOR_ESTRATEGIA_DEFAULT
76    }
77}
78
79impl RestartStrategy {
80    /// Exhaustive iteration surface for every consumer that walks the
81    /// closed four-arm [`RestartStrategy`] discriminator set (the future
82    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
83    /// admission-webhook rejection body naming the accepted-`:estrategia`
84    /// list, a future `feira supervisor --estrategia …` CLI arg-parse's
85    /// "did you mean" hint via a [`Self::from_wire`]-scan over the slice,
86    /// the future `feira app graph` per-supervisor `:estrategia` column,
87    /// any future round-trip fuzz harness that sweeps every arm). A
88    /// future arm addition (an OTP-`rest_for_all` arm the theory
89    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
90    /// might reach for once the four canonical OTP strategies stop
91    /// covering the substrate's discovered load-shape) extends this
92    /// slice as one edit and every consumer picks up the new entry by
93    /// construction; the compiler-checked exhaustiveness on the sibling
94    /// method `match` arms ([`Self::as_str`] / [`Self::from_wire`]) is
95    /// the build-time guarantee that no arm forgets to grow.
96    ///
97    /// Peer of the sibling closed-set typed enums'
98    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
99    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
100    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
101    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
102    /// surfaces — the fifth (and the first M2 OTP-shape) closed-set
103    /// typed enum on the caixa surface to converge onto the same
104    /// one-canonical-arm-list-per-enum discipline.
105    pub const ALL: &'static [Self] = &[
106        Self::OneForOne,
107        Self::OneForAll,
108        Self::RestForOne,
109        Self::SimpleOneForOne,
110    ];
111
112    /// Canonical PascalCase discriminator scalar this variant serializes
113    /// as under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`]. The four arms
114    /// return the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
115    /// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
116    /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
117    /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] lifted
118    /// constants so every substrate consumer that dispatches on the
119    /// per-supervisor sibling-restart strategy (the future
120    /// wasm-operator's per-supervisor sibling-restart branch, the future
121    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
122    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
123    /// reconciliation scheduler's per-strategy fan-out) reads the same
124    /// byte-string the `Serialize` derive emits — the pin test in
125    /// [`tests::restart_strategy_variants_serialize_to_lifted_scalar_values`]
126    /// asserts the two paths agree, peer of the M3
127    /// `PlacementStrategy::as_str` (cc8f749) on the sibling per-Aplicacao
128    /// distribution-strategy axis.
129    #[must_use]
130    pub const fn as_str(self) -> &'static str {
131        match self {
132            Self::OneForOne => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
133            Self::OneForAll => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
134            Self::RestForOne => crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
135            Self::SimpleOneForOne => crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
136        }
137    }
138
139    /// Substrate-canonical reverse projection on the `:supervisor
140    /// :estrategia` closed-set axis — parses the `PascalCase`
141    /// discriminator scalar back to the typed variant, or `None` when
142    /// `s` is outside
143    /// the closed-set arm-string set [`Self::as_str`] emits. Dispatches
144    /// on the same lifted
145    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
146    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
147    /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
148    /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
149    /// constants the [`Self::as_str`] emitter walks, so the parse and
150    /// emit halves of the round-trip migrate through one caixa-core
151    /// edit on any future arm addition.
152    ///
153    /// Prior to this lift the substrate carried only the forward
154    /// `Self → &str` projection on the OTP sibling-restart axis (the
155    /// [`Self::as_str`] emitter, the [`std::fmt::Display`] impl routed
156    /// through it, the `Serialize` derive that emits the same
157    /// byte-string under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`])
158    /// plus the kebab-case dispatcher-catalog identity via
159    /// [`Self::discriminant`] — every non-serde consumer that wanted to
160    /// parse a wire-form `PascalCase` strategy scalar had to re-inline
161    /// a four-arm `match s { "OneForOne" => …, "OneForAll" => …,
162    /// "RestForOne" => …, "SimpleOneForOne" => …, _ => … }` cascade
163    /// that expressed no compile-time link back to the typed variant's
164    /// canonical lifted constant. A future variant rename or per-arm
165    /// serde-attribute drift would silently split the wire byte-string
166    /// one non-serde consumer parsed from the one the emitter wrote,
167    /// with the failure surfacing at parse time far from the rebrand
168    /// commit.
169    ///
170    /// Distinct axis from the [`std::str::FromStr`] impl the
171    /// [`gen_platform::FromStrKind`] derive already installs on this
172    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
173    /// dispatcher-catalog identity (`"one-for-one"` / `"one-for-all"` /
174    /// `"rest-for-one"` / `"simple-one-for-one"` — the inverse of
175    /// [`Self::discriminant`]), while this method inverts the
176    /// `PascalCase` wire byte-string [`Self::as_str`] emits. The
177    /// two-axis split lets the dispatcher-catalog identity live in
178    /// kebab-case
179    /// (where every peer catalog identifier already lives) without
180    /// forcing a wire-format rename on the tatara-lisp author surface
181    /// (`:estrategia OneForOne`, `PascalCase`) — the same two-axis
182    /// distinction the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
183    /// / [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
184    /// carry on their peer closed-set typed-enum wire round-trips.
185    ///
186    /// Same closed-set-reverse-projection discipline the sibling
187    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
188    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
189    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
190    /// carry on the peer wire-side `str → Self` axes — extended onto
191    /// the M2 OTP-shape sibling-restart-strategy closed-set axis, the
192    /// fifth substrate-side closed-set typed enum to converge on the
193    /// two-way `str ↔ Self` round-trip. Method-named `from_wire` (not
194    /// `from_str`) to match the peer [`crate::CaixaKind::from_wire`]
195    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
196    /// derive already installs on the sibling kebab-case axis. Returns
197    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
198    /// shapes: the caller picks the diagnostic form appropriate for
199    /// its use site.
200    #[must_use]
201    pub fn from_wire(s: &str) -> Option<Self> {
202        match s {
203            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE => Some(Self::OneForOne),
204            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL => Some(Self::OneForAll),
205            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE => Some(Self::RestForOne),
206            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE => Some(Self::SimpleOneForOne),
207            _ => None,
208        }
209    }
210}
211
212/// [`std::fmt::Display`] routed through [`RestartStrategy::as_str`], so the
213/// pretty-printed byte-string every consumer that formats the strategy as
214/// user-facing text lands on (the future wasm-operator's per-supervisor
215/// sibling-restart-strategy diagnostic line, the future `feira app graph`
216/// per-supervisor strategy line, the future M4
217/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission-webhook
218/// rejection body) reaches for the same lifted
219/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
220/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
221/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
222/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
223/// wire-format `Serialize` derive already emits under
224/// [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the
225/// [`RestartStrategy::as_str`] helper already returns.
226///
227/// Pre-convergence the two paths structurally disagreed — the
228/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
229/// route (now retired here) sent [`std::fmt::Display`] through the
230/// gen-platform discriminant catalog string, which arrives kebab-case as
231/// `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
232/// `"simple-one-for-one"`, while the wire format ran as `PascalCase`
233/// `"OneForOne"` / `"OneForAll"` / `"RestForOne"` / `"SimpleOneForOne"`
234/// through the un-`rename`d serde derive. Every consumer that formatted
235/// the strategy for a diagnostic line, a graph, or a rejection body under
236/// `format!("{v}")` therefore landed under a different byte-string than
237/// the wire format the operator's per-strategy dispatch keyed off — a
238/// silent split whose apply-time symptom (a `format!("{v}")`-carrying
239/// diagnostic quoting `"one-for-one"` while the wire scalar the operator
240/// probed was `"OneForOne"`) surfaced as a confused correlate at
241/// operator-log time far from the two-declaration site.
242///
243/// Routing `Display` through [`RestartStrategy::as_str`] closes the third
244/// path: every `format!("{v}")` call reaches the same lifted
245/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const the wire format and
246/// the [`RestartStrategy::as_str`] helper route through — `Debug` (the
247/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
248/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
249/// byte-string per variant. A future variant rename or
250/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
251/// exactly one place, structurally.
252///
253/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
254/// (from `#[derive(gen_platform::Discriminant)]`) still returns
255/// `"one-for-one"` / etc., and the fleet-wide
256/// [`gen_platform::register_dispatcher!("caixa.restart-strategy", …)`]
257/// registration keys the catalog off the same kebab identity. The two
258/// naming worlds now live on separate typed methods (`Display` /
259/// `as_str` for the wire byte-string, `discriminant` for the catalog
260/// identity) rather than sharing one `Display` route that structurally
261/// disagrees with the wire format.
262///
263/// Pin tests
264/// [`tests::restart_strategy_display_routes_through_as_str_helper`]
265/// and
266/// [`tests::restart_strategy_display_matches_serialized_wire_byte_string`]
267/// assert the three paths agree byte-for-byte on every variant, so a
268/// future variant rename or per-arm serde attribute drift is a build
269/// error visible at caixa-core test time, not a silent per-consumer
270/// dispatch miss at apply / reconcile time.
271///
272/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
273/// (aplicacao.rs:2306) on the sibling per-Aplicacao distribution-strategy
274/// axis — same three-path-convergence discipline, extended to close the
275/// second of three OTP-shaped closed-enum discriminator axes on the
276/// caixa typed surface.
277impl std::fmt::Display for RestartStrategy {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        f.write_str(self.as_str())
280    }
281}
282
283/// Substrate-canonical [`AsRef<str>`] projection on the M2
284/// per-supervisor sibling-restart [`RestartStrategy`] closed-set typed
285/// enum — routes through the same [`RestartStrategy::as_str`]
286/// `pub const fn` scalar accessor the paired [`std::fmt::Display`]
287/// impl and the un-`rename`d [`serde::Serialize`] derive already key
288/// off, so any future consumer that binds a [`RestartStrategy`]
289/// through the standard-library `impl AsRef<str>` bound (a future
290/// [`caixa-feira`] `feira supervisor --estrategia <arm>` verb that
291/// composes the emitted `PascalCase` wire scalar into a
292/// [`std::process::Command::arg`] shell-out of the future
293/// wasm-operator's admission gate, a per-supervisor structured-log
294/// recorder on the future `caixa-operator`'s hierarchical
295/// reconciliation surface that accepts `impl AsRef<str>` at the
296/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
297/// lookup keyed on the estrategia wire byte through
298/// `map.get::<str>(strategy.as_ref())` on a future per-strategy
299/// dispatch table) reaches the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
300/// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
301/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
302/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
303/// lifted-const through one substrate-primitive dispatch rather
304/// than an open-coded `.as_str()` projection at every wire-up.
305///
306/// Peer of the sibling [`std::fmt::Display`] impl on the same
307/// primitive — both delegate to the shared
308/// [`RestartStrategy::as_str`] `pub const fn` accessor, so
309/// [`format!("{s}")`], `s.as_str()`, and
310/// `<RestartStrategy as AsRef<str>>::as_ref(&s)` resolve to the same
311/// byte-string per instance by construction. A future variant rename
312/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
313/// enum reaches every one of the three paths (plus the wire-format
314/// `Serialize` derive that already routes through the same lifted
315/// const) through exactly one caixa-core edit.
316///
317/// Same "route the trait impl through the substrate-primitive
318/// accessor" discipline the sibling [`crate::CaixaVersion`]
319/// [`AsRef<str>`] impl (16d5c7e) carries on the paired top-level
320/// `:versao` typed newtype — extends it onto the second `AsRef<str>`
321/// axis on the caixa typed surface (the first M2 OTP-shape
322/// closed-set typed enum to converge onto the standard-library
323/// [`AsRef<str>`] projection). Rust-side newtype/typed-enum
324/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
325/// primitive so a caller who has one has both; before this lift,
326/// [`RestartStrategy`] carried [`fmt::Display`] but not the paired
327/// [`AsRef<str>`] impl the convention names.
328///
329/// Pinned load-bearing by
330/// [`tests::restart_strategy_as_ref_str_routes_through_as_str_accessor`]
331/// (byte-parity pin against [`RestartStrategy::as_str`] across the
332/// four-arm closed set) — any future silent detour that routes the
333/// impl through a divergent projection (a per-arm inline
334/// `match self { … }` re-inlining that opens a compile-time link to
335/// the un-lifted arm-literal, a swap onto the kebab-case
336/// [`gen_platform::Discriminant`] catalog identity that would collide
337/// the wire axis with the dispatcher-catalog axis) trips at
338/// caixa-core test time under `assert_eq!` rather than at a
339/// downstream `impl AsRef<str>`-bound consumer's silent split.
340impl AsRef<str> for RestartStrategy {
341    fn as_ref(&self) -> &str {
342        self.as_str()
343    }
344}
345
346/// Trait-idiomatic reverse projection on the M2-OTP-shape sibling-restart
347/// [`RestartStrategy`] closed-set typed enum — routes byte-for-byte through
348/// the paired substrate-primitive [`RestartStrategy::from_wire`]
349/// `Option<Self>` accessor so every future consumer that binds a
350/// `PascalCase` `:supervisor :estrategia` wire byte-string through the
351/// standard-library `.try_into()` / [`TryFrom`] axis (a future
352/// [`caixa-feira`] `feira supervisor --estrategia <OneForOne|OneForAll|
353/// RestForOne|SimpleOneForOne>` CLI arg-parse that composes into
354/// `let estrategia: RestartStrategy = s.try_into()?`, a future
355/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
356/// `spec.estrategia: String` field through
357/// `RestartStrategy::try_from(&s)?`, a generic
358/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
359/// set typed enums) reaches the same four-arm accept-set the sibling
360/// [`RestartStrategy::from_wire`] resolver parses through and the sibling
361/// [`RestartStrategy::as_str`] emits, rather than an open-coded per-arm
362/// `match s { "OneForOne" => …, "OneForAll" => …, "RestForOne" => …,
363/// "SimpleOneForOne" => …, _ => … }` cascade whose arm-set has no
364/// compile-time link back to the substrate primitive.
365///
366/// Complements the pre-existing forward-projection triple
367/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartStrategy::as_str`])
368/// with the paired trait-idiomatic reverse-projection axis: Rust-side
369/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
370/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
371/// caller who can project *out to* a `&str` can also project *in from*
372/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
373/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
374/// lint the sibling method-named [`RestartStrategy::from_wire`] would
375/// trigger under a `FromStr` impl and to avoid colliding with the
376/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
377/// already installs on the paired *kebab-case dispatcher-catalog* axis
378/// (which parses `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
379/// `"simple-one-for-one"`, the inverse of [`Self::discriminant`]) — this
380/// impl closes the trait-idiomatic reverse axis on the *`PascalCase` wire*
381/// half without disturbing either the method-named `from_wire` shape every
382/// sibling closed-set typed enum on the substrate already carries or the
383/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
384/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
385///
386/// `type Error = ()` matches the sibling [`RestartStrategy::from_wire`]'s
387/// `Option<Self>` return-shape's deliberate deferral of error typing: the
388/// caller picks the diagnostic form appropriate for its use site (a future
389/// `feira supervisor --estrategia` arg-parse composes its own per-verb
390/// "unknown strategy: <arg> — accepted: {…}" message enumerating
391/// [`RestartStrategy::ALL`], a future M4 admission-webhook rejection body
392/// wraps the `Err(())` outcome with the accepted-set enumeration for
393/// operator diagnostics, a `Result::map_err` at the call site lifts the
394/// unit-error to a per-verb error type). Same shape the peer
395/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136),
396/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd), and
397/// [`crate::provedor::ferrite::FerriteRuntime::from_wire`] blocks motivate
398/// on their peer closed-set typed enums' reverse projections.
399///
400/// The paired [`TryFrom<&str>`] impl reaches the same four-arm accept-set
401/// the [`RestartStrategy::from_wire`] resolver dispatches through, so any
402/// future arm addition (an OTP-`rest_for_all` fifth arm the theory
403/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
404/// might reach for once the four canonical OTP strategies stop covering
405/// the substrate's discovered load-shape) grows the trait-idiomatic axis
406/// by construction — one caixa-core edit on
407/// [`RestartStrategy::from_wire`] extends both the method-named reverse
408/// projection every existing consumer keys off and the trait-idiomatic
409/// reverse projection this impl exposes, without a coordinated rewrite
410/// across every future `TryFrom<&str>`-bound consumer's arm-set.
411///
412/// Extends the substrate-wide closed-set-enum reverse-projection family
413/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via bf33136,
414/// [`crate::aplicacao::PlacementStrategy`] via 6fd00cd) onto the first
415/// M2-OTP-shape closed-set typed enum on the caixa surface — the
416/// `:supervisor :estrategia` closed set the future wasm-operator's
417/// hierarchical reconciliation scheduler keys off end-to-end.
418///
419/// Pinned load-bearing by
420/// [`tests::restart_strategy_try_from_str_routes_through_from_wire_accessor`]
421/// (byte-parity pin against [`RestartStrategy::from_wire`] across the
422/// four-arm accept-set) and
423/// [`tests::restart_strategy_try_from_str_rejects_unknown_byte_strings`]
424/// (rejection witness against silent accept-set widening).
425impl TryFrom<&str> for RestartStrategy {
426    type Error = ();
427
428    fn try_from(s: &str) -> Result<Self, Self::Error> {
429        Self::from_wire(s).ok_or(())
430    }
431}
432
433/// Trait-idiomatic *forward* projection on the M2-OTP-shape sibling-restart
434/// [`RestartStrategy`] closed-set typed enum onto the `&'static str` axis —
435/// routes byte-for-byte through the paired substrate-primitive
436/// [`RestartStrategy::as_str`] `pub const fn` accessor so every future
437/// consumer that binds a [`RestartStrategy`] through the standard-library
438/// `.into()` / [`From<Self> for &'static str`] (equivalently
439/// [`Into<&'static str>`]) axis (a future
440/// `tracing::field::valuable::Value::Str(strategy.into())` structured-log
441/// recorder where the `Str` arm typing demands `&'static str` and the
442/// sibling [`AsRef<str>`] impl's borrowed `&str` return-type does not
443/// satisfy the bound, a future `Cow::Borrowed::<'static, str>(strategy.into())`
444/// composer on the future M4 admission-webhook rejection body where the
445/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`] borrowed
446/// return, a generic `<T: Into<&'static str>>`-bound serializer on a
447/// per-strategy diagnostic column) reaches the same lifted
448/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
449/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
450/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
451/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
452/// paired [`std::fmt::Display`], [`AsRef<str>`], and
453/// [`RestartStrategy::as_str`] surfaces already return, rather than an
454/// open-coded per-arm `match s { OneForOne => "OneForOne", … }` cascade
455/// whose arm-set has no compile-time link back to the substrate primitive.
456///
457/// Complements the pre-existing quadruple
458/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartStrategy::as_str`],
459/// [`TryFrom<&str>`] via 5b828ed) with the paired trait-idiomatic
460/// forward-projection axis: Rust-side newtype/typed-enum convention pairs
461/// [`TryFrom<&str>`] (trait-idiomatic reverse) with [`From<Self> for
462/// &'static str`] (trait-idiomatic forward) on the same primitive so a
463/// caller who can project *in from* a `&str` via the trait axis can also
464/// project *out to* one — mirroring the `strum::IntoStaticStr` /
465/// `serde::Serialize`-shape idiom where both projection halves share one
466/// trait-driven vocabulary. Before this lift the substrate carried a
467/// `&str`-returning [`AsRef<str>`] but not the paired `&'static str`-
468/// returning [`From<Self> for &'static str`] axis every downstream
469/// generic that specifically needs `'static` byte-string bytes reaches for.
470///
471/// The paired [`RestartStrategy::as_str`] returns `&'static str` by
472/// construction (each `match` arm resolves to a
473/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str` with static
474/// lifetime), so the trait's return-type promise is upheld structurally.
475/// Any future silent detour that routes the impl through a non-static
476/// projection (a per-arm inline `String::from("OneForOne")`-shaped
477/// re-inlining that would `.leak()`-cast for the `'static` bound, a
478/// hypothetical rebrand of one arm's [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
479/// const to a non-`const &str`) is a caixa-core-build-time failure through
480/// the `pub const fn as_str` signature the trait routes through.
481///
482/// The paired impl reaches the same four-arm emit-set the
483/// [`RestartStrategy::as_str`] accessor dispatches through, so any future
484/// arm addition (an OTP-`rest_for_all` fifth arm the theory
485/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
486/// might reach for once the four canonical OTP strategies stop covering
487/// the substrate's discovered load-shape) grows the trait-idiomatic
488/// forward axis by construction — one caixa-core edit on
489/// [`RestartStrategy::as_str`] extends every one of the five sibling
490/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
491/// [`RestartStrategy::as_str`] itself, this [`From<Self> for &'static str`],
492/// and the un-`rename`d [`serde::Serialize`] derive that also emits
493/// [`Self::as_str`]'s bytes) without a coordinated rewrite across every
494/// future `Into<&'static str>`-bound consumer's arm-set.
495///
496/// Opens the substrate-wide trait-idiomatic *forward*-projection family on
497/// closed-set fieldless typed enums — the mirror of the recently-closed
498/// trait-idiomatic *reverse*-projection family ([`crate::CaixaKind`] via
499/// 3c83606, [`crate::CaixaDialeto`] via bf33136,
500/// [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, this enum via
501/// 5b828ed, [`crate::supervisor::RestartPolicy`] via 6fdd0d9,
502/// [`crate::aplicacao::WitShape`] via 5472902,
503/// [`crate::aplicacao::RateLimitUnit`] via bf78400,
504/// [`crate::render::PathShapeViolation`] via e67e48a, and the four
505/// downstream-crate peers — [`caixa_arch::InvariantKind`] via e21a857,
506/// [`caixa_arch::ArchVerdict`] via 0a4cc45, [`caixa_lint::Severity`] via
507/// a7bf74c, [`caixa_lint::FixSafety`] via df86c94,
508/// [`caixa_theme::Semantic`] via bd7da69, and
509/// [`caixa_provedor::ferrite::FerriteRuntime`] via 42ab951). This lift
510/// picks [`RestartStrategy`] as the first-mover on the forward-projection
511/// family because its wire byte-string (`PascalCase`) and diagnostic
512/// byte-string ([`as_str`] return) coincide by construction — the sibling
513/// [`crate::CaixaKind`] two-axis split (lowercase Portuguese diagnostic
514/// vs `PascalCase` wire) would leave a first-mover peer arbitrarily
515/// picking one axis; on [`RestartStrategy`] the choice is unambiguous.
516///
517/// Pinned load-bearing by
518/// [`tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
519/// (byte-parity pin against [`RestartStrategy::as_str`] across the
520/// four-arm emit-set, plus a `const`-context materialization witness for
521/// the `&'static str` lifetime promise) and
522/// [`tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
523/// (partition pin asserting `<&'static str as From<RestartStrategy>>::from`
524/// and [`RestartStrategy::as_str`] agree on every arm, so no future
525/// silent bifurcation of the two forward-projection paths can land
526/// silently).
527impl From<RestartStrategy> for &'static str {
528    fn from(strategy: RestartStrategy) -> &'static str {
529        strategy.as_str()
530    }
531}
532
533/// Trait-idiomatic *forward* projection on [`RestartStrategy`] from a
534/// *borrowed* input onto the `&'static str` axis — the borrowed-input
535/// companion to the paired owned-input [`From<RestartStrategy> for
536/// &'static str`] impl immediately above. Routes byte-for-byte through
537/// the same substrate-primitive [`RestartStrategy::as_str`] `pub const
538/// fn` accessor so every consumer that binds a `&RestartStrategy`
539/// through the standard-library `.into()` / [`From<&Self> for &'static
540/// str`] axis (a `RestartStrategy::ALL.iter().map(<&'static
541/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
542/// whose iterator over `&'static [RestartStrategy]` yields
543/// `&RestartStrategy`, not `RestartStrategy`, so the owned-input
544/// [`From<RestartStrategy>`] axis alone forces every call site through
545/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
546/// rather than the direct trait-idiomatic projection; a future generic
547/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
548/// that walks the `iter().map(Into::into)` shape verbatim across every
549/// substrate-wide closed-set typed enum; the future wasm-operator's
550/// per-supervisor sibling-restart-strategy diagnostic line that
551/// composes the accepted-set enumeration from an iterated
552/// `RestartStrategy::ALL.iter().map(|s| s.into())` pipe rather than a
553/// per-arm `match s { … }` cascade; a future
554/// `HashMap::<&'static str, RestartStrategy>::from_iter(
555///     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
556/// per-strategy reverse-lookup table the sibling [`TryFrom<&str>`]
557/// impl cannot compose without this borrowed-input axis in place)
558/// reaches the same four-arm lifted
559/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
560/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
561/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
562/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
563/// the paired owned-input [`From<RestartStrategy> for &'static str`],
564/// the sibling [`std::fmt::Display`], [`AsRef<str>`], and
565/// [`RestartStrategy::as_str`] surfaces already return.
566///
567/// Fourth peer on the substrate-wide trait-idiomatic *borrowed-input*
568/// forward-projection family opened on [`crate::dep::DepList`]
569/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a) and
570/// [`crate::CaixaDialeto`] (807b0b5). Rust's `From` trait does not
571/// auto-derive the `From<&Self>` sibling from a `From<Self>` impl (the
572/// blanket `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does
573/// not exist in `core`), so every closed-set typed enum that carries
574/// the owned-input axis but not the borrowed-input axis forces every
575/// borrowed-input call site through a `.copied()` /
576/// `<&'static str>::from(*strategy)` / `strategy.as_str()` detour whose
577/// type bounds have no compile-time link to the substrate primitive.
578/// [`RestartStrategy`] is the first M2 OTP-shape peer to converge onto
579/// this campaign (mirroring the first-mover role it played on the
580/// owned-input axis in 523157d); the remaining eleven substrate-wide
581/// closed-set fieldless typed enum peers (`RestartPolicy`, `WitShape`,
582/// `RateLimitUnit`, `PlacementStrategy`, `PathShapeViolation`,
583/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
584/// `FerriteRuntime`) are the future targets of this campaign.
585///
586/// Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
587/// [`From<Self> for &'static str`] emits the lowercase Portuguese
588/// [`Self::as_str`] diagnostic vocabulary while the reverse
589/// [`TryFrom<&str>`] parses the `PascalCase` [`Self::wire_name`]
590/// author-surface vocabulary, forcing the round-trip through an
591/// intermediate wire-vocab hop), [`RestartStrategy`]'s
592/// [`Self::as_str`] emit and [`Self::from_wire`] parse share the same
593/// `PascalCase` vocabulary by construction, so the borrowed-input
594/// forward axis and the reverse axis compose directly — the round-trip
595/// witness pin below locks this direct composition without the
596/// intermediate hop the peer axis requires.
597///
598/// Pinned load-bearing by
599/// [`tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
600/// (byte-parity pin against [`RestartStrategy::as_str`] across the
601/// four-arm emit-set via a borrowed input, plus a `const`-context
602/// materialization witness for the `&'static str` lifetime promise,
603/// plus a blanket `.into()` shape) and
604/// [`tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
605/// (cross-axis partition pin against the paired owned-input
606/// [`From<RestartStrategy> for &'static str`] impl, plus a
607/// `.iter().map(Into::into)` pipe witness over
608/// [`RestartStrategy::ALL`], plus a direct round-trip witness through
609/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
610/// Self` round-trip without the wire-vocab intermediate the peer
611/// [`crate::CaixaKind`] axis pair requires).
612impl From<&RestartStrategy> for &'static str {
613    fn from(strategy: &RestartStrategy) -> &'static str {
614        strategy.as_str()
615    }
616}
617
618/// Trait-idiomatic *owned-`String`* forward projection on the M2
619/// OTP-shape sibling-restart-strategy closed-set typed enum — the
620/// owned-heap-string companion to the paired `&'static str`-returning
621/// [`From<RestartStrategy> for &'static str`] / [`From<&RestartStrategy>
622/// for &'static str`] impls immediately above. Routes byte-for-byte
623/// through the substrate-primitive [`RestartStrategy::as_str`]
624/// `pub const fn` accessor (via [`str::to_owned`]) so every consumer
625/// that binds a [`RestartStrategy`] through the standard-library
626/// `.into()` / [`From<Self> for String`] (equivalently
627/// [`Into<String>`]) axis — a future
628/// `serde_json::Value::String(strategy.into())` structured-payload
629/// composer where the `Value::String` arm typing demands an owned
630/// [`String`] and the sibling [`&'static str`]-returning axis forces an
631/// explicit `.to_owned()` / `String::from` restatement at every call
632/// site, a future
633/// `HashMap::<String, RestartStrategy>::from_iter(RestartStrategy::ALL
634/// .iter().map(|s| (s.into(), *s)))` per-strategy lookup where the
635/// map's key type is owned [`String`] rather than [`&'static str`], a
636/// future `Cow::<'static, str>::Owned(strategy.into())` composer on
637/// the future M4 admission-webhook rejection body's owned-arm, the
638/// future wasm-operator's per-supervisor `serde_json::json!({
639/// "estrategia": strategy })` diagnostic emit where the JSON
640/// serializer's `Serialize` impl on [`String`] owns the emit-path — reaches
641/// the same four-arm lifted
642/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
643/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
644/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
645/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
646/// paired [`std::fmt::Display`], [`AsRef<str>`],
647/// [`RestartStrategy::as_str`], and the two `&'static str`-returning
648/// forward-projection impls already return.
649///
650/// Opens the trait-idiomatic *owned-`String`* forward-projection axis
651/// on the closed-set fieldless typed enum surface — first-mover on the
652/// M2 OTP-shape sibling-restart-strategy axis, mirror of the
653/// [`crate::supervisor::RestartStrategy`] first-mover position that
654/// opened the paired owned-`&'static str` axis (523157d) and the
655/// borrowed-input `&'static str` axis on
656/// [`crate::dep::DepList`] (64aa742). Rust's standard library does not
657/// carry a blanket `impl<T: AsRef<str>> From<T> for String` (nor an
658/// `impl<T: fmt::Display> From<T> for String`), so every closed-set
659/// typed enum that carries the paired `AsRef<str>` / `Display` /
660/// `From<Self> for &'static str` triple but not the owned-[`String`]
661/// axis forces every owned-string call site through a `.to_string()` /
662/// `.as_str().to_owned()` / `String::from(strategy.as_str())` detour
663/// whose type bounds have no compile-time link to the substrate
664/// primitive.
665///
666/// Deliberately routes through the human-readable
667/// [`RestartStrategy::as_str`] axis — for this enum the wire format
668/// (`PascalCase`, tatara-lisp author surface `:estrategia OneForOne`)
669/// and the diagnostic byte-string share the same vocabulary by
670/// construction (unlike the sibling [`crate::CaixaKind`] enum whose two
671/// axes diverge), so the owned-[`String`] projection lands
672/// byte-identically on both the wire vocabulary the paired
673/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
674/// [`RestartStrategy::as_str`] helper returns.
675///
676/// The remaining fourteen closed-set typed enums on the caixa
677/// substrate surface (`RestartPolicy`, `CaixaKind`, `CaixaDialeto`,
678/// `DepList`, `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
679/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
680/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets of
681/// this campaign — each carries the same paired `AsRef<str>` /
682/// `Display` / `From<Self> for &'static str` / `From<&Self> for
683/// &'static str` quadruple that this owned-[`String`] axis extends onto.
684///
685/// Pinned load-bearing by
686/// [`tests::restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
687/// (byte-parity pin against [`RestartStrategy::as_str`] across the
688/// four-arm emit-set, plus a blanket `.into::<String>()` shape witness)
689/// and
690/// [`tests::restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm`]
691/// (cross-axis partition pin against the paired owned-input
692/// [`From<RestartStrategy> for &'static str`] impl and the sibling
693/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
694/// plus a direct round-trip witness through [`TryFrom<&str>`] on the
695/// owned-[`String`]'s [`String::as_str`] borrow that closes the two-way
696/// `Self → String → Self` round-trip on the trait-idiomatic
697/// owned-[`String`] forward + reverse axis pair).
698impl From<RestartStrategy> for String {
699    fn from(strategy: RestartStrategy) -> String {
700        strategy.as_str().to_owned()
701    }
702}
703
704/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
705/// projection on the M2 OTP-shape sibling-restart-strategy closed-set
706/// typed enum — the fourth (and closing) corner of the
707/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
708/// projection family. Routes byte-for-byte through the
709/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
710/// accessor (via [`str::to_owned`]) so every consumer that holds a
711/// borrowed [`&RestartStrategy`] and needs an owned [`String`] — a
712/// future `serde_json::Value::String(String::from(&strategy))`
713/// structured-payload composer over a borrowed field, a future
714/// `Iterator::map` over `&[RestartStrategy]` that projects to owned
715/// keys through `.iter().map(String::from)`, a future
716/// `HashMap::<String, RestartStrategy>::from_iter` that keys off a
717/// borrowed-iteration axis where dereferencing the strategy would force
718/// an unnecessary `Copy` at every step, the future wasm-operator's
719/// per-supervisor `strategies.iter().map(String::from).collect()`
720/// diagnostic emit whose iteration axis is borrowed by construction —
721/// reaches the same four-arm lifted
722/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
723/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
724/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
725/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
726/// paired [`std::fmt::Display`], [`AsRef<str>`],
727/// [`RestartStrategy::as_str`], and the three other trait-idiomatic
728/// forward-projection impls
729/// ([`From<RestartStrategy> for &'static str`],
730/// [`From<&RestartStrategy> for &'static str`],
731/// [`From<RestartStrategy> for String`]) already return.
732///
733/// Opens the trait-idiomatic *borrowed-input, owned-`String` output*
734/// forward-projection axis on closed-set fieldless typed enums —
735/// first-mover on the 2×2 completion corner, mirror of the
736/// [`crate::supervisor::RestartStrategy`] first-mover position that
737/// opened the paired owned-input owned-`String` axis (7baa18a), the
738/// owned-input owned-`&'static str` axis (523157d), and the paired
739/// [`crate::dep::DepList`] first-mover position that opened the
740/// borrowed-input `&'static str` axis (64aa742). Rust's standard
741/// library does not carry a blanket `impl<T: AsRef<str>> From<&T> for
742/// String` (nor an `impl<T: fmt::Display> From<&T> for String`), so
743/// every closed-set typed enum that carries the paired `AsRef<str>` /
744/// `Display` / `From<Self> for &'static str` / `From<&Self> for
745/// &'static str` / `From<Self> for String` quintuple but not the
746/// borrowed-input owned-[`String`] axis forces every borrowed-input
747/// owned-string call site through a `strategy.as_str().to_owned()` /
748/// `String::from(*strategy)` (with a spurious `Copy`) /
749/// `strategy.to_string()` (through `Display`) detour whose type bounds
750/// have no compile-time link to the substrate primitive.
751///
752/// Deliberately routes through the human-readable
753/// [`RestartStrategy::as_str`] axis — for this enum the wire format
754/// (`PascalCase`, tatara-lisp author surface `:estrategia OneForOne`)
755/// and the diagnostic byte-string share the same vocabulary by
756/// construction (unlike the sibling [`crate::CaixaKind`] enum whose two
757/// axes diverge), so the borrowed-input owned-[`String`] projection
758/// lands byte-identically on both the wire vocabulary the paired
759/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
760/// [`RestartStrategy::as_str`] helper returns.
761///
762/// The remaining fourteen closed-set typed enums on the caixa
763/// substrate surface (`RestartPolicy`, `CaixaKind`, `CaixaDialeto`,
764/// `DepList`, `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
765/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
766/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets of
767/// this 2×2-completion campaign — each carries the same paired
768/// quintuple that this borrowed-input owned-[`String`] axis extends onto.
769///
770/// Pinned load-bearing by
771/// [`tests::restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
772/// (byte-parity pin against [`RestartStrategy::as_str`] across the
773/// four-arm emit-set through the borrowed-input surface) and
774/// [`tests::restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
775/// (cross-axis partition pin against the paired owned-input owned-
776/// [`String`] [`From<RestartStrategy> for String`] impl, the paired
777/// borrowed-input owned-[`&'static str`] [`From<&RestartStrategy> for
778/// &'static str`] impl, and the sibling [`ToString::to_string`] surface
779/// routed through [`std::fmt::Display`], plus a direct round-trip
780/// witness through [`TryFrom<&str>`] on the owned-[`String`]'s
781/// [`String::as_str`] borrow that closes the two-way
782/// `&Self → String → Self` round-trip on the trait-idiomatic
783/// borrowed-input owned-[`String`] forward + reverse axis pair).
784impl From<&RestartStrategy> for String {
785    fn from(strategy: &RestartStrategy) -> String {
786        strategy.as_str().to_owned()
787    }
788}
789
790/// Per-child restart policy.
791///
792/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
793#[derive(
794    Serialize,
795    Deserialize,
796    Debug,
797    Clone,
798    Copy,
799    PartialEq,
800    Eq,
801    Hash,
802    gen_platform::TypedDispatcher,
803    gen_platform::Discriminant,
804    gen_platform::IsVariant,
805    gen_platform::FromStrKind,
806)]
807pub enum RestartPolicy {
808    /// Always restart the child, regardless of how it died. Used for
809    /// long-running services that must always be up.
810    Permanent,
811    /// Never restart. Used for one-shot work whose completion is
812    /// itself the success signal (`oneShot` triggers map here).
813    Temporary,
814    /// Restart only when the child died *abnormally* (non-zero exit
815    /// or unhandled exception). A clean exit completes the child.
816    Transient,
817}
818
819impl Default for RestartPolicy {
820    fn default() -> Self {
821        // Route the [`Default for RestartPolicy`] impl's return arm through
822        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
823        // `pub const` rather than a raw `Self::Permanent` arm — one source
824        // of truth for the Erlang/OTP-canonical `permanent` worker-child
825        // default across the two production consumers that currently
826        // dispatch on it (this impl at the [`RestartPolicy::default`] call
827        // and the serde-side `#[serde(default)]` on
828        // [`ChildSpec::restart`] that resolves an author-omitted
829        // `:children :restart` slot through `RestartPolicy::default()`).
830        // Peer of the sibling per-`:supervisor` axis
831        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
832        // route (95ffacc) — the two impls now share one substrate-primitive
833        // lift discipline, so any future coherent rebrand of the OTP-shape
834        // supervisor+child default set migrates through typed constants in
835        // lockstep instead of splitting a lifted supervisor half against
836        // an open-coded child half. Pinned by
837        // `restart_policy_default_routes_through_lifted_default` +
838        // `child_spec_serde_default_restart_routes_through_lifted_default`
839        // in the tests module.
840        SUPERVISOR_CHILD_RESTART_DEFAULT
841    }
842}
843
844impl RestartPolicy {
845    /// Exhaustive iteration surface for every consumer that walks the
846    /// closed three-arm [`RestartPolicy`] discriminator set (the future
847    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
848    /// per-child admission-webhook rejection body naming the accepted-
849    /// `:restart` list, a future `feira supervisor --restart …` CLI
850    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
851    /// over the slice, the future `feira app graph` per-child restart
852    /// column, any future round-trip fuzz harness that sweeps every
853    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
854    /// theory
855    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
856    /// might reach for once the three canonical OTP restart policies
857    /// stop covering the substrate's discovered load-shape) extends
858    /// this slice as one edit and every consumer picks up the new entry
859    /// by construction; the compiler-checked exhaustiveness on the
860    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
861    /// is the build-time guarantee that no arm forgets to grow.
862    ///
863    /// Peer of the sibling closed-set typed enums'
864    /// [`RestartStrategy::ALL`] (4eec29c) /
865    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
866    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
867    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
868    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
869    /// surfaces — the sixth (and the third and final M2 OTP-shape)
870    /// closed-set typed enum on the caixa surface to converge onto the
871    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
872    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
873    /// sibling-restart-strategy axis; this closes the per-child
874    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
875    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
876
877    /// Canonical PascalCase discriminator scalar this variant serializes
878    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
879    /// arms return the paired
880    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
881    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
882    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
883    /// constants so every substrate consumer that dispatches on the
884    /// per-child restart-decision policy (the future wasm-operator's
885    /// per-child post-exit restart-decision branch, the future M4
886    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
887    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
888    /// reconciliation scheduler's per-child-policy fan-out) reads the
889    /// same byte-string the `Serialize` derive emits — the pin test in
890    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
891    /// asserts the two paths agree, peer of the M2
892    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
893    /// sibling-restart-strategy axis and the M3
894    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
895    /// per-Aplicacao distribution-strategy axis — the third of three
896    /// OTP-shaped closed-enum discriminator axes on the caixa typed
897    /// surface to converge onto the same three-path-convergence
898    /// (`Serialize` derive → `as_str` helper → lifted constant)
899    /// drift-detection posture.
900    #[must_use]
901    pub const fn as_str(self) -> &'static str {
902        match self {
903            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
904            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
905            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
906        }
907    }
908
909    /// Substrate-canonical reverse projection on the `:children :restart`
910    /// closed-set axis — parses the `PascalCase` discriminator scalar
911    /// back to the typed variant, or `None` when `s` is outside the
912    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
913    /// the same lifted
914    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
915    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
916    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
917    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
918    /// of the round-trip migrate through one caixa-core edit on any
919    /// future arm addition.
920    ///
921    /// Prior to this lift the substrate carried only the forward
922    /// `Self → &str` projection on the OTP per-child restart-policy
923    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
924    /// impl routed through it, the `Serialize` derive that emits the
925    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
926    /// plus the kebab-case dispatcher-catalog identity via
927    /// [`Self::discriminant`] — every non-serde consumer that wanted to
928    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
929    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
930    /// "Transient" => …, _ => … }` cascade that expressed no
931    /// compile-time link back to the typed variant's canonical lifted
932    /// constant. A future variant rename or per-arm serde-attribute
933    /// drift would silently split the wire byte-string one non-serde
934    /// consumer parsed from the one the emitter wrote, with the failure
935    /// surfacing at the operator's reconcile posture (a `:temporary`
936    /// `oneShot` child being restarted on clean exit, treating the
937    /// successful-completion signal as failure and re-running the
938    /// completion-terminal one-shot indefinitely; a `:transient` child
939    /// that clean-exited being restarted, masking the clean-completion
940    /// contract) far from the rebrand commit and with no field naming
941    /// the drift.
942    ///
943    /// Distinct axis from the [`std::str::FromStr`] impl the
944    /// [`gen_platform::FromStrKind`] derive already installs on this
945    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
946    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
947    /// `"transient"` — the inverse of [`Self::discriminant`]), while
948    /// this method inverts the `PascalCase` wire byte-string
949    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
950    /// catalog identity live in kebab-case (where every peer catalog
951    /// identifier already lives) without forcing a wire-format rename
952    /// on the tatara-lisp author surface (`:restart Permanent`,
953    /// `PascalCase`) — the same two-axis distinction the sibling
954    /// [`RestartStrategy::from_wire`] (4eec29c) /
955    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
956    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
957    /// carry on their peer closed-set typed-enum wire round-trips.
958    ///
959    /// Same closed-set-reverse-projection discipline the sibling
960    /// [`RestartStrategy::from_wire`] (4eec29c) /
961    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
962    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
963    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
964    /// carry on the peer wire-side `str → Self` axes — extended onto
965    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
966    /// sixth substrate-side closed-set typed enum (and the third and
967    /// final OTP-shape closed-enum discriminator axis) to converge on
968    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
969    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
970    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
971    /// derive already installs on the sibling kebab-case axis. Returns
972    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
973    /// shapes: the caller picks the diagnostic form appropriate for
974    /// its use site.
975    #[must_use]
976    pub fn from_wire(s: &str) -> Option<Self> {
977        match s {
978            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
979            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
980            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
981            _ => None,
982        }
983    }
984}
985
986/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
987/// pretty-printed byte-string every consumer that formats the policy as
988/// user-facing text lands on (the future wasm-operator's per-child
989/// post-exit restart-decision diagnostic line, the future `feira app
990/// graph` per-child restart column, the future M4
991/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
992/// admission-webhook rejection body) reaches for the same lifted
993/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
994/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
995/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
996/// wire-format `Serialize` derive already emits under
997/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
998/// [`RestartPolicy::as_str`] helper already returns.
999///
1000/// Pre-convergence the two paths structurally disagreed — the
1001/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1002/// route (now retired here) sent [`std::fmt::Display`] through the
1003/// gen-platform discriminant catalog string, which arrives kebab-case as
1004/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1005/// (whose variant names each collapse to their own lowercase form under
1006/// the kebab-case transform), while the wire format ran as `PascalCase`
1007/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1008/// serde derive. Every consumer that formatted the policy for a
1009/// diagnostic line, a graph column, or a rejection body under
1010/// `format!("{v}")` therefore landed under a different byte-string than
1011/// the wire format the operator's per-child-policy dispatch keyed off —
1012/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1013/// diagnostic quoting `"permanent"` while the wire scalar the operator
1014/// probed was `"Permanent"`) surfaced as a confused correlate at
1015/// operator-log time far from the two-declaration site.
1016///
1017/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1018/// path: every `format!("{v}")` call reaches the same lifted
1019/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1020/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1021/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1022/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1023/// byte-string per variant. A future variant rename or
1024/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1025/// exactly one place, structurally.
1026///
1027/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1028/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1029/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1030/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1031/// registration keys the catalog off the same kebab identity. The two
1032/// naming worlds now live on separate typed methods (`Display` /
1033/// `as_str` for the wire byte-string, `discriminant` for the catalog
1034/// identity) rather than sharing one `Display` route that structurally
1035/// disagrees with the wire format.
1036///
1037/// Pin tests
1038/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1039/// and
1040/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1041/// assert the three paths agree byte-for-byte on every variant, so a
1042/// future variant rename or per-arm serde attribute drift is a build
1043/// error visible at caixa-core test time, not a silent per-consumer
1044/// dispatch miss at apply / reconcile time.
1045///
1046/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1047/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1048/// and the sibling [`RestartStrategy`] `Display` impl on the
1049/// per-supervisor sibling-restart-strategy axis — same three-path-
1050/// convergence discipline, extended to close the third and final of
1051/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1052/// surface.
1053impl std::fmt::Display for RestartPolicy {
1054    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1055        f.write_str(self.as_str())
1056    }
1057}
1058
1059/// Substrate-canonical [`AsRef<str>`] projection on the M2
1060/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1061/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1062/// scalar accessor the paired [`std::fmt::Display`] impl and the
1063/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1064/// future consumer that binds a [`RestartPolicy`] through the
1065/// standard-library `impl AsRef<str>` bound (a future
1066/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1067/// composes the emitted `PascalCase` wire scalar into a
1068/// [`std::process::Command::arg`] shell-out of the future
1069/// wasm-operator's per-child admission gate, a per-child structured-
1070/// log recorder on the future `caixa-operator`'s hierarchical
1071/// reconciliation surface that accepts `impl AsRef<str>` at the
1072/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1073/// lookup keyed on the restart-policy wire byte through
1074/// `map.get::<str>(policy.as_ref())` on a future per-policy
1075/// dispatch table) reaches the paired
1076/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1077/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1078/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1079/// lifted-const through one substrate-primitive dispatch rather
1080/// than an open-coded `.as_str()` projection at every wire-up.
1081///
1082/// Peer of the sibling [`std::fmt::Display`] impl on the same
1083/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1084/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1085/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1086/// byte-string per instance by construction. A future variant rename
1087/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1088/// enum reaches every one of the three paths (plus the wire-format
1089/// `Serialize` derive that already routes through the same lifted
1090/// const) through exactly one caixa-core edit.
1091///
1092/// Same "route the trait impl through the substrate-primitive
1093/// accessor" discipline the sibling [`crate::CaixaVersion`]
1094/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1095/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1096/// the axis onto the paired per-child-restart-decision-policy
1097/// sibling on the same M2 `:supervisor` slot (the second M2
1098/// OTP-shape closed-set typed enum to converge onto the standard-
1099/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1100/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1101/// primitive so a caller who has one has both; before this lift,
1102/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1103/// [`AsRef<str>`] impl the convention names.
1104///
1105/// Pinned load-bearing by
1106/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1107/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1108/// three-arm closed set) and
1109/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1110/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1111/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1112/// arm) — any future silent detour that routes the impl through a
1113/// divergent projection (a per-arm inline `match self { … }`
1114/// re-inlining that opens a compile-time link to the un-lifted
1115/// arm-literal, a swap onto the kebab-case
1116/// [`gen_platform::Discriminant`] catalog identity that would
1117/// collide the wire axis with the dispatcher-catalog axis) trips at
1118/// caixa-core test time under `assert_eq!` rather than at a
1119/// downstream `impl AsRef<str>`-bound consumer's silent split.
1120impl AsRef<str> for RestartPolicy {
1121    fn as_ref(&self) -> &str {
1122        self.as_str()
1123    }
1124}
1125
1126/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1127/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1128/// byte-for-byte through the paired substrate-primitive
1129/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1130/// consumer that binds a `PascalCase` `:children :restart` wire
1131/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1132/// axis (a future [`caixa-feira`] `feira supervisor --restart
1133/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1134/// `let restart: RestartPolicy = s.try_into()?`, a future
1135/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1136/// `spec.children[*].restart: String` field through
1137/// `RestartPolicy::try_from(&s)?`, a generic
1138/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1139/// set typed enums) reaches the same three-arm accept-set the sibling
1140/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1141/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1142/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1143/// … }` cascade whose arm-set has no compile-time link back to the
1144/// substrate primitive.
1145///
1146/// Complements the pre-existing forward-projection triple
1147/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1148/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1149/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1150/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1151/// caller who can project *out to* a `&str` can also project *in from*
1152/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1153/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1154/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1155/// trigger under a `FromStr` impl and to avoid colliding with the
1156/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1157/// already installs on the paired *kebab-case dispatcher-catalog* axis
1158/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1159/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1160/// idiomatic reverse axis on the *`PascalCase` wire* half without
1161/// disturbing either the method-named `from_wire` shape every sibling
1162/// closed-set typed enum on the substrate already carries or the
1163/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1164/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1165///
1166/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1167/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1168/// caller picks the diagnostic form appropriate for its use site (a
1169/// future `feira supervisor --restart` arg-parse composes its own
1170/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1171/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1172/// wraps the `Err(())` outcome with the accepted-set enumeration for
1173/// operator diagnostics, a `Result::map_err` at the call site lifts the
1174/// unit-error to a per-verb error type). Same shape the peer
1175/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1176/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1177/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1178/// their peer closed-set typed enums' reverse projections.
1179///
1180/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1181/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1182/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1183/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1184/// might reach for once the three canonical OTP restart policies stop
1185/// covering the substrate's discovered load-shape) grows the trait-
1186/// idiomatic axis by construction — one caixa-core edit on
1187/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1188/// projection every existing consumer keys off and the trait-idiomatic
1189/// reverse projection this impl exposes, without a coordinated rewrite
1190/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1191///
1192/// Extends the substrate-wide closed-set-enum reverse-projection family
1193/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1194/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1195/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1196/// closed-enum discriminator axis on the caixa surface — the paired
1197/// per-child `:children :restart` closed set the future wasm-operator's
1198/// hierarchical reconciliation scheduler's per-child post-exit
1199/// restart-decision branch keys off end-to-end.
1200///
1201/// Pinned load-bearing by
1202/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1203/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1204/// three-arm accept-set),
1205/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1206/// (rejection witness against silent accept-set widening), and
1207/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1208/// (cross-axis partition pin locking the trait and method-named
1209/// projections onto one accept-set).
1210impl TryFrom<&str> for RestartPolicy {
1211    type Error = ();
1212
1213    fn try_from(s: &str) -> Result<Self, Self::Error> {
1214        Self::from_wire(s).ok_or(())
1215    }
1216}
1217
1218/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1219/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1220/// byte-for-byte through the paired substrate-primitive
1221/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1222/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1223/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1224/// &str` with `'static` lifetime, so the trait's return-type promise is
1225/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1226/// literal.
1227///
1228/// Every future consumer that specifically needs `&'static str` lifetime
1229/// bytes on the per-child restart-decision axis (a
1230/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1231/// arm's typing demands `&'static str`, a
1232/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1233/// on the future M4 admission-webhook rejection body where the
1234/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1235/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1236/// or error formatter that requires the `'static` bound) reaches the same
1237/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1238/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1239/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1240/// primitive dispatch rather than an open-coded per-arm literal cascade
1241/// whose arm-set has no compile-time link back to the substrate primitive.
1242///
1243/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1244/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1245/// the second (and second-of-two-in-M2) closed-set typed enum on the
1246/// caixa surface to converge onto the paired trait-idiomatic forward-
1247/// projection axis. With this lift the paired per-child
1248/// `:children :restart` closed-set typed enum carries the full sibling
1249/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1250/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1251/// lift) plus the round-trip witness through both the trait-idiomatic
1252/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1253/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1254/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1255/// (an OTP-`intrinsic` fourth arm the theory
1256/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1257/// might reach for once the three canonical OTP restart policies stop
1258/// covering the substrate's discovered load-shape) grows the trait-
1259/// idiomatic forward axis by construction: one caixa-core edit on
1260/// [`RestartPolicy::as_str`] extends every one of the five sibling
1261/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1262/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1263/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1264/// bytes) without a coordinated rewrite across every future
1265/// `Into<&'static str>`-bound consumer's arm-set.
1266///
1267/// Pinned load-bearing by
1268/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1269/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1270/// three-arm emit-set, plus a `const`-context materialization witness for
1271/// the `&'static str` lifetime promise) and
1272/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1273/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1274/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1275/// round-trip witness through the paired trait-idiomatic reverse-
1276/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1277/// `policy.into::<&'static str>()` output re-parses back through
1278/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1279/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1280impl From<RestartPolicy> for &'static str {
1281    fn from(policy: RestartPolicy) -> &'static str {
1282        policy.as_str()
1283    }
1284}
1285
1286/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
1287/// *borrowed* input onto the `&'static str` axis — the borrowed-input
1288/// companion to the paired owned-input [`From<RestartPolicy> for
1289/// &'static str`] impl immediately above. Routes byte-for-byte through
1290/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
1291/// fn` accessor so every consumer that binds a `&RestartPolicy`
1292/// through the standard-library `.into()` / [`From<&Self> for &'static
1293/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
1294/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
1295/// whose iterator over `&'static [RestartPolicy]` yields
1296/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
1297/// [`From<RestartPolicy>`] axis alone forces every call site through
1298/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
1299/// rather than the direct trait-idiomatic projection; a future generic
1300/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
1301/// that walks the `iter().map(Into::into)` shape verbatim across every
1302/// substrate-wide closed-set typed enum; the future wasm-operator's
1303/// per-child post-exit restart-decision diagnostic line that composes
1304/// the accepted-set enumeration from an iterated
1305/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1306/// per-arm `match p { … }` cascade; a future
1307/// `HashMap::<&'static str, RestartPolicy>::from_iter(
1308///     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
1309/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
1310/// cannot compose without this borrowed-input axis in place) reaches
1311/// the same three-arm lifted
1312/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1313/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1314/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1315/// paired owned-input [`From<RestartPolicy> for &'static str`], the
1316/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
1317/// [`RestartPolicy::as_str`] surfaces already return.
1318///
1319/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
1320/// forward-projection family opened on [`crate::dep::DepList`]
1321/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
1322/// [`crate::CaixaDialeto`] (807b0b5), and the paired
1323/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
1324/// (e941836). Rust's `From` trait does not auto-derive the
1325/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
1326/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
1327/// exist in `core`), so every closed-set typed enum that carries the
1328/// owned-input axis but not the borrowed-input axis forces every
1329/// borrowed-input call site through a `.copied()` /
1330/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
1331/// type bounds have no compile-time link to the substrate primitive.
1332/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
1333/// OTP-shape peer to converge onto this campaign — sibling of the
1334/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
1335/// with this lift both closed-set typed enums on the M2 `:supervisor`
1336/// slot now carry the full sibling quintet ([`std::fmt::Display`],
1337/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
1338/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
1339/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
1340/// forward-projection axis on the M2 OTP-shape slot as a unit.
1341///
1342/// Same three-path convergence discipline as the paired owned-input
1343/// impl (this borrowed-input axis, the paired owned-input
1344/// [`From<RestartPolicy> for &'static str`], and
1345/// [`RestartPolicy::as_str`] all route through the same lifted
1346/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
1347/// variant rename or per-arm serde-attribute drift reaches every one
1348/// of the six sibling forward-projection paths
1349/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1350/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
1351/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
1352/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
1353/// edit.
1354///
1355/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
1356/// parse share the same `PascalCase` vocabulary by construction, so
1357/// the borrowed-input forward axis and the reverse axis compose
1358/// directly — the round-trip witness pin below locks this direct
1359/// composition without the intermediate wire-vocab hop the peer
1360/// [`crate::CaixaKind`] axis pair requires.
1361///
1362/// Pinned load-bearing by
1363/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
1364/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1365/// three-arm emit-set via a borrowed input, plus a `const`-context
1366/// materialization witness for the `&'static str` lifetime promise,
1367/// plus a blanket `.into()` shape) and
1368/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
1369/// (cross-axis partition pin against the paired owned-input
1370/// [`From<RestartPolicy> for &'static str`] impl, plus a
1371/// `.iter().map(Into::into)` pipe witness over
1372/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1373/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
1374/// Self` round-trip without the wire-vocab intermediate the peer
1375/// [`crate::CaixaKind`] axis pair requires).
1376impl From<&RestartPolicy> for &'static str {
1377    fn from(policy: &RestartPolicy) -> &'static str {
1378        policy.as_str()
1379    }
1380}
1381
1382/// Trait-idiomatic *owned-`String`* forward projection on the second
1383/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
1384/// owned-heap-string companion to the paired `&'static str`-returning
1385/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
1386/// for &'static str`] impls immediately above. Routes byte-for-byte
1387/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
1388/// const fn` accessor (via [`str::to_owned`]) so every consumer that
1389/// binds a [`RestartPolicy`] through the standard-library `.into()` /
1390/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
1391/// future `serde_json::Value::String(policy.into())` structured-payload
1392/// composer where the `Value::String` arm typing demands an owned
1393/// [`String`] and the sibling [`&'static str`]-returning axis forces
1394/// an explicit `.to_owned()` / `String::from` restatement at every
1395/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
1396/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
1397/// lookup where the map's key type is owned [`String`] rather than
1398/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
1399/// composer on the future M4 admission-webhook rejection body's
1400/// owned-arm, the future wasm-operator's per-child post-exit
1401/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
1402/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
1403/// — reaches the same three-arm lifted
1404/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1405/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1406/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1407/// paired [`std::fmt::Display`], [`AsRef<str>`],
1408/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
1409/// forward-projection impls already return.
1410///
1411/// Extends the trait-idiomatic *owned-`String`* forward-projection
1412/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
1413/// the caixa surface — mirror of the first-mover
1414/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
1415/// axis on the sibling supervisor-level strategy enum. Rust's standard
1416/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
1417/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
1418/// every closed-set typed enum that carries the paired `AsRef<str>` /
1419/// `Display` / `From<Self> for &'static str` triple but not the
1420/// owned-[`String`] axis forces every owned-string call site through a
1421/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
1422/// detour whose type bounds have no compile-time link to the
1423/// substrate primitive.
1424///
1425/// Deliberately routes through the human-readable
1426/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1427/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1428/// the diagnostic byte-string share the same vocabulary by
1429/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1430/// two axes diverge), so the owned-[`String`] projection lands
1431/// byte-identically on both the wire vocabulary the paired
1432/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
1433/// [`RestartPolicy::as_str`] helper returns, and — because the paired
1434/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
1435/// axis parses the same `PascalCase` vocabulary — the direct two-way
1436/// `Self → String → Self` round-trip composes without the wire-vocab
1437/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
1438/// axis pair requires.
1439///
1440/// Pinned load-bearing by
1441/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
1442/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1443/// three-arm emit-set, plus a blanket `.into::<String>()` shape
1444/// witness) and
1445/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
1446/// (cross-axis partition pin against the paired owned-input
1447/// [`From<RestartPolicy> for &'static str`] impl and the sibling
1448/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
1449/// plus a `.iter().copied().map(String::from)` pipe witness over
1450/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1451/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
1452/// borrow that closes the two-way `Self → String → Self` round-trip
1453/// on the trait-idiomatic owned-[`String`] forward + reverse axis
1454/// pair).
1455impl From<RestartPolicy> for String {
1456    fn from(policy: RestartPolicy) -> String {
1457        policy.as_str().to_owned()
1458    }
1459}
1460
1461/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
1462/// projection on the second-of-two M2 OTP-shape closed-set typed enum
1463/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
1464/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1465/// projection family on this enum, mirror of the first-mover
1466/// [`From<&RestartStrategy> for String`] (579385f) that opened the
1467/// 2×2-completion corner on the sibling supervisor-level strategy
1468/// enum. Routes byte-for-byte through the substrate-primitive
1469/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
1470/// [`str::to_owned`]) so every consumer that holds a borrowed
1471/// [`&RestartPolicy`] and needs an owned [`String`] — a future
1472/// `serde_json::Value::String(String::from(&policy))` structured-payload
1473/// composer over a borrowed field, a future `Iterator::map` over
1474/// `&[RestartPolicy]` that projects to owned keys through
1475/// `.iter().map(String::from)`, a future `HashMap::<String,
1476/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
1477/// where dereferencing the policy would force an unnecessary `Copy` at
1478/// every step, the future wasm-operator's per-supervisor
1479/// `child_policies.iter().map(String::from).collect()` per-child post-
1480/// exit restart-decision diagnostic emit whose iteration axis is
1481/// borrowed by construction — reaches the same three-arm lifted
1482/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1483/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1484/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1485/// paired [`std::fmt::Display`], [`AsRef<str>`],
1486/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
1487/// forward-projection impls
1488/// ([`From<RestartPolicy> for &'static str`],
1489/// [`From<&RestartPolicy> for &'static str`],
1490/// [`From<RestartPolicy> for String`]) already return.
1491///
1492/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
1493/// owned-`String` output* forward-projection family opened on
1494/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
1495/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
1496/// both M2 OTP-shape sibling peers (the paired supervisor-level
1497/// sibling-restart-strategy axis and the per-child restart-decision-
1498/// policy axis), so the whole M2 OTP-shape axis pair now carries the
1499/// full four-corner family by construction. Rust's standard library
1500/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
1501/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
1502/// closed-set typed enum that carries the paired `AsRef<str>` /
1503/// `Display` / `From<Self> for &'static str` / `From<&Self> for
1504/// &'static str` / `From<Self> for String` quintuple but not the
1505/// borrowed-input owned-[`String`] axis forces every borrowed-input
1506/// owned-string call site through a `policy.as_str().to_owned()` /
1507/// `String::from(*policy)` (with a spurious `Copy`) /
1508/// `policy.to_string()` (through `Display`) detour whose type bounds
1509/// have no compile-time link to the substrate primitive.
1510///
1511/// Deliberately routes through the human-readable
1512/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1513/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1514/// the diagnostic byte-string share the same vocabulary by
1515/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1516/// two axes diverge), so the borrowed-input owned-[`String`]
1517/// projection lands byte-identically on both the wire vocabulary the
1518/// paired [`serde::Serialize`] derive emits and the diagnostic
1519/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
1520/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
1521/// reverse-projection axis parses the same `PascalCase` vocabulary —
1522/// the direct two-way `&Self → String → Self` round-trip composes
1523/// without the wire-vocab intermediate hop the peer
1524/// [`crate::CaixaKind`] axis pair requires.
1525///
1526/// The remaining thirteen closed-set typed enums on the caixa
1527/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
1528/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
1529/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
1530/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
1531/// of this 2×2-completion campaign — each carries the same paired
1532/// quintuple that this borrowed-input owned-[`String`] axis extends
1533/// onto.
1534///
1535/// Pinned load-bearing by
1536/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
1537/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1538/// three-arm emit-set through the borrowed-input surface) and
1539/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
1540/// (cross-axis partition pin against the paired owned-input owned-
1541/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
1542/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
1543/// &'static str`] impl, and the sibling [`ToString::to_string`]
1544/// surface routed through [`std::fmt::Display`], plus a direct round-
1545/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
1546/// [`String::as_str`] borrow that closes the two-way
1547/// `&Self → String → Self` round-trip on the trait-idiomatic
1548/// borrowed-input owned-[`String`] forward + reverse axis pair).
1549impl From<&RestartPolicy> for String {
1550    fn from(policy: &RestartPolicy) -> String {
1551        policy.as_str().to_owned()
1552    }
1553}
1554
1555// Fleet-wide dispatcher-catalog registrations for caixa's OTP
1556// supervisor surface — two more typed shadows over Erlang/OTP
1557// primitives the substrate now mechanically tracks (see
1558// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
1559// theory/TYPED-ABSORPTION.md for the absorption arc).
1560gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
1561gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
1562
1563/// One child entry in the supervisor's `:children` list.
1564///
1565/// Every child references another caixa by `:caixa <nome>` + version
1566/// constraint. The supervisor materializes one ComputeUnit per entry.
1567#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1568#[serde(rename_all = "camelCase")]
1569pub struct ChildSpec {
1570    /// The child caixa's `:nome`. Must resolve via the same dependency
1571    /// resolution path as `:deps` (caixa-resolver).
1572    pub caixa: String,
1573
1574    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
1575    /// [`crate::dep::Dep::versao`].
1576    pub versao: String,
1577
1578    /// Restart policy — an author-omitted slot degrades onto the
1579    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
1580    /// (`permanent`, the Erlang/OTP worker-child default) through the
1581    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
1582    /// to.
1583    #[serde(default)]
1584    pub restart: RestartPolicy,
1585}
1586
1587impl ChildSpec {
1588    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
1589    /// accessor every consumer that reads the OTP-shape supervised
1590    /// child's identity keys off — returns the author-declared
1591    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
1592    /// from the typed slot's own [`String`] storage.
1593    ///
1594    /// The `:children :caixa` slot carries the DNS-1123 label — the
1595    /// child caixa's `:nome` — that every emitted cluster artifact
1596    /// derives its `metadata.name` from verbatim: the rendered
1597    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
1598    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
1599    /// identity, and the per-child K8s Service `metadata.name` the
1600    /// future wasm-operator (M3) provisions for inter-child supervision-
1601    /// tree wiring. Every downstream consumer that fans on the child's
1602    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
1603    /// per-child DNS-1123 gate at
1604    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
1605    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
1606    /// [`validate_no_self_supervision`] cross-slot equality check
1607    /// against the parent's `:nome`, every `SupervisorError` variant
1608    /// carrying the offending child caixa verbatim for `feira lint`
1609    /// rendering, the future wasm-operator's hierarchical reconciliation
1610    /// scheduler's per-child ComputeUnit-name projection, the future M4
1611    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1612    /// admission webhook).
1613    ///
1614    /// Prior to this lift the `.caixa` byte-string was accessed inline
1615    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
1616    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
1617    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
1618    /// carriers' `child.caixa.clone()`, the dedup key's
1619    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
1620    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
1621    /// field-accesses that expressed no compile-time link back to the
1622    /// typed slot. A future extension of the `:children :caixa` axis to
1623    /// a richer author surface (a per-cluster alias table the operator
1624    /// pins through a future `:placement`-scoped slot on the supervisor
1625    /// tree, a namespace-qualified rewrite the M4 CR materializer
1626    /// applies per-CR, a per-child overlay from the future `:children
1627    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1628    /// acknowledges) would have had to be threaded through every
1629    /// open-coded copy in lockstep or one consumer would silently
1630    /// disagree with the peers on which caixa a given child resolves to
1631    /// — a child-set lookup that treated the name as `"cart-worker"`
1632    /// while the peer duplicate-detector treated it as
1633    /// `"tenant-a/cart-worker"` would silently split the
1634    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
1635    /// self-supervision detector's parent-equality check, a two-consumer
1636    /// split at the validator far from the source `caixa.lisp` with no
1637    /// field naming the identity-drift root cause. Lifting the resolution
1638    /// rule to a typed method on the substrate primitive means every
1639    /// downstream consumer of the Supervisor's per-`:children` identity
1640    /// surface reaches for exactly one typed dispatch — the resolver's
1641    /// accept-set migrates as a unit on any future axis addition.
1642    ///
1643    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
1644    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
1645    /// mesh-slot surface — same "one typed dispatch on the substrate
1646    /// primitive, thin projections at each consumer" discipline extended
1647    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
1648    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
1649    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
1650    /// accessor discipline for the shared substrate concept "another
1651    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
1652    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
1653    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
1654    /// slot family's typed-accessor discipline now spans both the
1655    /// upgrade axis (`:upgrade-from`) and the supervision axis
1656    /// (`:children`), matching the closed M3 mesh-slot accessor family's
1657    /// shape. Named `nome()` to match the tatara-lisp author-surface
1658    /// term the field's docstring already reaches for ("The child
1659    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
1660    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
1661    /// discipline the substrate already carries — the accessor's name
1662    /// maps directly onto the canonical caixa-identity vocabulary rather
1663    /// than shadowing the field's storage-side `caixa` label.
1664    #[must_use]
1665    pub const fn nome(&self) -> &str {
1666        self.caixa.as_str()
1667    }
1668
1669    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
1670    /// requirement scalar accessor every consumer that reads the OTP-shape
1671    /// supervised child's version pin keys off — returns the author-declared
1672    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
1673    /// the typed slot's own [`String`] storage.
1674    ///
1675    /// The `:children :versao` slot carries the Cargo-shaped semver
1676    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
1677    /// which release of the supervised child caixa the OTP-shape supervisor
1678    /// tree materializes against — the same requirement grammar the peer
1679    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
1680    /// shared [`crate::render::require_valid_versao_requirement`] cascade
1681    /// and the shared [`crate::version::parse_requirement`] parser. Every
1682    /// downstream consumer that fans on the child's version pin keys off
1683    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
1684    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
1685    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
1686    /// for `feira lint` rendering, every future per-cluster version-lock
1687    /// overlay the caixa-operator's hierarchical reconciliation scheduler
1688    /// pins through a future `:placement`-scoped supervisor-tree slot, the
1689    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1690    /// per-child version resolver, the future wasm-operator's per-child
1691    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
1692    ///
1693    /// Prior to this lift the `.versao` byte-string was accessed inline at
1694    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
1695    /// [`SupervisorSpec::validate`] requirement-gate call
1696    /// `require_valid_versao_requirement(&child.versao, …)` and the
1697    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
1698    /// `versao: child.versao.clone()` — two open-coded field-accesses that
1699    /// expressed no compile-time link back to the typed slot. A future
1700    /// extension of the `:children :versao` axis to a richer author surface
1701    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1702    /// flow, a lacre-projected concrete-version rewrite the operator
1703    /// materializes at CR-admission time, a future `:children :versao-lock`
1704    /// per-cluster override slot the wasm-operator's hierarchical
1705    /// reconciliation scheduler authors per-CR) would have had to be
1706    /// threaded through both open-coded copies in lockstep or one consumer
1707    /// would silently disagree with the peer on which release constraint a
1708    /// given child resolves to — the requirement-gate call reading
1709    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
1710    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
1711    /// the actual gate rejection input, a two-consumer split at the
1712    /// validator far from the source `caixa.lisp` with no field naming the
1713    /// version-pin drift root cause. Lifting the resolution rule to a typed
1714    /// method on the substrate primitive means every downstream
1715    /// requirement-facing consumer of the Supervisor's per-`:children`
1716    /// version-pin surface reaches for exactly one typed dispatch — the
1717    /// resolver's accept-set migrates as a unit on any future axis addition.
1718    ///
1719    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
1720    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
1721    /// surface — same "one typed dispatch on the substrate primitive, thin
1722    /// projections at each consumer" discipline extended onto the M2
1723    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
1724    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
1725    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
1726    /// one accessor discipline for the shared substrate concept "another
1727    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
1728    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
1729    /// `:nome` scalar accessor — the pair
1730    /// `(nome(), versao_requirement())` jointly projects the
1731    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
1732    /// that fans on per-child identity + version pin keys off, closing the
1733    /// last unlifted per-`:children` `String`-carry axis so every downstream
1734    /// per-`:children` reader now routes through a typed dispatch on the
1735    /// substrate primitive. Named `versao_requirement()` rather than
1736    /// `versao()` because the field's storage-side `.versao` label is
1737    /// already the author-surface term (`:versao`); the accessor's name
1738    /// carries the semantic role — the semver *requirement* string the
1739    /// shared [`crate::version::parse_requirement`] entry-point consumes —
1740    /// so a raw field access and a typed dispatch read differently at every
1741    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
1742    /// naming discipline verbatim.
1743    #[must_use]
1744    pub const fn versao_requirement(&self) -> &str {
1745        self.versao.as_str()
1746    }
1747
1748    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
1749    /// per-child post-exit restart-decision policy scalar accessor every
1750    /// consumer that dispatches on the supervised child's post-exit
1751    /// reconcile posture keys off — returns the author-declared
1752    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
1753    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
1754    /// storage.
1755    ///
1756    /// The `:children :restart` slot carries the closed-set OTP-shaped
1757    /// per-child restart-decision policy discriminator
1758    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
1759    /// worker-child default; [`RestartPolicy::Transient`] — restart only
1760    /// on abnormal exit, the OTP `transient` clean-completion-aware
1761    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
1762    /// `temporary` one-shot default) that every downstream consumer of
1763    /// the Supervisor's per-child post-exit reconcile branch keys off.
1764    /// Every future downstream consumer that fans on the per-child
1765    /// restart-decision keys off this scalar (the future `feira app
1766    /// graph` per-child restart column, the future wasm-operator's
1767    /// per-child post-exit restart-decision branch, the future M4
1768    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1769    /// admission webhook, the `caixa-operator`'s hierarchical
1770    /// reconciliation scheduler's per-child post-exit reconcile branch,
1771    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
1772    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1773    /// pin threads through).
1774    ///
1775    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
1776    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
1777    /// scalar accessor and the M3 mesh-slot
1778    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
1779    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
1780    /// — same "one typed dispatch on the substrate primitive,
1781    /// `Copy`-projected closed-set enum-arm discriminator that partitions
1782    /// the downstream renderer's per-arm fan-out" discipline extended
1783    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
1784    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
1785    /// [`ChildSpec`] type — companion to the sibling per-`:children`
1786    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
1787    /// and the per-`:children` [`ChildSpec::versao_requirement`]
1788    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
1789    /// on the sibling `String`-carry axes. The triple
1790    /// `(nome(), versao_requirement(), restart())` jointly projects the
1791    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
1792    /// tree consumer that fans on per-child identity + version pin +
1793    /// restart-decision keys off, closing the last unlifted per-`:children`
1794    /// axis so every downstream per-`:children` reader now routes through
1795    /// a typed dispatch on the substrate primitive. Named `restart()` to
1796    /// match the storage field's name and the author-surface
1797    /// `:children :restart` slot term verbatim; the accessor's identity
1798    /// name maps onto the canonical OTP-shape per-child restart-decision-
1799    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
1800    /// carries.
1801    ///
1802    /// Declared `pub const fn` to close the last non-`const`
1803    /// `Copy`-return raw-field-getter posture on the M2
1804    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
1805    /// of the sibling M2 per-`:supervisor`
1806    /// [`SupervisorSpec::estrategia`] (converted in this commit)
1807    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
1808    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1809    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
1810    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
1811    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
1812    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
1813    /// downstream substrate-side `const`-context consumer of the
1814    /// per-`:children` restart-decision-policy scalar (a future
1815    /// module-scope `const _:() = assert!(matches!(child.restart(),
1816    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
1817    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1818    /// admission-webhook `const fn` per-child restart-decision floor
1819    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
1820    /// composer over the substrate primitive that fans on the per-child
1821    /// restart-decision policy at compile time) now reaches through the
1822    /// same typed dispatch on the substrate primitive at const-eval
1823    /// time as at runtime. A future non-`Copy`-return promotion of the
1824    /// scalar (an `Option<RestartPolicy>`-shape migration on the
1825    /// per-child restart-decision axis once heterogeneous per-cluster
1826    /// restart-policy overlays land, a per-tenant restart-policy-alias
1827    /// table the M4 CR materializer resolves per-CR) that would drop
1828    /// the `const` qualifier fails the fail-before-pass-after pin
1829    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
1830    /// build time rather than surfacing as a downstream consumer
1831    /// regression.
1832    #[must_use]
1833    pub const fn restart(&self) -> RestartPolicy {
1834        self.restart
1835    }
1836}
1837
1838/// Supervisor-typed slots that live alongside the standard Caixa
1839/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
1840/// the manifest stays a single typed form; this struct exists for
1841/// validation + conversion.
1842#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1843#[serde(rename_all = "camelCase")]
1844pub struct SupervisorSpec {
1845    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
1846    #[serde(default)]
1847    pub estrategia: RestartStrategy,
1848
1849    /// Max restarts within [`Self::restart_window`] before the
1850    /// supervisor itself terminates (and its parent supervisor decides
1851    /// what to do). Default 5.
1852    #[serde(default = "default_max_restarts")]
1853    pub max_restarts: u32,
1854
1855    /// Sliding window for `max_restarts`. Authored as a duration
1856    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
1857    /// is rejected by [`Self::validate`] — Erlang/OTP's
1858    /// `MaxIntensity / Period` invariant requires a positive window
1859    /// (a zero-period supervisor either trips on the first failure or
1860    /// never trips, depending on operator interpretation, neither of
1861    /// which is the author's intent). Omit the slot to express "no
1862    /// reset"; carry a positive duration to express the sliding window.
1863    #[serde(
1864        default,
1865        skip_serializing_if = "Option::is_none",
1866        with = "duration_codec"
1867    )]
1868    pub restart_window: Option<Duration>,
1869
1870    /// Static children. Empty for `SimpleOneForOne` (children added
1871    /// dynamically); required for the other three strategies.
1872    #[serde(default)]
1873    pub children: Vec<ChildSpec>,
1874}
1875
1876const fn default_max_restarts() -> u32 {
1877    // Route the private serde-`#[serde(default = "…")]` helper through
1878    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
1879    // `pub const` rather than the raw `5` literal — one source of truth
1880    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
1881    // default across the two production consumers that currently
1882    // dispatch on it (this helper via `#[serde(default = "…")]` on
1883    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
1884    // impl at line 962). Pinned by
1885    // `default_max_restarts_helper_routes_through_lifted_default` +
1886    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
1887    // in the tests module; peer of the sibling caixa-core
1888    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
1889    // that now routes its author-omitted `:max-restarts` arm through
1890    // the same lifted constant.
1891    SUPERVISOR_MAX_RESTARTS_DEFAULT
1892}
1893
1894/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
1895/// count default for the `:supervisor :max-restarts` axis — the
1896/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
1897/// Erlang's worker-supervisor default, extracted as a typed `pub const`
1898/// so every substrate-side consumer that resolves "what
1899/// [`SupervisorSpec::max_restarts`] value does an author-omitted
1900/// `:max-restarts` slot degrade onto?" reaches for exactly one
1901/// substrate-primitive `u32`.
1902///
1903/// The `:max-restarts` default axis has two production consumers on the
1904/// substrate side today (both prior to this lift folded onto raw `5`
1905/// literals with no compile-time link back to a shared truth): the
1906/// serde-`#[serde(default = "default_max_restarts")]` helper on
1907/// [`SupervisorSpec::max_restarts`] that every author-omitted
1908/// `:supervisor :max-restarts` slot lands in past the derive-macro's
1909/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
1910/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
1911/// the composed [`SupervisorSpec`] altitude reaches through
1912/// (`feira app graph`, the future wasm-operator's per-supervisor
1913/// restart-intensity counter, the future M4
1914/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1915/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
1916/// A pair of open-coded `5`s across two files that expressed no
1917/// compile-time link back to the shared OTP-canonical default — a
1918/// future rebrand of the default (a tightening to Elixir's
1919/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
1920/// the operator pins through a future
1921/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
1922/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1923/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
1924/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
1925/// per-child-cohort roadmap lands) would have had to be threaded
1926/// through both open-coded copies in lockstep or the wire-format
1927/// author-omitted arm and the view-construction author-omitted arm
1928/// would silently disagree on which restart-budget an omitted
1929/// `:max-restarts` resolves to (an author writing `:supervisor
1930/// (:max-restarts ())` would round-trip through serde with the new
1931/// default while `supervisor_view` silently continued to compose the
1932/// stale `5`, or vice versa), a two-consumer split at the composition
1933/// boundary far from the source `caixa.lisp` with no field naming the
1934/// default-drift root cause. Lifting the resolution rule to a typed
1935/// `pub const` on the substrate primitive means every downstream
1936/// consumer of the per-Supervisor default-restart-budget-count surface
1937/// reaches for exactly one substrate-primitive `u32` — the resolver's
1938/// accepted value migrates as a unit on any future axis change.
1939///
1940/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1941/// worker-supervisor default (the closest canonical OTP-shape
1942/// production reference the substrate carries, matching the sibling
1943/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
1944/// this constant with on the paired sliding-window axis). Two orders of
1945/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
1946/// (the upper bracket on the same axis, sibling of this lower default;
1947/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
1948/// axis and now share one accessor discipline on the substrate) and
1949/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
1950/// restart floor — the "one restart, then escalate" default is
1951/// deliberately loose enough to absorb a short burst of transient
1952/// child failures without escalating past the supervisor's parent
1953/// while remaining tight enough to trip the `MaxIntensity / Period`
1954/// ratio's escalation on a genuinely-stuck child within the sibling
1955/// `60s` sliding window.
1956///
1957/// Lifted as a typed `pub const` so the bound has exactly one source
1958/// of truth — the serde-side wire-format author-omitted arm at
1959/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
1960/// struct-literal default field, and the caixa-core
1961/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
1962/// arm all read from one place. Same shape every other typed default
1963/// in this crate carries (the sibling
1964/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
1965/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
1966/// sibling `:restart-window` axis, and the peer
1967/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1968/// per-renderer defaults on the caixa-flux / caixa-helm rendering
1969/// axes).
1970pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
1971
1972/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
1973/// validated [`SupervisorSpec::max_restarts`] past
1974/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
1975///
1976/// The typed field is `u32` (the zero-floor arm
1977/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
1978/// so a programmatic struct literal
1979/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
1980/// author-surface form (`:max-restarts 4294967295` or any
1981/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
1982/// cleanly through serde — a structurally unbounded `u32` ceiling. The
1983/// runtime substrate consuming the value (Erlang/OTP's
1984/// `MaxIntensity / Period` ratio, the future wasm-operator's
1985/// per-supervisor restart-intensity counter, the M4
1986/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
1987/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
1988/// escalation threshold is structurally so high that no realistic
1989/// restarts-per-`:restart-window` traffic shape can reach it, the
1990/// supervisor never escalates to its parent, and a bad child can loop
1991/// inside the window indefinitely with the parent supervisor structurally
1992/// never receiving the "this subtree has exceeded its restart budget"
1993/// signal the typed slot is meant to express — the canonical
1994/// "supervisor intensity declared, no escalation" footgun, exactly the
1995/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
1996/// on the `:politicas :circuit-breaker :max-failures` axis (both are
1997/// "trip the next-higher protection layer after N events in a rolling
1998/// window" counters with identical degenerate-at-the-high-end shape).
1999///
2000/// The `1000` ceiling matches the sibling
2001/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
2002/// peer — same "events-per-window trip threshold" semantics, same `u32`
2003/// type, same no-op-at-the-high-end failure mode) so the M4
2004/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
2005/// and the future wasm-operator's per-supervisor restart-intensity
2006/// counter reach for either field knowing the value is in `1..=1000`
2007/// without re-validating at the reconciler layer. The cap sits two
2008/// orders of magnitude above every documented Erlang/OTP production
2009/// playbook recommendation (Learn You Some Erlang's
2010/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
2011/// `max_restarts: 3` default, OTP's `supervisor` callback module
2012/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
2013/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
2014/// default) and below the clearly-pathological "effectively no
2015/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
2016/// author can plausibly want at hyperscale (a long-running supervisor
2017/// over a very-flaky pool tolerating thousands of transient restarts
2018/// before escalating), but a hard wall above which the typed policy is
2019/// structurally a no-op carried verbatim on every emitted child-restart
2020/// reconciliation contract.
2021///
2022/// Lifted as a typed `pub const` so the bound has exactly one source of
2023/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2024/// materializer's admission webhook and the wasm-operator-side
2025/// per-supervisor restart-intensity reconciler read from one place. Same
2026/// shape every other typed upper bound in this crate carries
2027/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2028/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2029/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2030/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2031/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2032/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2033pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
2034
2035/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
2036/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
2037/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2038/// (inclusive on both ends, integer-millisecond magnitudes by the
2039/// canonical-form gate immediately preceding).
2040///
2041/// The typed field is `Option<Duration>` (the zero-floor arm
2042/// [`SupervisorError::RestartWindowZero`] already rejects
2043/// `Some(Duration::ZERO)`, and the canonical-form arm
2044/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
2045/// sub-millisecond residue), so a programmatic struct literal
2046/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
2047/// .. }` — 24h) and the equivalent author-surface form
2048/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
2049/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
2050/// cleanly through serde — a structurally unbounded `Duration` ceiling.
2051/// A `:restart-window` value far above the documented Erlang/OTP
2052/// `MaxIntensity / Period` production-playbook band (Learn You Some
2053/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
2054/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
2055/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
2056/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
2057/// degenerates the supervisor's restart-intensity counter into a
2058/// lifetime counter: the rolling failure-counting window is structurally
2059/// so long that transient restarts are never forgotten, so the
2060/// `MaxIntensity / Period` ratio degenerates from "trip the parent
2061/// supervisor when the child has exceeded its restart budget *within
2062/// the recent window*" to "trip the parent when the child has exceeded
2063/// its restart budget *over its lifetime*" — every transient restart
2064/// counts against the budget forever, the supervisor's reset semantic
2065/// never reaches the child, and the typed `:restart-window` slot
2066/// becomes a no-op rolling window carried on every emitted hierarchical
2067/// reconciliation contract. The canonical
2068/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
2069/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
2070/// `:politicas :circuit-breaker :window` axis with identical shape (both
2071/// are "rolling failure-counting window with a per-`Period` reset" Duration
2072/// axes whose lifetime-counter degenerate at the high end is the same
2073/// "the reset semantic never fires" CSE invariant violation).
2074///
2075/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
2076/// the shared duration codec emits (`"<n>h"` for any integer-hour
2077/// magnitude) — every value in the canonical authoring form's
2078/// `<integer><unit>` grammar at or below this cap renders to a clean
2079/// canonical string — and matches the three sibling typed-`Duration`
2080/// caps already lifted to this surface
2081/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2082/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
2083/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
2084/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
2085/// per-supervisor `:supervisor :restart-window` — now share a single
2086/// uniform top edge at the codec's largest emitted unit so the next
2087/// typed-slot wiring (the future wasm-operator's per-supervisor
2088/// `MaxIntensity / Period` reconciler, the M4
2089/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2090/// webhook, the `caixa-operator`'s hierarchical reconciliation
2091/// scheduler) reaches for any of the four knowing the value is in
2092/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
2093/// two orders of magnitude above every documented Erlang/OTP / Elixir /
2094/// Riak Core / RabbitMQ production-playbook recommendation band
2095/// (`5s..=300s`) and below the clearly-pathological "rolling window
2096/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
2097/// a value the author can plausibly want for a very-low-traffic
2098/// long-tail failure-restart window over a hyperscale-flaky child pool,
2099/// but a hard wall above which the rolling-window contract is
2100/// structurally a lifetime-counter contract.
2101///
2102/// Lifted as a typed `pub const` so the bound has exactly one source
2103/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2104/// materializer's admission webhook, the wasm-operator-side
2105/// per-supervisor `MaxIntensity / Period` reconciler, and the
2106/// `caixa-operator`'s hierarchical reconciliation scheduler all read
2107/// from one place. Same shape every other typed upper bound in this
2108/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
2109/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2110/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2111/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2112/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2113/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2114/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
2115/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2116/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2117pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
2118
2119/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
2120/// default for the `:supervisor :restart-window` axis — the canonical
2121/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
2122/// worker-supervisor default, extracted as a typed `pub const` so every
2123/// substrate-side consumer that resolves "what
2124/// [`SupervisorSpec::restart_window`] value does an author-omitted
2125/// `:restart-window` slot degrade onto?" reaches for exactly one
2126/// substrate-primitive [`Duration`].
2127///
2128/// The `:restart-window` default axis has one production consumer on the
2129/// substrate side today: the [`Default for SupervisorSpec`] impl's
2130/// struct-literal `restart_window` field, which prior to this lift folded
2131/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
2132/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
2133/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
2134/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
2135/// *not* fall back to this default on the sibling `:restart-window` axis
2136/// — an author-omitted `:supervisor :restart-window` composes to
2137/// `restart_window: None` (the shared codec's soft-swallow shape),
2138/// keeping author-declared intent ("no reset — never escalate on rolling
2139/// window") distinct from the [`Default for SupervisorSpec`] "canonical
2140/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
2141/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
2142/// default was split across two files with no compile-time link between
2143/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
2144/// `MaxIntensity` half at the substrate primitive while the `Period`
2145/// half rode as an open-coded literal at the composition site, so a
2146/// future coherent rebrand of the paired canonical (a tightening to
2147/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
2148/// per-cluster overlay the operator pins through a future
2149/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
2150/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2151/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
2152/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
2153/// roadmap lands) would have had to migrate the `MaxIntensity` half
2154/// through the lifted constant and the `Period` half through a raw
2155/// literal in lockstep or the two halves of the same OTP-canonical
2156/// default would silently drift out of pairing. Lifting the resolution
2157/// rule to a typed `pub const` on the substrate primitive means the
2158/// paired OTP-canonical default migrates as one unit on any future
2159/// axis change.
2160///
2161/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2162/// worker-supervisor default (the closest canonical OTP-shape
2163/// production reference the substrate carries, matching the paired
2164/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
2165/// constant is the `Period` denominator of on the same
2166/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
2167/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
2168/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
2169/// this lower default; both are typed [`Duration`] const bounds on the
2170/// `:supervisor :restart-window` axis and now share one accessor
2171/// discipline on the substrate) and above the OTP-`supervisor`
2172/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
2173/// rolling window" default is deliberately loose enough to absorb a
2174/// short burst of transient child failures without escalating past the
2175/// supervisor's parent while remaining tight enough for the paired
2176/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
2177/// stuck child within a human-scale observation window.
2178///
2179/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2180/// exactly one source of truth on each half — the sibling
2181/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
2182/// `Period` `60s` half now share the same substrate-primitive lift
2183/// discipline. Same shape every other typed default in this crate
2184/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
2185/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
2186/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
2187/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
2188/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
2189/// caixa-flux / caixa-helm rendering axes).
2190pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
2191
2192/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
2193/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
2194/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
2195/// worker-supervisor default, extracted as a typed `pub const` so every
2196/// substrate-side consumer that resolves "what
2197/// [`SupervisorSpec::estrategia`] variant does an author-omitted
2198/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
2199/// primitive [`RestartStrategy`].
2200///
2201/// The `:estrategia` default axis has three production consumers on the
2202/// substrate side today: the [`Default for RestartStrategy`] impl's
2203/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
2204/// `estrategia` field, and the
2205/// [`crate::manifest::Caixa::supervisor_view`] fold's
2206/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
2207/// collapse arm — three entry points onto the same OTP-canonical
2208/// `one_for_one` value that prior to this lift folded onto a raw
2209/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
2210/// implicit `RestartStrategy::default()` routes at the sibling consumers,
2211/// with no compile-time link back to the paired
2212/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
2213/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
2214/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
2215/// triple was split across three altitudes with no compile-time link
2216/// between the halves: the `MaxIntensity` half rode through the lifted
2217/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
2218/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2219/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
2220/// discriminator at the [`Default for RestartStrategy`] impl, so a future
2221/// coherent rebrand of the triple (Elixir's `{:one_for_one,
2222/// max_restarts: 3, max_seconds: 5}` — same strategy, different
2223/// intensity/period; an OTP `rest_for_one` widening once the substrate
2224/// discovers startup-order-coupled child cohorts as the more common
2225/// worker-supervisor default; a per-cluster overlay the operator pins
2226/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
2227/// §III.2 supervision-canary roadmap acknowledges) would have had to
2228/// migrate the `MaxIntensity` + `Period` halves through the lifted
2229/// constants and the `one_for_one` half through an open-coded arm in
2230/// lockstep or the three halves of the same OTP-canonical default would
2231/// silently drift out of pairing. Lifting the resolution rule to a typed
2232/// `pub const` on the substrate primitive means the paired OTP-canonical
2233/// worker-supervisor default migrates as one unit on any future axis
2234/// change.
2235///
2236/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
2237/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
2238/// closest canonical OTP-shape production reference the substrate
2239/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
2240/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2241/// `60s` `Period` half). The `one_for_one` strategy — restart only the
2242/// failed child, leaving siblings untouched — is the default for tree-of-
2243/// independent-workers use cases the substrate's [`RestartStrategy`]
2244/// discriminator's own docstring already carries as the default arm; it
2245/// composes with the `{5, 60}` restart-intensity ratio to name the same
2246/// substrate-canonical "canonical worker-supervisor" shape the paired
2247/// halves close on their respective axes.
2248///
2249/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2250/// exactly one source of truth on each of its three halves — the sibling
2251/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
2252/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
2253/// this `one_for_one` strategy half now share the same substrate-
2254/// primitive lift discipline. Same shape every other typed default in
2255/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
2256/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
2257/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
2258/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
2259/// upper caps on the paired sibling axes, and the peer
2260/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2261/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
2262pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
2263
2264/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
2265/// default for the `:children :restart` axis — the OTP `permanent`
2266/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
2267/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
2268/// `pub const` so every substrate-side consumer that resolves "what
2269/// [`ChildSpec::restart`] variant does an author-omitted `:children
2270/// :restart` slot degrade onto?" reaches for exactly one substrate-
2271/// primitive [`RestartPolicy`].
2272///
2273/// Completes the OTP-shape supervisor-tree default set at the substrate
2274/// primitive. The per-`:supervisor` axis already carries all three of its
2275/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2276/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
2277/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2278/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
2279/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
2280/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
2281/// the M2 `:supervisor` slot family. The split mattered because the two
2282/// axes resolve *together* on every author-omitted supervisor: a
2283/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
2284/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
2285/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
2286/// `permanent` through an open-coded enum arm, so a future coherent
2287/// rebrand of the OTP-shape default set (an Elixir-shaped
2288/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
2289/// per-cluster overlay the operator pins through the MESH-COMPOSITION
2290/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
2291/// once the substrate discovers clean-completion-aware children as the
2292/// more common child shape) would have had to migrate three halves
2293/// through typed constants and the fourth through a raw enum arm in
2294/// lockstep or the supervisor-level and child-level defaults would
2295/// silently drift apart.
2296///
2297/// The `:children :restart` default axis has two production consumers on
2298/// the substrate side today: the [`Default for RestartPolicy`] impl's
2299/// return arm, and the serde-side `#[serde(default)]` on
2300/// [`ChildSpec::restart`] that resolves an author-omitted `:children
2301/// :restart` slot through that same impl. Both now key off this one
2302/// substrate primitive, so the future wasm-operator's per-child post-exit
2303/// restart-decision branch, the future M4
2304/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2305/// admission webhook, and the `caixa-operator`'s hierarchical
2306/// reconciliation scheduler's per-child fan-out all reach for one typed
2307/// identifier when they resolve an omitted per-child restart posture.
2308///
2309/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
2310/// worker-child restart type — always restart the child regardless of how
2311/// it died, the canonical posture for long-running services that must
2312/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2313/// `one_for_one` tree-of-independent-workers strategy this constant pairs
2314/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
2315/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
2316/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
2317/// [`RestartPolicy::Temporary`] — never restart) express deliberate
2318/// one-shot / clean-completion-aware postures an author declares
2319/// explicitly, never a posture an omitted slot should silently assume.
2320pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
2321
2322/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
2323/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
2324/// `pub const fn` constructor rather than a struct-literal cascade over
2325/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
2326/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2327/// lifted consts — one source of truth for the Erlang/OTP-canonical
2328/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
2329/// paths every downstream consumer already reaches through (the
2330/// hand-authored-until-now [`Default::default`] the
2331/// `..SupervisorSpec::default()` struct-update-syntax on every
2332/// one-axis-under-test fixture in this crate's test module rests on,
2333/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
2334/// every `const`-context consumer reaches through).
2335///
2336/// Extends the [`Default`]-through-const-ctor fold discipline the
2337/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
2338/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
2339/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
2340/// and [`crate::BehaviorSpec`]
2341/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
2342/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
2343/// typed-slot spec family — extended here onto the M2 supervisor-slot
2344/// [`SupervisorSpec`] whose canonical baseline is not "everything
2345/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
2346/// supervisor triple. The `empty()` peer's naming did not fit
2347/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
2348/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
2349/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
2350/// the sibling `Option`-only slots fold to), so this peer is named
2351/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
2352/// existing per-arm pin tests
2353/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
2354/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
2355/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2356/// already reach for. Pinned load-bearing by
2357/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
2358/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
2359/// [`PartialEq`], sharpening the sibling
2360/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
2361/// pins from a per-field lift into a whole-struct one-source-of-truth
2362/// pin — the derived-until-now [`Default::default`] and the
2363/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
2364/// construction, not by coincidence).
2365impl Default for SupervisorSpec {
2366    #[inline]
2367    fn default() -> Self {
2368        Self::otp_canonical()
2369    }
2370}
2371
2372impl SupervisorSpec {
2373    /// `const`-context peer of the [`Default for SupervisorSpec`]
2374    /// impl (which routes through this constructor) — returns the
2375    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
2376    /// baseline this crate reaches for in every fixture-builder
2377    /// `..SupervisorSpec::default()` struct-update expression and
2378    /// every downstream `SupervisorSpec::default()` seed.
2379    ///
2380    /// Each field routes through the same substrate-canonical
2381    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
2382    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
2383    /// per-arm pin tests
2384    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
2385    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
2386    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2387    /// already assert, so a future coherent rebrand of the OTP-canonical
2388    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
2389    /// cluster overlay via a future `:restart-window-overrides` slot, a
2390    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
2391    /// absorption roadmap acknowledges) migrates through three typed
2392    /// constants in lockstep, and the paired [`Default`] impl inherits
2393    /// every future extension by construction.
2394    ///
2395    /// `pub const fn` rather than the derived-style `Default::default`
2396    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
2397    /// [`Default::default`] is not `const` on stable Rust, and
2398    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
2399    /// every consumer through a [`Clone::clone`]. The `pub const fn`
2400    /// discipline lets `const`-context callers construct the OTP-
2401    /// canonical baseline at compile time without runtime dispatch on
2402    /// the derived [`Default::default`], the same posture the sibling
2403    /// [`crate::LimitsSpec::empty`] (9739971) /
2404    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
2405    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
2406    /// spec `pub const fn` constructors carry on the sibling
2407    /// "everything `None`" baseline axis.
2408    ///
2409    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
2410    /// of the derived-style [`Default`]" family — sibling of the
2411    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
2412    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
2413    /// baseline" trio, extended here onto the M2 supervisor-slot
2414    /// [`SupervisorSpec`] whose canonical baseline is not "everything
2415    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
2416    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
2417    /// than `empty()` to name the actual invariant the return value
2418    /// pins — the same phrasing already used in the per-arm pin tests
2419    /// on this file. Pinned load-bearing by
2420    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
2421    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
2422    #[must_use]
2423    pub const fn otp_canonical() -> Self {
2424        Self {
2425            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
2426            max_restarts: default_max_restarts(),
2427            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2428            children: Vec::new(),
2429        }
2430    }
2431
2432    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
2433    /// sibling-restart-strategy scalar accessor every consumer that
2434    /// dispatches on the supervisor's per-sibling restart-decision shape
2435    /// keys off — returns the author-declared `:supervisor :estrategia`
2436    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
2437    /// the typed slot's own [`RestartStrategy`] storage.
2438    ///
2439    /// The `:supervisor :estrategia` slot carries the closed-set
2440    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
2441    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
2442    /// [`RestartStrategy::OneForAll`] — restart every child on any child
2443    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
2444    /// [`RestartStrategy::RestForOne`] — restart the failed child and
2445    /// every child started after it, the Erlang/OTP `rest_for_one`
2446    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
2447    /// dynamic children of the same shape, the Erlang/OTP
2448    /// `simple_one_for_one` per-session default) that every downstream
2449    /// consumer of the Supervisor's per-sibling restart-decision fan-out
2450    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
2451    /// paired coherently with the sibling `:children` axis
2452    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
2453    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
2454    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
2455    /// downstream consumer that reads the strategy keys off this scalar
2456    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2457    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
2458    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
2459    /// `estrategia:` field, the future `feira app graph` per-Supervisor
2460    /// strategy print line, the future wasm-operator's per-supervisor
2461    /// sibling-restart-strategy branch, the future M4
2462    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
2463    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
2464    /// reconciliation scheduler's per-strategy fan-out).
2465    ///
2466    /// Prior to this lift the `.estrategia` field was accessed inline at
2467    /// two production sites in `caixa-core/src/supervisor.rs` — the
2468    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2469    /// `match self.estrategia { … }` partition dispatch, and the
2470    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
2471    /// carrier at `estrategia: self.estrategia` — two open-coded
2472    /// field-accesses that expressed no compile-time link back to the
2473    /// typed slot. A future extension of the `:supervisor :estrategia`
2474    /// axis to a richer author surface (a per-cluster strategy override
2475    /// the operator pins through a future `:supervisor :estrategia-overrides`
2476    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2477    /// acknowledges, a per-tenant strategy-alias table the M4 CR
2478    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
2479    /// derivation the future adaptive-supervision engine computes from
2480    /// child-failure-history topology, a per-child-cohort strategy split
2481    /// the future `RestForCohort` extension acknowledged by the
2482    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
2483    /// would have had to be threaded through every open-coded copy in
2484    /// lockstep — one consumer reading the raw variant while a peer read
2485    /// the operator-resolved variant would silently split the
2486    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
2487    /// the actual partition-dispatch input the empty-children refusal
2488    /// arm reached under, a two-consumer split at the validator far from
2489    /// the source `caixa.lisp` with no field naming the strategy-drift
2490    /// root cause. Lifting the resolution rule to a typed method on the
2491    /// substrate primitive means every downstream consumer of the
2492    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
2493    /// reaches for exactly one typed dispatch — the resolver's accept-set
2494    /// migrates as a unit on any future axis addition.
2495    ///
2496    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
2497    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
2498    /// per-`:placement` distribution-strategy axis — same "one typed
2499    /// dispatch on the substrate primitive, thin projections at each
2500    /// consumer" discipline extended onto the M2 supervisor-slot
2501    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
2502    /// scalar axis. The two typed axes (`Placement::estrategia` on the
2503    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
2504    /// Supervisor side) now share one accessor discipline for the shared
2505    /// substrate concept "a `Copy`-projected closed-set enum-arm
2506    /// discriminator that partitions the downstream renderer's per-arm
2507    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
2508    /// `SupervisorSpec` type — companion to the sibling per-`:children`
2509    /// [`crate::ChildSpec::nome`] (57c61d0) /
2510    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2511    /// scalar accessors on the sibling per-`:children` `String`-carry
2512    /// axes. Named `estrategia()` to match the storage field's name and
2513    /// the peer [`crate::Placement::estrategia`] method-name discipline
2514    /// verbatim; the accessor's identity name maps onto the canonical
2515    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
2516    /// docstring already carries.
2517    ///
2518    /// Declared `pub const fn` to close the M2 supervisor-slot
2519    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
2520    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
2521    /// (converted in this commit) `Copy`-composite-enum accessor, peer
2522    /// of the sibling M2 per-`:supervisor`
2523    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2524    /// already lifted, and mirror of the peer M3 mesh-slot
2525    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
2526    /// `Copy`-return `pub const fn` scalar accessor whose method-name
2527    /// discipline this accessor was authored to match. Every downstream
2528    /// substrate-side `const`-context consumer of the per-`:supervisor`
2529    /// sibling-restart-strategy scalar (a future module-scope `const
2530    /// _:() = assert!(matches!(sup.estrategia(),
2531    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
2532    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2533    /// admission-webhook `const fn` per-supervisor strategy-arm floor
2534    /// over a typed [`SupervisorSpec`], any future `const fn`
2535    /// supervisor-tree composer over the substrate primitive that fans
2536    /// on the sibling-restart-strategy at compile time) now reaches
2537    /// through the same typed dispatch on the substrate primitive at
2538    /// const-eval time as at runtime. A future non-`Copy`-return
2539    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
2540    /// migration once the substrate grows per-cluster strategy overlays
2541    /// the [`SupervisorSpec`] docstring already anticipates, a
2542    /// per-tenant strategy-alias table the M4 CR materializer resolves
2543    /// per-CR) that would drop the `const` qualifier fails the
2544    /// fail-before-pass-after pin
2545    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
2546    /// caixa-core build time rather than surfacing as a downstream
2547    /// consumer regression.
2548    #[must_use]
2549    pub const fn estrategia(&self) -> RestartStrategy {
2550        self.estrategia
2551    }
2552
2553    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
2554    /// `MaxIntensity` restart-budget scalar accessor every consumer that
2555    /// reads the supervisor's per-`:restart-window` restart-budget count
2556    /// keys off — returns the author-declared `:supervisor :max-restarts`
2557    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
2558    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
2559    /// borrow of `&self` past the call). Non-optional (the `u32` field
2560    /// carries the restart-budget count as a required axis with a
2561    /// [`default_max_restarts`]-supplied default; the zero-floor arm
2562    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
2563    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
2564    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
2565    ///
2566    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
2567    /// `MaxIntensity` restart-budget count that pairs with the sibling
2568    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
2569    /// restart-intensity ratio the supervisor trips its own escalation on
2570    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
2571    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
2572    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
2573    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
2574    /// upper-cap bracket at
2575    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
2576    /// wasm-operator's per-supervisor restart-intensity counter's
2577    /// budget-vs-count comparator, the future M4
2578    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2579    /// webhook, the `caixa-operator`'s hierarchical reconciliation
2580    /// scheduler's per-supervisor escalation-decision branch, every
2581    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
2582    /// offending count verbatim for `feira lint` rendering).
2583    ///
2584    /// Prior to this lift the `.max_restarts` field was accessed inline at
2585    /// one production site in `caixa-core/src/supervisor.rs` — the
2586    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
2587    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
2588    /// that expressed no compile-time link back to the typed slot. A
2589    /// future extension of the `:max-restarts` axis to a richer author
2590    /// surface (a per-cluster restart-budget override the operator pins
2591    /// through a future `:supervisor :max-restarts-overrides` slot the
2592    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
2593    /// a per-tenant restart-budget-alias table the M4 CR materializer
2594    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
2595    /// the future adaptive-supervision engine computes from child-failure-
2596    /// history topology, a promotion of the plain `u32` count to a richer
2597    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
2598    /// budget-partition slot comes into scope) would have had to be
2599    /// threaded through every open-coded copy in lockstep or the validate
2600    /// gate and the future M4 emit path would silently disagree on which
2601    /// restart-budget count a given supervisor resolves to — an author's
2602    /// `:max-restarts 5` would satisfy validate while the emit path
2603    /// silently read a drifted other value (a `:max-restarts 10000`
2604    /// no-op supervisor at the emit boundary would carry the author's
2605    /// declared `5` verbatim in `feira lint` output while the future
2606    /// wasm-operator's restart-intensity counter operated under the
2607    /// drifted count), a two-consumer split at the validator far from the
2608    /// source `caixa.lisp` with no field naming the restart-budget-drift
2609    /// root cause. Lifting the resolution rule to a typed method on the
2610    /// substrate primitive means every downstream consumer of the
2611    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
2612    /// for exactly one typed dispatch — the resolver's accept-set migrates
2613    /// as a unit on any future axis addition.
2614    ///
2615    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
2616    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
2617    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
2618    /// outlier-detection trip-threshold axis — same "one typed dispatch on
2619    /// the substrate primitive, thin projections at each consumer"
2620    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
2621    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
2622    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
2623    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
2624    /// one accessor discipline for the shared substrate concept "a
2625    /// `Copy`-projected required `u32` count that trips the next-higher
2626    /// protection layer after N events in a rolling window" — both are
2627    /// counters with identical degenerate-at-the-high-end shape and share
2628    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
2629    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
2630    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
2631    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
2632    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
2633    /// the storage field's name verbatim and the peer
2634    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
2635    /// accessor's identity maps onto the canonical OTP-shape supervision
2636    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
2637    /// already carries.
2638    #[must_use]
2639    pub const fn max_restarts(&self) -> u32 {
2640        self.max_restarts
2641    }
2642
2643    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
2644    /// `Period` sliding-window scalar accessor every consumer of the
2645    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
2646    /// keys off — returns the author-declared `:supervisor :restart-window`
2647    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
2648    /// the typed slot's own `Option<Duration>` storage (`Duration` is
2649    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
2650    /// value; no borrow of `&self` past the call). `None` when the slot is
2651    /// absent (the canonical "never reset — every restart across the
2652    /// supervisor's lifetime counts against the sibling `:max-restarts`
2653    /// budget" sentinel the field's own docstring names and the peer
2654    /// `validate_accepts_none_restart_window` pin locks in on the
2655    /// [`SupervisorSpec::validate`] entry-side).
2656    ///
2657    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
2658    /// `Period` sliding-observation-interval that pairs with the sibling
2659    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
2660    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
2661    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
2662    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
2663    /// default). The typed slot's `Option<Duration>` accept-set —
2664    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
2665    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
2666    /// `Period > 0`; a zero period either trips on the first failure or
2667    /// never trips depending on operator interpretation, neither of which
2668    /// is the author's intent — omit the slot to express "no reset";
2669    /// carry a positive duration to express the sliding window),
2670    /// integer-millisecond canonical form enforced through
2671    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
2672    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
2673    /// future wasm-operator's per-supervisor restart-intensity counter
2674    /// quantizes at milliseconds), upper-bounded by
2675    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
2676    /// supervisor rolling window any operationally-reachable supervisor
2677    /// can honor without spanning multiple scheduler epochs the
2678    /// hierarchical-reconciliation scheduler treats as independent) —
2679    /// maps onto the future wasm-operator (M3) per-supervisor
2680    /// restart-intensity counter's rolling-observation-interval, the
2681    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2682    /// per-`spec.restartWindow` admission webhook, and the sibling
2683    /// `duration_codec`-serialized wire scalar every downstream consumer
2684    /// of the supervisor's per-`:supervisor` restart-intensity denominator
2685    /// keys off.
2686    ///
2687    /// Prior to this lift the `.restart_window` field was accessed inline
2688    /// at one production site in `caixa-core/src/supervisor.rs` — the
2689    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
2690    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
2691    /// open-coded field-access that expressed no compile-time link back to
2692    /// the typed slot. A future extension of the `:restart-window` axis to
2693    /// a richer author surface (a per-cluster restart-window override the
2694    /// operator pins through a future `:supervisor :restart-window-overrides`
2695    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2696    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
2697    /// materializer resolves per-CR, a per-supervisor dynamic
2698    /// restart-window derivation the future adaptive-supervision engine
2699    /// computes from child-failure-history topology, a promotion of the
2700    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
2701    /// pair once Erlang/OTP's per-child-cohort observation-interval-
2702    /// partition slot comes into scope) would have had to be threaded
2703    /// through every open-coded copy in lockstep or the validate gate and
2704    /// the future M4 emit path would silently disagree on which
2705    /// restart-window a given supervisor resolves to — an author's
2706    /// `:restart-window "60s"` would satisfy validate while the emit path
2707    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
2708    /// authored slot at the emit boundary would carry the author's
2709    /// declared window verbatim in `feira lint` output while the future
2710    /// wasm-operator's restart-intensity counter operated under a
2711    /// drifted window, or vice versa: an author's `:restart-window ()`
2712    /// would carry the "never reset" sentinel through validate while the
2713    /// emit path silently substituted a default sliding window), a
2714    /// two-consumer split at the validator far from the source
2715    /// `caixa.lisp` with no field naming the restart-window-drift root
2716    /// cause. Lifting the resolution rule to a typed method on the
2717    /// substrate primitive means every downstream consumer of the
2718    /// Supervisor's per-`:supervisor` restart-intensity-denominator
2719    /// surface reaches for exactly one typed dispatch — the resolver's
2720    /// accept-set migrates as a unit on any future axis addition.
2721    ///
2722    /// Third `Copy`-return accessor on the M2 supervisor-slot
2723    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
2724    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
2725    /// payload rather than a `Copy`-scalar, and the per-`:children`
2726    /// [`crate::ChildSpec::nome`] (57c61d0) /
2727    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2728    /// scalar accessors already close the per-element `String`-carry
2729    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
2730    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
2731    /// per-outermost-call wall-clock-deadline axis and the peer M3
2732    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
2733    /// accessor on the `:politicas` slot's per-call-deadline axis — all
2734    /// three share the shared substrate concept "a `Copy`-projected
2735    /// optional `Duration` that carries a positive integer-millisecond
2736    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
2737    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
2738    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
2739    /// bracket-helper the three axes each route through. Named
2740    /// `restart_window()` to match the storage field's name verbatim and
2741    /// the peer [`crate::LimitsSpec::wall_clock`] /
2742    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
2743    /// accessor's identity maps onto the canonical OTP-shape supervision
2744    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
2745    /// already carries.
2746    #[must_use]
2747    pub const fn restart_window(&self) -> Option<Duration> {
2748        self.restart_window
2749    }
2750
2751    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
2752    /// static-child-list slice accessor every consumer that walks the
2753    /// supervisor's declared child set keys off — returns the author-
2754    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
2755    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
2756    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
2757    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
2758    /// through). Non-optional: an empty slice is the load-bearing
2759    /// "author declared `:children ()`" sentinel every consumer of the
2760    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
2761    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
2762    /// three strategies require a non-empty slice — the paired
2763    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
2764    /// [`SupervisorError::NoChildren`] refusal cascade pins the
2765    /// partition on both arms).
2766    ///
2767    /// The `:supervisor :children` slot carries the OTP-shaped static
2768    /// child list the supervisor materializes one ComputeUnit per
2769    /// entry from — the Erlang/OTP `supervisor:init/1`'s
2770    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
2771    /// through the tatara-lisp `:children` author surface onto a typed
2772    /// `Vec<ChildSpec>` whose per-element `(nome(),
2773    /// versao_requirement(), restart)` triple the per-child
2774    /// [`SupervisorSpec::validate`] loop already gates through the
2775    /// lifted [`ChildSpec::nome`] (57c61d0) /
2776    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
2777    /// Every downstream consumer that fans on the static child list
2778    /// keys off this slice (the [`SupervisorSpec::validate`]
2779    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
2780    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
2781    /// per-child DNS-1123 / semver-requirement / duplicate-detection
2782    /// fan-out loop, every future wasm-operator (M3) per-supervisor
2783    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
2784    /// materialization loop, the future M4
2785    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2786    /// admission-webhook fan-out, the future `feira app graph`
2787    /// per-supervisor tree-print traversal).
2788    ///
2789    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
2790    /// inline at three production sites in `caixa-core/src/supervisor.rs`
2791    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
2792    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
2793    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
2794    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
2795    /// validate loop's `for child in &self.children` traversal head —
2796    /// three open-coded field-accesses that expressed no compile-time
2797    /// link back to the typed slot. A future extension of the
2798    /// `:supervisor :children` axis to a richer author surface (a
2799    /// per-cluster child-set overlay the operator pins through a future
2800    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
2801    /// supervision-canary roadmap acknowledges, a per-tenant
2802    /// child-set-alias table the M4 CR materializer resolves per-CR,
2803    /// a per-supervisor dynamic-child derivation the future adaptive-
2804    /// supervision engine computes from child-failure-history topology,
2805    /// a promotion of the plain `Vec<ChildSpec>` to a richer
2806    /// `{static, dynamic}` partition once Erlang/OTP's
2807    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
2808    /// would have had to be threaded through all three open-coded copies
2809    /// in lockstep or one consumer would silently disagree with the
2810    /// peers on which child-set a given supervisor resolves to — the
2811    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
2812    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
2813    /// would silently split the partition-dispatch's two-arm coherence
2814    /// (a supervisor that satisfies neither arm's precondition, or that
2815    /// satisfies both, at the cost of the paired
2816    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
2817    /// silently drifting from the per-child validate loop's actual
2818    /// traversal input), a three-consumer split at the validator far
2819    /// from the source `caixa.lisp` with no field naming the
2820    /// child-set-drift root cause. Lifting the resolution rule to a
2821    /// typed method on the substrate primitive means every downstream
2822    /// consumer of the Supervisor's per-`:supervisor` static-child-list
2823    /// surface reaches for exactly one typed dispatch — the resolver's
2824    /// accept-set migrates as a unit on any future axis addition.
2825    ///
2826    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
2827    /// — the seed for the same "one typed dispatch on the substrate
2828    /// primitive, thin projections at each consumer" discipline the
2829    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
2830    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
2831    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
2832    /// onto the first `Vec`-carry axis on the substrate. The four peer
2833    /// `Vec`-carry axes still unlifted at the time of this seed —
2834    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
2835    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
2836    /// (`Vec<Membro>` per-Aplicacao member list),
2837    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
2838    /// per-Aplicacao WIT-typed edge list),
2839    /// [`crate::UpgradeFromEntry::instructions`]
2840    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
2841    /// — inherit this accessor's discipline as future compounding runs
2842    /// migrate their consumers onto the shared slice-return shape.
2843    /// Fourth (and final) accessor on the M2 supervisor-slot
2844    /// `SupervisorSpec` type, sibling to the three `Copy`-return
2845    /// [`SupervisorSpec::estrategia`] (eafb619) /
2846    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
2847    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
2848    /// the last unlifted per-`:supervisor` field axis (the
2849    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
2850    /// per-`:supervisor` reader now routes through a typed dispatch on
2851    /// the substrate primitive. Named `children()` to match the storage
2852    /// field's name verbatim and the tatara-lisp author-surface term
2853    /// (`:children`) the field's own docstring already carries; the
2854    /// accessor's identity maps onto the canonical OTP-shape
2855    /// supervision vocabulary the [`SupervisorSpec::children`] field's
2856    /// docstring already reaches for ("Static children ..."). Returns
2857    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
2858    /// consumer of the child list treats it as a read-only sequence —
2859    /// the slice-view is the narrowest borrow that supports every
2860    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
2861    /// index, `.len()`) without leaking the backing `Vec`'s
2862    /// grow/push/reserve surface that no consumer of the typed view
2863    /// reaches for (the storage-side `Vec` remains reachable through
2864    /// the `pub children` field for the mutation-carrying
2865    /// `Caixa::supervisor_view` fold-in path in
2866    /// `manifest.rs:supervisor_view`).
2867    #[must_use]
2868    pub const fn children(&self) -> &[ChildSpec] {
2869        self.children.as_slice()
2870    }
2871
2872    /// Validate the supervisor's typed shape — strategy ↔ children
2873    /// invariants, max_restarts > 0, restart_window > 0 when set,
2874    /// per-child non-empty + duplicate-free names.
2875    ///
2876    /// Mirrors the value-shape discipline applied to every other
2877    /// typed slot:
2878    ///
2879    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
2880    ///     same "0 means the opposite of what you think" footgun
2881    ///     closed for `:politicas :timeout` (Envoy interprets a zero
2882    ///     timeout as `infinite`), `:politicas :circuit-breaker
2883    ///     :window`, and `:limits :wall-clock`. The
2884    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
2885    ///     `supervisor` requires `Period > 0`; a zero period either
2886    ///     trips on the first failure or never trips depending on
2887    ///     operator interpretation, neither of which is the
2888    ///     author's intent. Omit `:restart-window` to express "no
2889    ///     reset"; carry a positive duration to express the window.
2890    ///   - duplicate `:children` `:caixa` names are the same
2891    ///     graph-node-set / multiset distinction closed for
2892    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
2893    ///     and `:entrada :paths` (eb3456d). Two children with the
2894    ///     same `:caixa` materialize as two ComputeUnits with the
2895    ///     same name in the cluster's HelmRelease values, one
2896    ///     silently overwriting the other. Erlang/OTP's
2897    ///     `child_spec.id` is required-unique per supervisor;
2898    ///     pleme-io enforces the same set-not-multiset shape on
2899    ///     `:caixa` (the load-bearing identity in our renderer).
2900    pub fn validate(&self) -> Result<(), SupervisorError> {
2901        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
2902        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2903        // error carrier's `estrategia:` field through the lifted
2904        // [`SupervisorSpec::estrategia`] accessor rather than the raw
2905        // `self.estrategia` field access — the two production consumers
2906        // of the per-`:supervisor` sibling-restart-strategy scalar now
2907        // key off exactly one typed dispatch on the substrate primitive,
2908        // so any future rebrand on the axis (a per-cluster strategy
2909        // override the operator pins through a future `:supervisor
2910        // :estrategia-overrides` slot, a per-tenant strategy-alias table
2911        // the M4 CR materializer resolves per-CR) migrates as a single
2912        // caixa-core edit rather than a coordinated rewrite of the two
2913        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
2914        // (921fe1b) four-consumer migration on the per-`:placement`
2915        // distribution-strategy axis.
2916        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
2917        // dispatch's paired `.is_empty()` cross-slot refusal probes
2918        // (the `SimpleOneForOne`-arm
2919        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
2920        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2921        // refusal) through the lifted [`SupervisorSpec::children`]
2922        // slice-return accessor rather than the raw `self.children`
2923        // field access — the two paired production consumers of the
2924        // per-`:supervisor` static-child-list scalar-shape now key off
2925        // exactly one typed dispatch on the substrate primitive, so any
2926        // future rebrand on the axis (a per-cluster child-set overlay
2927        // the operator pins through a future `:supervisor
2928        // :children-overrides` slot, a per-tenant child-set-alias table
2929        // the M4 CR materializer resolves per-CR) migrates as a single
2930        // caixa-core edit rather than a coordinated rewrite of the
2931        // paired arms — first slice-return migration on any typed slot,
2932        // seed for the peer per-`:placement :clusters`,
2933        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
2934        // :instructions` `Vec`-carry axes.
2935        match self.estrategia() {
2936            RestartStrategy::SimpleOneForOne => {
2937                // SimpleOneForOne: children added at runtime. Static
2938                // list must be empty (one shape declared elsewhere).
2939                if !self.children().is_empty() {
2940                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
2941                }
2942            }
2943            _ => {
2944                if self.children().is_empty() {
2945                    return Err(SupervisorError::no_children(self.estrategia()));
2946                }
2947            }
2948        }
2949        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
2950        // axis. See [`crate::render::require_positive_bounded_u32`] for
2951        // the ordering discipline (zero-floor arm strictly precedes cap
2952        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
2953        // diagnostic with its counter-axis remediation directly named,
2954        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
2955        // cap-arm miss). Until this bracket landed the top edge ran all
2956        // the way to `u32::MAX` and a struct-literal
2957        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
2958        // equivalent author-surface `:max-restarts 100000` /
2959        // `:max-restarts 4294967295` typo landing in the slot) silently
2960        // passed validate. The runtime substrate consuming the value
2961        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
2962        // wasm-operator's per-supervisor restart-intensity counter, the
2963        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2964        // admission webhook) then turned a typed `:max-restarts`
2965        // policy into a no-op supervisor: the escalation threshold is
2966        // structurally so high that no realistic
2967        // restarts-per-`:restart-window` traffic shape can reach it,
2968        // the supervisor never escalates to its parent, and a bad
2969        // child can loop inside the window indefinitely with the
2970        // parent supervisor structurally never receiving the "this
2971        // subtree has exceeded its restart budget" signal the typed
2972        // slot is meant to express. The bracket set is
2973        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
2974        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
2975        // the sibling `:politicas :circuit-breaker :max-failures` axis:
2976        // both are "trip the next-higher protection layer after N
2977        // events in a rolling window" counters with identical
2978        // degenerate-at-the-high-end shape and now share one canonical
2979        // bracket helper. The bracket precedes the sibling
2980        // `:restart-window` zero-floor / canonical-millisecond arms so
2981        // an over-cap `max_restarts` paired with a structurally invalid
2982        // window surfaces the bracket diagnostic first, mirroring the
2983        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
2984        // ordering on the peer `:politicas :circuit-breaker` slot.
2985        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
2986        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
2987        // accessor rather than the raw `self.max_restarts` field access —
2988        // the one production consumer of the per-`:supervisor`
2989        // restart-budget-count scalar now keys off exactly one typed
2990        // dispatch on the substrate primitive, so any future rebrand on
2991        // the axis (a per-cluster restart-budget override the operator
2992        // pins through a future `:supervisor :max-restarts-overrides`
2993        // slot, a per-tenant restart-budget-alias table the M4 CR
2994        // materializer resolves per-CR) migrates as a single caixa-core
2995        // edit rather than a coordinated rewrite — sibling of the peer M3
2996        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
2997        // the per-`:politicas :circuit-breaker :max-failures` axis.
2998        crate::render::require_positive_bounded_u32(
2999            self.max_restarts(),
3000            SUPERVISOR_MAX_RESTARTS_MAX,
3001            || SupervisorError::ZeroMaxRestarts,
3002            SupervisorError::max_restarts_exceeds_cap,
3003        )?;
3004        // Route the [`SupervisorSpec::validate`] `:restart-window`
3005        // zero-floor + integer-millisecond canonical-form + upper-cap
3006        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
3007        // accessor rather than the raw `self.restart_window` field access —
3008        // the one production consumer of the per-`:supervisor`
3009        // restart-intensity-denominator scalar now keys off exactly one
3010        // typed dispatch on the substrate primitive, so any future rebrand
3011        // on the axis (a per-cluster restart-window override the operator
3012        // pins through a future `:supervisor :restart-window-overrides`
3013        // slot, a per-tenant restart-window-alias table the M4 CR
3014        // materializer resolves per-CR) migrates as a single caixa-core
3015        // edit rather than a coordinated rewrite — sibling of the peer M2
3016        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
3017        // on the per-`:limits :wall-clock` axis and the peer M3
3018        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
3019        // per-`:politicas :timeout` axis.
3020        if let Some(w) = self.restart_window() {
3021            // Zero-floor + integer-millisecond canonical-form +
3022            // upper-cap bracket on the typed `:restart-window` axis.
3023            // See
3024            // [`crate::render::require_positive_canonical_bounded_duration`]
3025            // for the full three-arm ordering discipline (zero-floor
3026            // strictly precedes canonical-form so `Duration::ZERO`
3027            // surfaces the self-locating `RestartWindowZero`
3028            // diagnostic; canonical-form strictly precedes the cap arm
3029            // so a sub-millisecond above-cap value surfaces the more
3030            // fundamental round-trip-shape diagnostic first) and the
3031            // three peer typed-`Duration` sites that share this
3032            // canonical bracket ([`crate::MeshPolicy::timeout`],
3033            // [`crate::CircuitBreaker::window`],
3034            // [`crate::LimitsSpec::wall_clock`]). Every validated
3035            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3036            // (1ms..=1h), integer-millisecond granularity.
3037            crate::render::require_positive_canonical_bounded_duration(
3038                w,
3039                SUPERVISOR_RESTART_WINDOW_MAX,
3040                || SupervisorError::RestartWindowZero,
3041                SupervisorError::restart_window_not_canonical,
3042                SupervisorError::restart_window_exceeds_cap,
3043            )?;
3044        }
3045        // Route the per-child DNS-1123 / semver-requirement / duplicate-
3046        // detection fan-out loop through the lifted named per-slot gate
3047        // [`SupervisorSpec::validate_children`] rather than an inline
3048        // three-per-child cascade — every future consumer that wants to
3049        // re-check only the `:children` slot's per-entry axes (the M4
3050        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3051        // admission webhook re-validating one added/renamed child, the
3052        // future wasm-operator's per-child dynamic-add re-validator on
3053        // the `SimpleOneForOne` runtime-add path once dynamic-children
3054        // graduate to a typed slot, a future partial re-validator on a
3055        // per-`:children`-entry patch) reaches every per-entry axis
3056        // through one dispatch rather than re-inlining the three-arm
3057        // cascade in lockstep with `validate` or paying the peer
3058        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
3059        // reach one entry check. Sibling of the peer M3 mesh-slot
3060        // per-slot gate family (`validate_membros` — the exact peer on
3061        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
3062        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
3063        // `validate_placement`; `validate_politicas` routing through
3064        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
3065        // per-slot gate discipline now spans both the M3 mesh-slot
3066        // family and the M2 `:children` per-child-cascade axis on one
3067        // shape: one named per-slot gate per typed per-entry loop.
3068        self.validate_children()?;
3069        Ok(())
3070    }
3071
3072    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
3073    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
3074    /// gate, and duplicate-`:caixa` dedup arm into one call every
3075    /// consumer that wants to re-validate one `:children` entry (or the
3076    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
3077    /// admits reaches through.
3078    ///
3079    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
3080    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
3081    /// three-per-entry shape (DNS-1123 name + semver-requirement +
3082    /// duplicate-`:caixa` dedup), lifted to one named substrate
3083    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3084    /// materializer's admission webhook re-checking one added or renamed
3085    /// child, the future wasm-operator's per-child dynamic-add
3086    /// re-validator on the `SimpleOneForOne` runtime-add path once
3087    /// dynamic-children graduate to a typed slot, a future partial
3088    /// re-validator on a per-`:children`-entry patch — each reaches the
3089    /// three per-entry axes through this one dispatch rather than
3090    /// re-inlining the three-arm cascade in lockstep with `validate`
3091    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
3092    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
3093    /// reach one entry check.
3094    ///
3095    /// Self-contained on `&self` — resolves its own dedup `HashSet`
3096    /// through [`SupervisorSpec::children`] rather than borrowing one
3097    /// threaded down from `validate`, the same posture the peer M3
3098    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
3099    /// [`crate::AplicacaoSpec::validate_contratos`],
3100    /// [`crate::AplicacaoSpec::validate_entrada`],
3101    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
3102    /// consumer that reaches this gate directly (without first calling
3103    /// `validate`) still runs the full per-child cascade — pinned by
3104    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3105    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3106    /// + `validate_children_is_self_contained_on_children_slot`.
3107    ///
3108    /// The three per-entry arms run in the same canonical order the
3109    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
3110    /// the diagnostic every author-declared per-`:children` entry surfaces
3111    /// through `validate` is byte-equal to the diagnostic this gate
3112    /// surfaces when called directly — the equivalence-pin pair
3113    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3114    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3115    /// asserts the two altitudes discriminate the same set on every
3116    /// per-entry-covered input.
3117    pub fn validate_children(&self) -> Result<(), SupervisorError> {
3118        let mut seen = std::collections::HashSet::new();
3119        for child in self.children() {
3120            // Every emitted cluster artifact's `metadata.name` for a
3121            // supervised child derives from this `:children :caixa` value
3122            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
3123            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
3124            // label value on every child's pod identity, and the per-
3125            // child K8s [`Service`][svc] `metadata.name` the future
3126            // wasm-operator (M3) provisions for inter-child supervision
3127            // tree wiring. Each apiserver-side schema on each landing
3128            // site enforces the DNS-1123 label rule on admission; a
3129            // structurally invalid child name (`"Worker"`, `"my_worker"`,
3130            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
3131            // UUID-shaped mistaken-identity slug) silently passes the
3132            // prior empty-/duplicate-only gate and the failure surfaces
3133            // at `kubectl apply` time as a `metadata.name: Invalid value`
3134            // rejection, far from the source caixa.lisp, with no field
3135            // naming the offending `:children` entry. Lifting the gate
3136            // to caixa-build time mirrors the `:membros :caixa` value-
3137            // shape trajectory (3f9d7a0) and the `:placement :clusters`
3138            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
3139            // identifier axis — the supervisor tree's child names —
3140            // through the lifted
3141            // [`crate::render::require_valid_dns_1123_label`] gate the
3142            // seven peer name axes (`:membros :caixa`, `:placement
3143            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
3144            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
3145            // route through, so drift between the eight axes' accepted
3146            // DNS-1123-label sets is structurally impossible.
3147            //
3148            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
3149            crate::render::require_valid_dns_1123_label(
3150                child.nome(),
3151                || SupervisorError::EmptyChildName,
3152                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
3153            )?;
3154            // The author surface for `:children :versao` is the same
3155            // Cargo-shaped semver requirement string `:deps :versao` and
3156            // `:membros :versao` carry — and the lacre pipeline resolves
3157            // all three axes through the same
3158            // [`crate::version::parse_requirement`] entry-point. The
3159            // shared [`crate::render::require_valid_versao_requirement`]
3160            // helper brackets the empty-first + parse cascade both peer
3161            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
3162            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
3163            // :versao`) route through, so drift between the three axes'
3164            // accepted requirement sets is structurally impossible and
3165            // the parse-side no-op the empty-first arm closes (semver's
3166            // empty parse yields an implicit `*`) lives in exactly one
3167            // predicate. Every `ChildSpec::versao` past validate is
3168            // round-trippable through [`crate::parse_requirement`]
3169            // without re-checking at the resolver layer, and the three
3170            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
3171            // are now structurally equivalent by construction.
3172            crate::render::require_valid_versao_requirement(
3173                child.versao_requirement(),
3174                || SupervisorError::empty_child_version(child.nome()),
3175                |reason| {
3176                    SupervisorError::child_versao_invalid(
3177                        child.nome(),
3178                        child.versao_requirement(),
3179                        reason,
3180                    )
3181                },
3182            )?;
3183            crate::render::insert_first_seen(&mut seen, child.nome(), || {
3184                SupervisorError::duplicate_child_caixa(child.nome())
3185            })?;
3186        }
3187        Ok(())
3188    }
3189}
3190
3191/// Cross-slot coherence gate on the supervision tree: no
3192/// `:children :caixa` entry may name the supervisor's own `:nome`.
3193///
3194/// A supervisor that lists itself as a child is a degenerate self-parent
3195/// — the supervision tree is a DAG rooted at the supervisor (OTP child
3196/// specs reference *distinct* child processes; a supervisor is never its
3197/// own child), and the wasm-operator's hierarchical reconciliation would
3198/// otherwise be handed a node that is its own parent: a one-node cycle it
3199/// either rejects far from the source `caixa.lisp` or recurses on. Because
3200/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
3201/// lacre closure root), a child whose `:caixa` equals the supervisor's
3202/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
3203///
3204/// Lives outside [`SupervisorSpec::validate`] because the typed view
3205/// carries the children but not the parent `:nome`; mirrors the
3206/// cross-slot precedence gate `validate_upgrade_from_against_versao`
3207/// (which likewise reads one slot against another at the
3208/// [`crate::layout`] wire-up site) and the mesh self-edge gate
3209/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
3210/// node to itself is structurally not a tree/mesh edge" discipline, here
3211/// on the supervision-tree axis.
3212pub fn validate_no_self_supervision(
3213    children: &[ChildSpec],
3214    parent_nome: &str,
3215) -> Result<(), SupervisorError> {
3216    for child in children {
3217        if child.nome() == parent_nome {
3218            return Err(SupervisorError::child_supervises_self(parent_nome));
3219        }
3220    }
3221    Ok(())
3222}
3223
3224#[derive(Debug, Error, PartialEq, Eq)]
3225pub enum SupervisorError {
3226    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
3227    NoChildren { estrategia: RestartStrategy },
3228    #[error(
3229        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
3230    )]
3231    SimpleOneForOneWithStaticChildren,
3232    #[error(":max-restarts must be > 0")]
3233    ZeroMaxRestarts,
3234    #[error(
3235        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
3236         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
3237         restart-intensity policy into a no-op supervisor: the escalation threshold is \
3238         structurally so high that no realistic restarts-per-:restart-window traffic shape \
3239         can reach it, so the supervisor never escalates to its parent and a bad child can \
3240         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
3241         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
3242         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3243         materializer's admission webhook) emits a `:max-restarts` declaration that is \
3244         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
3245         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
3246         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
3247         band) or restructure the supervision tree (split the flaky child into its own \
3248         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
3249    )]
3250    MaxRestartsExceedsCap { max_restarts: u32 },
3251    #[error(
3252        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
3253         requires Period > 0; a zero window either trips on the first failure or \
3254         never trips depending on operator interpretation. Omit :restart-window to \
3255         express `never reset`; carry a positive duration to express the window."
3256    )]
3257    RestartWindowZero,
3258    #[error(
3259        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
3260         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
3261         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
3262         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
3263         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
3264    )]
3265    RestartWindowNotCanonical { window: Duration },
3266    #[error(
3267        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
3268         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
3269         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
3270         failure-counting window is structurally so long that transient restarts are never \
3271         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
3272         when the child has exceeded its restart budget within the recent window` to `trip the \
3273         parent when the child has exceeded its restart budget over its lifetime`, and the \
3274         supervisor's reset semantic never reaches the child — every typed-slot consumer \
3275         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
3276         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3277         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
3278         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
3279         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
3280         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
3281         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
3282         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
3283         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
3284         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
3285         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
3286         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
3287         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
3288         hiding it behind a rolling-window declaration the cap arm rejects)"
3289    )]
3290    RestartWindowExceedsCap { window: Duration },
3291    #[error("child entry has empty :caixa name")]
3292    EmptyChildName,
3293    #[error(
3294        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
3295         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
3296         name / label value the child name lands in — the per-child \
3297         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
3298         label value, and the future wasm-operator per-child Service `metadata.name` \
3299         — each apiserver-side schema rejects names that don't match; use a \
3300         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
3301    )]
3302    ChildCaixaInvalid { caixa: String, reason: String },
3303    #[error("child {caixa:?} has empty :versao constraint")]
3304    EmptyChildVersion { caixa: String },
3305    #[error(
3306        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
3307         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
3308         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
3309         `:membros :versao` carry; the lacre pipeline resolves all three \
3310         through the same parser)"
3311    )]
3312    ChildVersaoInvalid {
3313        caixa: String,
3314        versao: String,
3315        reason: String,
3316    },
3317    #[error(
3318        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
3319         child_spec.id per supervisor; duplicate children materialize as duplicate \
3320         ComputeUnits in the rendered chart, one silently overwriting the other)"
3321    )]
3322    DuplicateChildCaixa { caixa: String },
3323    #[error(
3324        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
3325         never its own child (the supervision tree is a DAG rooted at the supervisor; \
3326         OTP child specs reference distinct child processes). Since every :nome is a \
3327         globally-unique substrate identity, a child naming the supervisor's own :nome \
3328         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
3329         self-referential :children entry or rename it to the actual child caixa."
3330    )]
3331    ChildSupervisesSelf { caixa: String },
3332}
3333
3334// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
3335// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
3336// and [`validate_no_self_supervision`] onto one substrate primitive per
3337// typed variant — the sibling on `SupervisorError` of the four uniform-shape
3338// `LayoutError`-envelope constructor families the peer
3339// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
3340// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
3341// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
3342// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
3343// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
3344// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
3345// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
3346// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
3347// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
3348// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
3349// variants on `{ de, para }`) already at that discipline on the peer
3350// `AplicacaoError` envelopes.
3351//
3352// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
3353// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
3354// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
3355// self-supervision arm) opened the identical
3356// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
3357// the exact "same block re-inlined at every consumer" shape the PRIME
3358// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
3359// `AplicacaoError` families each closed on their sibling envelopes. The
3360// three variants share one `{ caixa: String }` shape, so the fold routes
3361// each wire-up site through one dispatch per typed variant.
3362//
3363// The macro below generates one static constructor per variant of shape
3364// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
3365// collapses onto one dispatch:
3366// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
3367// struct-literal on the same `&str` fixture. The uniform one-field
3368// construction (`caixa: caixa.to_string()`) is spelled once — inside the
3369// macro — rather than at every wire-up site. Every constructor is
3370// `#[must_use]` so a caller who mistakenly discards the constructed error
3371// trips a compile warning at the wire-up site.
3372//
3373// Every future consumer that wants to construct one of these three
3374// variants outside `SupervisorSpec::validate_children` /
3375// `validate_no_self_supervision` — a deferred
3376// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3377// webhook re-checking one added/renamed child, a future
3378// `feira validate --supervisor` per-caixa admission verb, a per-child
3379// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
3380// once dynamic-children graduate to a typed slot, a per-Supervisor
3381// overlay resolver rejecting a duplicate/self-supervising child against
3382// a cluster-local snapshot — now reaches each variant through one call
3383// rather than re-inlining the three-line struct-literal in lockstep
3384// with the three in-crate wire-up sites.
3385macro_rules! supervisor_caixa_only_ctors {
3386    ($($ctor:ident => $variant:ident),* $(,)?) => {
3387        impl SupervisorError {
3388            $(
3389                #[doc = concat!(
3390                    "Construct a [`SupervisorError::",
3391                    stringify!($variant),
3392                    "`] naming the offending `:children :caixa` (or ",
3393                    "supervisor `:nome`, on the self-supervision arm). ",
3394                    "Folds the uniform `Self::",
3395                    stringify!($variant),
3396                    " { caixa: caixa.to_string() }` one-field ",
3397                    "struct-literal onto one substrate primitive so ",
3398                    "every [`SupervisorSpec::validate_children`] / ",
3399                    "[`validate_no_self_supervision`] wire-up on this ",
3400                    "variant reads through one dispatch rather than the ",
3401                    "pre-lift open-coded struct-literal block."
3402                )]
3403                #[must_use]
3404                pub fn $ctor(caixa: &str) -> Self {
3405                    Self::$variant { caixa: caixa.to_string() }
3406                }
3407            )*
3408        }
3409    };
3410}
3411
3412supervisor_caixa_only_ctors! {
3413    empty_child_version => EmptyChildVersion,
3414    duplicate_child_caixa => DuplicateChildCaixa,
3415    child_supervises_self => ChildSupervisesSelf,
3416}
3417
3418// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
3419// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
3420// one substrate primitive per typed variant — the M2 supervisor-side siblings
3421// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
3422// already lifted through the sibling
3423// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
3424// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
3425// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
3426// String }` two-slot shape the peer seven-variant
3427// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
3428// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
3429// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
3430// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
3431// variant carries the `{ caixa: String, versao: String, reason: String }`
3432// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
3433// carries on the same `:versao` value-shape.
3434//
3435// Each of the two wire-up sites opened the same closure-shaped
3436// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
3437// [versao: child.versao_requirement().to_string(),] reason }` block inside
3438// the paired [`crate::render::require_valid_dns_1123_label`] and
3439// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
3440// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
3441// as a bug, on the same altitude the peer `AplicacaoError` /
3442// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
3443// families already closed on their sibling envelopes.
3444//
3445// The two `#[must_use]` inherent constructors below fold each wire-up onto
3446// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
3447// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
3448// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
3449// The uniform per-field `.to_string()` / `.into()` construction is spelled
3450// once — inside each ctor body — rather than at every wire-up site. The
3451// `reason: impl Into<String>` bound accepts both `&str` literals and
3452// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
3453// diagnostic shape at the lift, matching the peer
3454// [`aplicacao_field_reason_ctors!`] and
3455// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
3456// sibling envelopes.
3457//
3458// Every future consumer that wants to construct one of these two variants
3459// outside `SupervisorSpec::validate_children` — a deferred
3460// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
3461// re-checking one added/renamed child's `:caixa` or `:versao`, a future
3462// `feira validate --supervisor` per-caixa admission verb, a per-child
3463// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
3464// dynamic-children graduate to a typed slot, a per-Supervisor overlay
3465// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
3466// cluster-local snapshot — now reaches each variant through one call rather
3467// than re-inlining the per-shape struct-literal block in lockstep with the
3468// two in-crate wire-up sites.
3469impl SupervisorError {
3470    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
3471    /// offending `:children :caixa` value under the given `reason`. Folds
3472    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
3473    /// reason: reason.into() }` two-slot struct-literal onto one substrate
3474    /// primitive so every wire-up on this variant reads through one
3475    /// dispatch, matching the peer
3476    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
3477    /// sibling `AplicacaoError { caixa: String, reason: String }`
3478    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
3479    /// outputs through the `impl Into<String>` bound.
3480    #[must_use]
3481    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
3482        Self::ChildCaixaInvalid {
3483            caixa: caixa.to_string(),
3484            reason: reason.into(),
3485        }
3486    }
3487
3488    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
3489    /// offending `:children :caixa` and its `:versao` requirement under
3490    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
3491    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
3492    /// reason.into() }` three-slot struct-literal onto one substrate
3493    /// primitive so every wire-up on this variant reads through one
3494    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
3495    /// { caixa, versao, reason }` three-slot axis on the peer
3496    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
3497    /// and `format!(…)` outputs through the `impl Into<String>` bound.
3498    #[must_use]
3499    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
3500        Self::ChildVersaoInvalid {
3501            caixa: caixa.to_string(),
3502            versao: versao.to_string(),
3503            reason: reason.into(),
3504        }
3505    }
3506}
3507
3508// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
3509// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
3510// three bracket-arms — one struct-literal at the `:children`-empty
3511// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
3512// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
3513// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
3514// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
3515// [`crate::render::require_positive_canonical_bounded_duration`]
3516// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
3517// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
3518// primitive per typed variant, matching the sibling
3519// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
3520// variants on the same `{ <field>: Duration | u32 }` shape) at that
3521// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
3522// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
3523// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
3524// wire-up site through one dispatch per typed variant without a runtime-
3525// work delta.
3526//
3527// Each of the four wire-up sites opened the identical
3528// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
3529// exact "same block re-inlined at every consumer" shape the PRIME
3530// DIRECTIVE names as a bug, on the same altitude the peer
3531// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
3532// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
3533// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
3534// the fold routes each wire-up site through one dispatch per typed
3535// variant.
3536//
3537// The macro below generates one static constructor per variant of shape
3538// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
3539// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
3540// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
3541// fixture — as a direct call at the [`SupervisorSpec::validate`]
3542// `:children`-empty refusal, or as a bare function pointer in the
3543// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
3544// [`crate::render::require_positive_bounded_u32`] /
3545// [`crate::render::require_positive_canonical_bounded_duration`] gate
3546// carries — rather than the pre-lift open-coded one-line closure over
3547// the same one-field struct-literal. `const fn` preserves the `Copy`-
3548// pass-through's zero-runtime-work property verbatim. Every constructor
3549// is `#[must_use]` so a caller who mistakenly discards the constructed
3550// error trips a compile warning at the wire-up site.
3551//
3552// Every future consumer that wants to construct one of these four
3553// variants outside `SupervisorSpec::validate` — a deferred
3554// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3555// webhook re-checking one edited `:estrategia` / `:max-restarts` /
3556// `:restart-window` slot against the cap + canonical-form cascade, a
3557// future `feira validate --supervisor` per-caixa admission verb re-
3558// running the shape gates on demand, a per-Supervisor overlay resolver
3559// rejecting an author-supplied slot against a cluster-local snapshot —
3560// now reaches each variant through one call rather than re-inlining the
3561// per-shape struct-literal block in lockstep with the four in-crate
3562// wire-up sites.
3563macro_rules! supervisor_scalar_ctors {
3564    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
3565        impl SupervisorError {
3566            $(
3567                #[doc = concat!(
3568                    "Construct a [`SupervisorError::",
3569                    stringify!($variant),
3570                    "`] naming the offending per-`:supervisor` `",
3571                    stringify!($field),
3572                    "` scalar. Folds the uniform `Self::",
3573                    stringify!($variant),
3574                    " { ",
3575                    stringify!($field),
3576                    " }` one-field `Copy`-pass-through struct-literal onto ",
3577                    "one substrate primitive so every per-axis wire-up on ",
3578                    "this variant reads through one dispatch — as a direct ",
3579                    "call (`SupervisorError::",
3580                    stringify!($ctor),
3581                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
3582                    "the same `Copy`-`",
3583                    stringify!($ty),
3584                    "` fixture) or as a bare function pointer in the ",
3585                    "`impl FnOnce(",
3586                    stringify!($ty),
3587                    ") -> SupervisorError` bracket-closure slot every ",
3588                    "`crate::render::require_positive_bounded_*` / ",
3589                    "`crate::render::require_positive_canonical_bounded_*` ",
3590                    "gate carries — rather than the pre-lift open-coded ",
3591                    "one-line closure over the same one-field struct-",
3592                    "literal. `const fn` preserves the `Copy`-pass-through's ",
3593                    "zero-runtime-work property verbatim."
3594                )]
3595                #[must_use]
3596                pub const fn $ctor($field: $ty) -> Self {
3597                    Self::$variant { $field }
3598                }
3599            )*
3600        }
3601    };
3602}
3603
3604supervisor_scalar_ctors! {
3605    no_children => NoChildren { estrategia: RestartStrategy },
3606    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
3607    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
3608    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
3609}
3610
3611/// Shared duration string codec for the typed slots that take a
3612/// duration (`restart_window`, `MeshPolicy::timeout`,
3613/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
3614/// reuse it without duplicating the parser.
3615pub mod duration_codec {
3616    use super::Duration;
3617    use serde::{Deserializer, Serializer};
3618
3619    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
3620        // Route through the canonical [`crate::render::serialize_option_via_str`]
3621        // — the substrate-side single-owner primitive for the forward
3622        // arm of the typed-magnitude codec family. See its docstring
3623        // for the full sibling roster.
3624        crate::render::serialize_option_via_str(v, s, render)
3625    }
3626
3627    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
3628        // Route through the canonical [`crate::render::deserialize_option_via_str`]
3629        // — the substrate-side single-owner primitive for the reverse
3630        // arm of the typed-magnitude codec family. See its docstring
3631        // for the full sibling roster.
3632        crate::render::deserialize_option_via_str(d, parse)
3633    }
3634
3635    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
3636        // Paired whitespace-rejection arm — same canonical-form
3637        // render-determinism discipline as the peer
3638        // `limits::parse_byte_size` / `limits::parse_duration` /
3639        // `limits::parse_millicores` /
3640        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
3641        // byte-scan closes the WhatWG-conformant whitespace bytes
3642        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
3643        // `char::is_whitespace` scan closes the strictly-complementary
3644        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
3645        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
3646        // codepoints) that `str::trim` at parse entry silently strips.
3647        // Either drift class would round-trip through `render` to a
3648        // *different* canonical form on next emit — breaking the
3649        // THEORY.md Part V render-determinism contract on three typed-
3650        // duration slots at once (`:supervisor :restart-window`,
3651        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
3652        // via the shared codec.
3653        //
3654        // Routed through the lifted [`crate::render::reject_whitespace`]
3655        // primitive — the substrate-side single-owner paired-arm gate
3656        // every typed-magnitude codec in caixa-core shares.
3657        crate::render::reject_whitespace::<String, _, _>(
3658            s,
3659            |b| {
3660                format!(
3661                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
3662                 authoring form for the typed duration slots routed through this shared codec \
3663                 (`:supervisor :restart-window`, `:politicas :timeout`, \
3664                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3665                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
3666                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
3667                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
3668                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
3669                 Part V render-determinism contract every typed slot carries. Strip every \
3670                 whitespace byte (write `\"30s\"` verbatim)"
3671                )
3672            },
3673            |ch| {
3674                format!(
3675                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
3676                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
3677                 duration slots routed through this shared codec (`:supervisor \
3678                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
3679                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
3680                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
3681                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
3682                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
3683                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
3684                 `White_Space` property, strictly wider than the ASCII byte set) silently \
3685                 strips it at parse entry, and the value round-trips through `render` to \
3686                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
3687                 the THEORY.md Part V render-determinism contract every typed slot \
3688                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
3689                 verbatim with only ASCII bytes)",
3690                    cp = ch as u32
3691                )
3692            },
3693        )?;
3694        let s = s.trim();
3695        // Routed through the lifted
3696        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
3697        // the single-owner split every ASCII-alphabetic-unit typed-
3698        // magnitude codec in caixa-core (`limits::parse_byte_size` /
3699        // `limits::parse_duration` / this shared duration codec) shares.
3700        // See its docstring for the full sibling roster on the same
3701        // primitive altitude.
3702        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
3703        let num_trim = num_part.trim();
3704        // The canonical authoring form for every typed slot routed
3705        // through this shared codec — `:supervisor :restart-window`,
3706        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
3707        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
3708        // non-negative integer with no decimal point and no leading
3709        // sign, so the parser's accepted set must match for
3710        // serialize/deserialize to round-trip without canonical-form
3711        // drift. Until this gate landed the parser accepted any
3712        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
3713        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
3714        // tripped the value to a *different* canonical string on the
3715        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
3716        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
3717        // — breaking the THEORY.md Part V render-determinism contract
3718        // on three typed slots at once. Same canonical-form discipline
3719        // `crate::limits::parse_duration` (818dd38, the immediate
3720        // predecessor on the peer `:limits :wall-clock` codec) applies;
3721        // this gate lifts the discipline onto the shared codec that
3722        // backs the remaining three typed-duration slots in caixa-core.
3723        //
3724        // Strict canonical form: every byte of the magnitude is an
3725        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
3726        // inputs the gate distinguishes "non-canonical-but-numeric"
3727        // (parses as f64 or i64 — surfaced with a self-locating
3728        // diagnostic naming the canonical authoring form, the
3729        // round-trip drift each rejected shape would produce on first
3730        // serialize, and the canonical-form remediation) from
3731        // "garbage" (parses as neither — surfaced with the existing
3732        // narrower "bad duration magnitude" wording so its diagnostic
3733        // shape remains stable for the parser-shape footgun case).
3734        // The pre-existing `num < 0.0` arm is now unreachable — the
3735        // digit-only gate strictly precedes magnitude parsing, and a
3736        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
3737        // non-canonical-but-numeric branch with the `-30` named
3738        // verbatim in the diagnostic rather than the prior
3739        // value-laundered "negative duration in \"-30s\"" wording.
3740        //
3741        // Routed through the lifted
3742        // [`crate::render::is_digit_only_magnitude`] predicate — the
3743        // same source of truth the four peer typed-magnitude codec
3744        // sites share.
3745        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
3746        if !digit_only {
3747            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
3748            if numeric {
3749                return Err(format!(
3750                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
3751                     canonical authoring form for the typed duration slots routed through \
3752                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3753                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3754                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
3755                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
3756                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
3757                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
3758                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
3759                     THEORY.md Part V render-determinism contract every typed slot carries. \
3760                     Pick an integer magnitude in the unit that divides cleanly (write \
3761                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
3762                ));
3763            }
3764            return Err(format!("bad duration magnitude in {s:?}"));
3765        }
3766        // Leading-zero arm — peer with the `rate_limit_codec` leading-
3767        // zero arm (4f46830) on the same canonical-form render-
3768        // determinism axis. The digit-only gate accepts `"030s"`,
3769        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
3770        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
3771        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
3772        // *different* canonical string on the next emit, breaking the
3773        // THEORY.md Part V render-determinism contract the same way
3774        // `"+30s"` did before the leading-`+` arm landed. The single-
3775        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
3776        // losslessly through `render` (`render(Duration::ZERO)` emits
3777        // `"0s"`) — the downstream semantic-zero gates (e.g.
3778        // `SupervisorError::ZeroRestartWindow` on
3779        // `:supervisor :restart-window`,
3780        // `AplicacaoError::PolicyTimeoutZero` /
3781        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
3782        // duration slots) refuse zero-magnitude authoring at the typed-
3783        // validate layer above, so the single-byte `"0"` stays in the
3784        // accepted set at this codec layer and the diagnostic
3785        // partitioning between canonical-form drift (this arm) and
3786        // semantic-zero (the downstream gates) remains stable.
3787        // Peer with the future leading-zero arms on the two remaining
3788        // typed-magnitude codecs the trajectory acknowledges:
3789        // `limits::parse_duration` backing `:limits :wall-clock`,
3790        // `limits::parse_byte_size` backing `:limits :memory` — each
3791        // carries the same canonical-form-drift class today; this
3792        // gate lands the discipline on the shared duration codec
3793        // first because the `rate_limit_codec` predecessor on the
3794        // same canonical-form-drift axis is the closest peer on the
3795        // trajectory.
3796        //
3797        // Routed through the lifted
3798        // [`crate::render::is_leading_zero_padded_magnitude`]
3799        // predicate — the same source of truth the four peer
3800        // typed-magnitude codec sites share.
3801        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
3802            return Err(format!(
3803                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
3804                 canonical authoring form for the typed duration slots routed through \
3805                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3806                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3807                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
3808                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
3809                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
3810                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
3811                 serialize — breaking the THEORY.md Part V render-determinism contract \
3812                 every typed slot carries. Strip the leading zeros (write \
3813                 `\"30s\"` instead of `\"030s\"`)"
3814            ));
3815        }
3816        // The digit-only gate guarantees every byte is `[0-9]`, and
3817        // the leading-zero arm above guarantees the magnitude is
3818        // either the single byte `"0"` or starts with `[1-9]`, so
3819        // the only way `u64::from_str` can fail here is overflow (the
3820        // magnitude exceeds `u64::MAX`). Surface that with an
3821        // overflow-shaped wording so the diagnostic names the offending
3822        // magnitude verbatim rather than collapsing onto the
3823        // non-canonical arm. The codec now operates on `u64` end-to-end
3824        // — every accepted magnitude is integer-exact; no f64 mantissa
3825        // drift between author-supplied magnitude and the consumer's
3826        // `Duration` value. Same shape `crate::limits::parse_duration`
3827        // (818dd38) carries on the peer `:limits :wall-clock` axis.
3828        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
3829            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
3830        })?;
3831        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
3832        // unit-arm dispatch through the canonical
3833        // [`crate::render::duration_from_integer_magnitude_and_unit`]
3834        // primitive — the substrate-side single-owner unit-dispatch
3835        // table every typed-duration codec in caixa-core routes
3836        // through (peer: `crate::limits::parse_duration` backing
3837        // `:limits :wall-clock`). Every unit conversion is integer-
3838        // exact for an integer magnitude; overflow surfaces via the
3839        // typed `DurationUnitError::Overflow { multiplier }`
3840        // discriminant so this arm reconstructs the pre-lift
3841        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
3842        // wording verbatim from `num` / `unit_trim` / the returned
3843        // `multiplier`, and the unknown-unit arm reconstructs the
3844        // pre-lift `"unknown duration unit \"<other>\""` wording from
3845        // the caller-scoped `unit_trim`. Load-bearing pinned by
3846        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
3847        let unit_trim = unit.trim();
3848        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
3849            |e| match e {
3850                crate::render::DurationUnitError::Overflow { multiplier } => format!(
3851                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
3852                ),
3853                crate::render::DurationUnitError::UnknownUnit => {
3854                    format!("unknown duration unit {unit_trim:?}")
3855                }
3856            },
3857        )?;
3858        Ok(dur)
3859    }
3860
3861    /// Render a [`Duration`] in the canonical pleme-io duration string
3862    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
3863    /// caixa typed-duration slot serializes to and the same form K8s
3864    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
3865    /// EnvoyConfig per-route timeouts both expect (an integer
3866    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
3867    /// `+`). Lifted to `pub` so caixa-side renderers
3868    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
3869    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
3870    /// emitter, the future caixa-otel collector pipeline emitter) can
3871    /// consume the same canonical formatter without re-inlining the
3872    /// magnitude/unit decision tree (and inheriting the same drift
3873    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
3874    /// downstream apply-time parsing in non-obvious ways).
3875    pub fn render(d: Duration) -> String {
3876        let total_ms = d.as_millis();
3877        if total_ms == 0 {
3878            return "0s".into();
3879        }
3880        if total_ms.is_multiple_of(3600 * 1000) {
3881            return format!("{}h", total_ms / (3600 * 1000));
3882        }
3883        if total_ms.is_multiple_of(60 * 1000) {
3884            return format!("{}m", total_ms / (60 * 1000));
3885        }
3886        if total_ms.is_multiple_of(1000) {
3887            return format!("{}s", total_ms / 1000);
3888        }
3889        format!("{total_ms}ms")
3890    }
3891
3892    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
3893    ///
3894    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
3895    /// largest divisor unit, so any sub-millisecond residue
3896    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
3897    /// §V.2.7 render-determinism contract:
3898    ///
3899    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
3900    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
3901    ///     `1_000_000` ns ≠ original `1_500_000` ns;
3902    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
3903    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
3904    ///     on every typed-`Duration` slot then rejects on re-validate.
3905    ///
3906    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
3907    /// the codec's round-trippable accepted set lives in exactly one place —
3908    /// every typed-`Duration` slot that routes through this shared codec
3909    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
3910    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
3911    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
3912    /// every typed-`Duration` slot whose own codec shares the same
3913    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
3914    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
3915    /// pair) calls this predicate from its `validate()` to bracket the
3916    /// accepted set against the codec's accepted set, structurally. Drift
3917    /// between the codec's granularity and any typed slot's accepted set is
3918    /// then a single-source-of-truth edit at this predicate rather than a
3919    /// silent round-trip break the next consumer discovers at apply time.
3920    ///
3921    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
3922    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
3923    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
3924    /// family — same "typed-slot's valid set matches its codec's accepted
3925    /// set, structurally" discipline carried at the codec layer.
3926    #[must_use]
3927    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
3928        d.subsec_nanos().is_multiple_of(1_000_000)
3929    }
3930}
3931
3932/// Required-Duration variant for fields that aren't Option<Duration>.
3933pub mod duration_codec_required {
3934    use super::Duration;
3935    use serde::{Deserialize, Deserializer, Serializer};
3936
3937    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
3938        s.serialize_str(&super::duration_codec::render(*v))
3939    }
3940
3941    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
3942        let s = String::deserialize(d)?;
3943        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
3944    }
3945}
3946
3947#[cfg(test)]
3948mod tests {
3949    use super::*;
3950
3951    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
3952        ChildSpec {
3953            caixa: name.into(),
3954            versao: ver.into(),
3955            restart,
3956        }
3957    }
3958
3959    #[test]
3960    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
3961        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
3962        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
3963        // posture. Each accessor projects the per-`:children :caixa`
3964        // / per-`:children :versao` [`String`] storage through the
3965        // `pub const fn` [`String::as_str`] (const-stable since Rust
3966        // 1.87, well within the workspace MSRV) — any future
3967        // accidental downgrade to non-`const` fails the corresponding
3968        // `<name>_via_const_fn` wrapper at caixa-core build time with
3969        // E0015 (`cannot call non-const method`), strictly stronger
3970        // than a runtime `assert!`. Sibling of the peer
3971        // per-M2/M3/universal-axis `String → &str` scalar-accessor
3972        // family pins on the sibling `const`-eval-surface passes
3973        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
3974        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
3975        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
3976        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
3977        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
3978        // [`crate::aplicacao::Entrada::destination`] at the M3
3979        // ingress axis,
3980        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
3981        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
3982        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
3983        // axis, and the per-`:contratos`
3984        // [`crate::aplicacao::WitContract::source`] /
3985        // [`crate::aplicacao::WitContract::destination`] /
3986        // [`crate::aplicacao::WitContract::world_ref`] trio the
3987        // sibling pin at 279823b already anchors).
3988        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
3989            c.nome()
3990        }
3991        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
3992            c.versao_requirement()
3993        }
3994        for (caixa, versao) in [
3995            ("worker-a", "^0.1"),
3996            ("worker-b", "~0.2.3"),
3997            ("collector", "*"),
3998        ] {
3999            let c = child(caixa, versao, RestartPolicy::Permanent);
4000            assert_eq!(nome_via_const_fn(&c), c.nome());
4001            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
4002            assert_eq!(c.nome(), caixa);
4003            assert_eq!(c.versao_requirement(), versao);
4004        }
4005    }
4006
4007    #[test]
4008    fn supervisor_children_slice_return_accessor_is_const_fn() {
4009        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
4010        // `const`-eval-surface posture. The accessor destructures the
4011        // per-`:children` `Vec<ChildSpec>` storage through the
4012        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
4013        // 1.66, well within the workspace MSRV) — any future
4014        // accidental downgrade to non-`const` fails
4015        // `children_via_const_fn` at caixa-core build time with E0015
4016        // (`cannot call non-const method`), strictly stronger than a
4017        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
4018        // `Vec → &[T]` slice-return accessor family pin
4019        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
4020        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
4021        // per-`:membros` / per-`:contratos` slice-return axes, and of
4022        // the peer M2 upgrade-appup axis pin
4023        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
4024        // on the per-`:upgrade-from :instructions` slice-return axis.
4025        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
4026            s.children()
4027        }
4028        // Sweep both the empty-children (leaf-supervisor with no
4029        // static children — the `SimpleOneForOne` dynamic-child
4030        // arm's canonical shape) and the populated-children
4031        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
4032        // arm's canonical shape) axes so the accessor carries a
4033        // const-dispatch pin on both arms.
4034        let s_empty = SupervisorSpec {
4035            estrategia: RestartStrategy::SimpleOneForOne,
4036            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4037            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4038            children: vec![],
4039        };
4040        assert!(children_via_const_fn(&s_empty).is_empty());
4041        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
4042        let s_full = SupervisorSpec {
4043            estrategia: RestartStrategy::OneForOne,
4044            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4045            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4046            children: vec![
4047                child("worker-a", "^0.1", RestartPolicy::Permanent),
4048                child("worker-b", "~0.2.3", RestartPolicy::Transient),
4049                child("collector", "*", RestartPolicy::Temporary),
4050            ],
4051        };
4052        assert_eq!(children_via_const_fn(&s_full).len(), 3);
4053        assert_eq!(children_via_const_fn(&s_full), s_full.children());
4054    }
4055
4056    #[test]
4057    fn default_has_one_for_one_and_5_restarts_in_60s() {
4058        let s = SupervisorSpec::default();
4059        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
4060        assert_eq!(s.max_restarts, 5);
4061        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
4062        assert!(s.children.is_empty());
4063    }
4064
4065    #[test]
4066    fn validate_one_for_one_requires_children() {
4067        let mut s = SupervisorSpec::default();
4068        s.children = vec![];
4069        assert!(matches!(
4070            s.validate().unwrap_err(),
4071            SupervisorError::NoChildren { .. }
4072        ));
4073        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
4074        s.validate().unwrap();
4075    }
4076
4077    #[test]
4078    fn validate_simple_one_for_one_forbids_static_children() {
4079        let mut s = SupervisorSpec {
4080            estrategia: RestartStrategy::SimpleOneForOne,
4081            ..SupervisorSpec::default()
4082        };
4083        s.children
4084            .push(child("w", "^0.1", RestartPolicy::Permanent));
4085        assert_eq!(
4086            s.validate().unwrap_err(),
4087            SupervisorError::SimpleOneForOneWithStaticChildren
4088        );
4089        s.children.clear();
4090        s.validate().unwrap();
4091    }
4092
4093    #[test]
4094    fn validate_rejects_zero_max_restarts() {
4095        let s = SupervisorSpec {
4096            max_restarts: 0,
4097            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4098            ..SupervisorSpec::default()
4099        };
4100        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
4101    }
4102
4103    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
4104    //
4105    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
4106    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
4107    // `:supervisor :max-restarts` axis — both fields are "trip the
4108    // next-higher protection layer after N events in a rolling window"
4109    // counters with identical degenerate-at-the-high-end shape, so the
4110    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
4111    // exactly as it lies in `1..=1000` on the breaker side.
4112
4113    #[test]
4114    fn validate_rejects_max_restarts_above_cap() {
4115        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
4116        // 1` is structurally one past the cap and silently passed
4117        // validate on every pre-gate codebase because the typed slot's
4118        // only check was the zero-floor arm. The no-op-supervisor vector
4119        // only surfaced at the runtime substrate (Erlang/OTP
4120        // MaxIntensity/Period ratio, the future wasm-operator's
4121        // per-supervisor restart-intensity counter) far from the source
4122        // caixa.lisp with no field naming the offending supervisor.
4123        let s = SupervisorSpec {
4124            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4125            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4126            ..SupervisorSpec::default()
4127        };
4128        assert_eq!(
4129            s.validate().unwrap_err(),
4130            SupervisorError::MaxRestartsExceedsCap {
4131                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4132            }
4133        );
4134    }
4135
4136    #[test]
4137    fn validate_rejects_max_restarts_far_above_cap() {
4138        // The `u32::MAX` worst case — the four-billion-restart
4139        // threshold a typo (`:max-restarts 4294967295`) or a
4140        // struct-literal copy-paste lands in the slot. Pin the cap
4141        // arm's coverage explicitly across the full `u32` overflow so
4142        // a future relaxation that drops the upper bound surfaces
4143        // here. Same shape every other typed-cap arm on this surface
4144        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
4145        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
4146        let s = SupervisorSpec {
4147            max_restarts: u32::MAX,
4148            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4149            ..SupervisorSpec::default()
4150        };
4151        assert_eq!(
4152            s.validate().unwrap_err(),
4153            SupervisorError::MaxRestartsExceedsCap {
4154                max_restarts: u32::MAX,
4155            }
4156        );
4157    }
4158
4159    #[test]
4160    fn validate_accepts_max_restarts_at_cap() {
4161        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
4162        // must validate. The cap is inclusive on the top edge,
4163        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
4164        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
4165        // discipline on the sibling capped axes. Pin the boundary
4166        // explicitly so a future off-by-one tightening
4167        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
4168        // here as a test failure rather than a silent contract
4169        // narrowing.
4170        let s = SupervisorSpec {
4171            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
4172            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4173            ..SupervisorSpec::default()
4174        };
4175        s.validate()
4176            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
4177    }
4178
4179    #[test]
4180    fn validate_accepts_max_restarts_typical_values() {
4181        // The documented production-playbook band positive-control
4182        // sweep — every value Erlang/OTP / Elixir / Riak Core /
4183        // RabbitMQ recommend (1..=100) must pass, plus a sweep
4184        // through the hyperscale band (200, 500, 1000) the cap
4185        // accepts. Pin the inclusive validated set explicitly so a
4186        // future tightening of the ceiling surfaces here.
4187        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
4188            let s = SupervisorSpec {
4189                max_restarts: n,
4190                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4191                ..SupervisorSpec::default()
4192            };
4193            s.validate()
4194                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
4195        }
4196    }
4197
4198    #[test]
4199    fn zero_max_restarts_takes_precedence_over_cap() {
4200        // The cross-arm ordering pin: `0` is structurally outside
4201        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
4202        // (cap), but the zero-floor diagnostic is the more
4203        // self-locating one (it directly names the counter-axis
4204        // remediation), so the validate gate must fire on zero first.
4205        // Same shape every other zero-then-shape ordering on this
4206        // surface uses (PolicyRetriesZero then
4207        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
4208        // PolicyBreakerMaxFailuresExceedsCap).
4209        let s = SupervisorSpec {
4210            max_restarts: 0,
4211            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4212            ..SupervisorSpec::default()
4213        };
4214        assert_eq!(
4215            s.validate().unwrap_err(),
4216            SupervisorError::ZeroMaxRestarts,
4217            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
4218        );
4219    }
4220
4221    #[test]
4222    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
4223        // The cross-arm ordering pin between the cap and the sibling
4224        // `:restart-window` gates (zero-window, canonical-window). A
4225        // supervisor carrying both an over-cap `max_restarts` AND a
4226        // structurally invalid window (zero, sub-ms) must surface the
4227        // cap diagnostic first — the cap arm is wired immediately
4228        // after the zero-restart arm and strictly before the window
4229        // arms, so the offending value the diagnostic names matches
4230        // the order the author would discover the gates by reading
4231        // top-to-bottom through `SupervisorSpec::validate`. Pin the
4232        // order so a future refactor that reorders the arms surfaces
4233        // here as a test failure rather than a silent diagnostic
4234        // regression. Peer of
4235        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
4236        // on the sibling `:politicas :circuit-breaker` slot.
4237        let s = SupervisorSpec {
4238            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4239            restart_window: Some(Duration::ZERO),
4240            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4241            ..SupervisorSpec::default()
4242        };
4243        assert_eq!(
4244            s.validate().unwrap_err(),
4245            SupervisorError::MaxRestartsExceedsCap {
4246                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4247            },
4248            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4249        );
4250    }
4251
4252    #[test]
4253    fn max_restarts_cap_diagnostic_carries_offending_value() {
4254        // The diagnostic-shape pin: the offending `u32` is carried
4255        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
4256        // variant so the surfaced error message names the value the
4257        // author wrote (`":supervisor :max-restarts (50000) exceeds the
4258        // supervisor-policy ceiling …"`), not just the cap. Same
4259        // self-locating diagnostic shape every other typed-cap arm on
4260        // this surface carries
4261        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
4262        // the offending failure count verbatim,
4263        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
4264        // retries count verbatim).
4265        let s = SupervisorSpec {
4266            max_restarts: 50_000,
4267            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4268            ..SupervisorSpec::default()
4269        };
4270        let err = s.validate().unwrap_err();
4271        assert!(
4272            matches!(
4273                err,
4274                SupervisorError::MaxRestartsExceedsCap {
4275                    max_restarts: 50_000
4276                }
4277            ),
4278            "got {err:?}"
4279        );
4280        let msg = err.to_string();
4281        assert!(
4282            msg.contains("50000"),
4283            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
4284        );
4285    }
4286
4287    #[test]
4288    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
4289        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
4290        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
4291        // half of Learn You Some Erlang's worker-supervisor default,
4292        // sibling of the `60s` `Period` half that the paired
4293        // [`Default for SupervisorSpec`] impl already pins on the
4294        // sibling `restart_window` axis. Pinning the literal here
4295        // surfaces a future rebrand (a tightening to Elixir's `3`,
4296        // a widening to a per-cluster overlay the operator pins
4297        // through a future `:max-restarts-overrides` slot) as a
4298        // deliberate test edit, not a silent contract migration.
4299        // Peer of the sibling
4300        // [`supervisor_max_restarts_cap_pins_canonical_value`]
4301        // upper-bracket pin on the same axis.
4302        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
4303    }
4304
4305    #[test]
4306    fn default_max_restarts_helper_routes_through_lifted_default() {
4307        // Composition pin: the private `default_max_restarts()`
4308        // serde-`#[serde(default = "…")]` helper on
4309        // [`SupervisorSpec::max_restarts`] must route through the
4310        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4311        // typed `pub const` rather than a raw `5` literal. Prior to
4312        // the lift the helper carried an inline `5` with no compile-
4313        // time link back to the shared default, so the wire-format
4314        // author-omitted arm and the caixa-core
4315        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
4316        // arm could silently split on any future default rebrand.
4317        // Byte-parity against the lifted constant closes the split.
4318        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
4319    }
4320
4321    #[test]
4322    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
4323        // Composition pin: the [`Default for SupervisorSpec`] impl's
4324        // struct-literal `max_restarts` field must route through the
4325        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4326        // typed `pub const` (via the private helper this test's
4327        // sibling `default_max_restarts_helper_routes_through_lifted_default`
4328        // already pins onto the constant). Structurally: every
4329        // `SupervisorSpec::default()` call must yield a
4330        // `max_restarts` field byte-equal to the lifted constant
4331        // (the two paired defaults — the serde-side wire-format arm
4332        // and the struct-literal default arm — cannot silently split
4333        // on any future default rebrand). Peer of the sibling
4334        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
4335        // — this pin closes the byte-parity arm on the two paired
4336        // altitude entry points onto the shared substrate constant.
4337        assert_eq!(
4338            SupervisorSpec::default().max_restarts(),
4339            SUPERVISOR_MAX_RESTARTS_DEFAULT,
4340        );
4341    }
4342
4343    #[test]
4344    fn supervisor_restart_window_default_pins_otp_canonical_value() {
4345        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
4346        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
4347        // Learn You Some Erlang's worker-supervisor default, paired
4348        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
4349        // `MaxIntensity` half this constant is the sliding-window
4350        // denominator of on the same `MaxIntensity / Period`
4351        // restart-intensity ratio. Pinning the literal here surfaces a
4352        // future coherent rebrand of the paired default (Elixir's
4353        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
4354        // the operator pins through a future
4355        // `:restart-window-overrides` slot) as a deliberate test edit,
4356        // not a silent contract migration. Peer of the sibling
4357        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
4358        // paired-half pin on the same OTP-canonical default and the
4359        // [`supervisor_restart_window_cap_pins_canonical_value`]
4360        // upper-bracket pin on the same axis.
4361        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
4362    }
4363
4364    #[test]
4365    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
4366        // Composition pin: the [`Default for SupervisorSpec`] impl's
4367        // struct-literal `restart_window` field must route through the
4368        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4369        // typed `pub const` rather than a raw
4370        // `Duration::from_secs(60)` literal. Prior to this lift the
4371        // paired `{intensity, 5, 60}` OTP-canonical default was split
4372        // across two altitudes with no compile-time link between the
4373        // halves — the `MaxIntensity` half rode through the lifted
4374        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
4375        // `Period` half rode as an open-coded literal at the
4376        // composition site, so a future coherent rebrand of the paired
4377        // canonical would have had to migrate one half through the
4378        // constant and the other through a raw literal in lockstep.
4379        // Byte-parity against the lifted constant on the `Period` half
4380        // closes the split — the paired OTP-canonical default now
4381        // migrates as one unit on any future axis change. Peer of the
4382        // sibling
4383        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4384        // byte-parity pin on the paired `MaxIntensity` half.
4385        assert_eq!(
4386            SupervisorSpec::default().restart_window(),
4387            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4388        );
4389    }
4390
4391    #[test]
4392    fn supervisor_estrategia_default_pins_otp_canonical_value() {
4393        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
4394        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
4395        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
4396        // canonical default, paired with the sibling
4397        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
4398        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
4399        // this constant is the strategy discriminator of on the same
4400        // OTP-canonical worker-supervisor default. Pinning the arm here
4401        // surfaces a future coherent rebrand of the paired triple (Elixir's
4402        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
4403        // intensity/period axes leaving this strategy arm untouched, an OTP
4404        // `rest_for_one` widening once the substrate discovers startup-
4405        // order-coupled child cohorts as the more common worker-supervisor
4406        // shape, a per-cluster overlay the operator pins through a future
4407        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
4408        // supervision-canary roadmap acknowledges) as a deliberate test
4409        // edit, not a silent contract migration. Peer of the sibling
4410        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
4411        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4412        // paired-half pins on the same OTP-canonical default.
4413        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
4414    }
4415
4416    #[test]
4417    fn restart_strategy_default_routes_through_lifted_default() {
4418        // Composition pin: the [`Default for RestartStrategy`] impl's
4419        // return arm must route through the substrate-canonical
4420        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
4421        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
4422        // an inline `Self::OneForOne` with no compile-time link back to
4423        // the shared OTP-canonical `one_for_one` strategy the paired
4424        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
4425        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
4426        // `.unwrap_or_default()` (now
4427        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
4428        // so a future rebrand of the OTP-canonical strategy default (an
4429        // OTP `rest_for_one` widening once the substrate discovers
4430        // startup-order-coupled child cohorts as the more common worker-
4431        // supervisor shape, a per-cluster overlay the operator pins
4432        // through a future `:estrategia-overrides` slot) would have had to
4433        // be threaded through the `Default` impl and the two peer routes
4434        // in lockstep or the three consumers would silently split. Byte-
4435        // parity against the lifted constant closes the split. Peer of
4436        // the sibling
4437        // [`default_max_restarts_helper_routes_through_lifted_default`] +
4438        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4439        // composition pins on the paired `MaxIntensity` + `Period` halves.
4440        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
4441    }
4442
4443    #[test]
4444    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
4445        // Composition pin: the [`Default for SupervisorSpec`] impl's
4446        // struct-literal `estrategia` field must route through the
4447        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
4448        // `pub const` (either directly, or via the
4449        // [`RestartStrategy::default`] impl that the sibling
4450        // `restart_strategy_default_routes_through_lifted_default` pin
4451        // already routes onto the constant). Structurally: every
4452        // `SupervisorSpec::default()` call must yield an `estrategia`
4453        // field byte-equal to the lifted constant (the three paired
4454        // defaults — the [`Default for RestartStrategy`] impl arm, the
4455        // struct-literal default arm here, and the
4456        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
4457        // silently split on any future default rebrand). Peer of the
4458        // sibling
4459        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4460        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4461        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
4462        // of the same `SupervisorSpec::default()` composed altitude.
4463        assert_eq!(
4464            SupervisorSpec::default().estrategia(),
4465            SUPERVISOR_ESTRATEGIA_DEFAULT,
4466        );
4467    }
4468
4469    #[test]
4470    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
4471        // Composition pin: the [`Default for SupervisorSpec`] impl must
4472        // route through the substrate-canonical
4473        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
4474        // rather than a re-hand-authored struct-literal cascade. Sharpens
4475        // the sibling per-arm
4476        // `supervisor_spec_default_*_routes_through_lifted_default` pins
4477        // from a per-field lift into a whole-struct one-source-of-truth
4478        // pin — the derived-until-now [`Default::default`] and the
4479        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
4480        // construction, not by coincidence.
4481        //
4482        // A future extension of the OTP-canonical baseline (a fifth
4483        // `restart_intensity` field the Erlang/OTP `#supervisor` record
4484        // grows, a per-child-cohort split of the `restart_window` /
4485        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
4486        // CR materializer's admission-time overlay pass) reaches both
4487        // paths through exactly one edit on
4488        // [`SupervisorSpec::otp_canonical`] — the derived path could
4489        // silently disagree with the constructor's shape on any new
4490        // field whose [`Default::default`] resolves to a different arm
4491        // than the OTP-canonical baseline the constructor names, while
4492        // this delegated impl reaches the constructor directly and
4493        // picks up every future extension by construction.
4494        //
4495        // Fourth peer on the M2 / M3 typed-slot-spec
4496        // [`Default`]-through-const-ctor fold family — sibling of the
4497        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
4498        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
4499        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
4500        // (91641a4), and [`crate::BehaviorSpec`]
4501        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
4502        // per-`Option`-only-typed-slot folds — extended here onto the
4503        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
4504        // is not "everything `None`" but the Erlang/OTP-canonical
4505        // `{one_for_one, 5, 60}` worker-supervisor triple.
4506        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
4507    }
4508
4509    #[test]
4510    fn supervisor_spec_otp_canonical_byte_equals_default() {
4511        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
4512        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
4513        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
4514        // pin already asserts against the [`Default::default`] path.
4515        // Sharpens the pair-invariant into a per-constructor pin so a
4516        // future extension of [`SupervisorSpec`] with a fifth field
4517        // whose OTP-canonical shape is non-`Default::default`-equivalent
4518        // trips at caixa-core test time rather than at a downstream
4519        // consumer that composed [`SupervisorSpec::otp_canonical`] with
4520        // [`SupervisorSpec::validate`] as its "canonical baseline
4521        // seed".
4522        let canonical = SupervisorSpec::otp_canonical();
4523        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
4524        assert_eq!(canonical.max_restarts, 5);
4525        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
4526        assert!(canonical.children.is_empty());
4527    }
4528
4529    #[test]
4530    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
4531        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
4532        // remain callable from a `const`-bound position so downstream
4533        // `const`-context callers wanting a canonical OTP-baseline seed
4534        // can construct one at compile time without runtime dispatch on
4535        // the derived [`Default::default`]. Peer of the sibling
4536        // `pub const fn` [`crate::LimitsSpec::empty`] /
4537        // [`crate::aplicacao::MeshPolicy::empty`] /
4538        // [`crate::BehaviorSpec::empty`] constructors on the sibling
4539        // typed-slot-spec `pub const fn` axis. If a future edit breaks
4540        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
4541        // (a non-`const` field-default helper, a non-`const`-stable
4542        // container type promotion), this evaluation fails at
4543        // build time on this file rather than at a downstream
4544        // `const`-context call site.
4545        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
4546        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
4547        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
4548        assert_eq!(
4549            CANONICAL.restart_window,
4550            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4551        );
4552        assert!(CANONICAL.children.is_empty());
4553    }
4554
4555    #[test]
4556    fn supervisor_child_restart_default_pins_otp_canonical_value() {
4557        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
4558        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
4559        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
4560        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
4561        // half of the same OTP-shape supervisor-tree default set whose
4562        // per-`:supervisor` halves the sibling
4563        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
4564        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
4565        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
4566        // arm here surfaces a future rebrand of the per-child default (an
4567        // OTP-`transient` widening once the substrate discovers clean-
4568        // completion-aware children as the more common child shape, a
4569        // per-cluster overlay the operator pins through a future
4570        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
4571        // supervision-canary roadmap acknowledges) as a deliberate test
4572        // edit, not a silent contract migration. Peer of the sibling
4573        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
4574        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
4575        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4576        // value pins on the per-`:supervisor` halves.
4577        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
4578    }
4579
4580    #[test]
4581    fn restart_policy_default_routes_through_lifted_default() {
4582        // Composition pin: the [`Default for RestartPolicy`] impl's return
4583        // arm must route through the substrate-canonical
4584        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
4585        // than a raw `Self::Permanent` arm. Prior to the lift the impl
4586        // carried an inline `Self::Permanent` with no compile-time link
4587        // back to the OTP-shape supervisor-tree default set whose three
4588        // per-`:supervisor` halves already rode through lifted constants
4589        // — so a future coherent rebrand of the set would have had to
4590        // migrate three halves through typed constants and this fourth
4591        // through a raw enum arm in lockstep or the supervisor-level and
4592        // child-level defaults would silently drift apart. Byte-parity
4593        // against the lifted constant closes the split. Peer of the
4594        // sibling
4595        // [`restart_strategy_default_routes_through_lifted_default`]
4596        // composition pin on the per-`:supervisor` `:estrategia` axis.
4597        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
4598    }
4599
4600    #[test]
4601    fn child_spec_serde_default_restart_routes_through_lifted_default() {
4602        // Composition pin: the serde-side `#[serde(default)]` on
4603        // [`ChildSpec::restart`] — the wire-format author-omitted
4604        // `:children :restart` arm — must resolve onto the substrate-
4605        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
4606        // (via the [`Default for RestartPolicy`] impl the sibling
4607        // `restart_policy_default_routes_through_lifted_default` pin
4608        // already routes onto the constant). Structurally: a `ChildSpec`
4609        // deserialized from a payload that omits the `restart` key must
4610        // yield a `restart` field byte-equal to the lifted constant, so
4611        // the wire-format author-omitted arm and the
4612        // [`RestartPolicy::default`] impl arm cannot silently split on any
4613        // future default rebrand. Peer of the sibling
4614        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
4615        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4616        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4617        // byte-parity pins on the per-`:supervisor` halves of the same
4618        // author-omitted-slot resolution surface.
4619        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
4620            .expect("ChildSpec must deserialize with the restart key omitted");
4621        assert_eq!(
4622            omitted.restart(),
4623            SUPERVISOR_CHILD_RESTART_DEFAULT,
4624            "an author-omitted :children :restart slot must degrade onto \
4625             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
4626             {:?}, expected {:?})",
4627            omitted.restart(),
4628            SUPERVISOR_CHILD_RESTART_DEFAULT,
4629        );
4630    }
4631
4632    #[test]
4633    fn supervisor_max_restarts_cap_pins_canonical_value() {
4634        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
4635        // 1000 — the same ceiling the peer
4636        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
4637        // `:politicas :circuit-breaker :max-failures` axis (both are
4638        // "trip the next-higher protection layer after N events in a
4639        // rolling window" counters with identical
4640        // degenerate-at-the-high-end shape; uniform top edge so the
4641        // M4 CR materializers and the wasm-operator reconciler reach
4642        // for either field knowing the value is in `1..=1000`). Two
4643        // orders of magnitude above every documented Erlang/OTP /
4644        // Elixir / Riak Core / RabbitMQ production-playbook
4645        // recommendation band and below the clearly-pathological
4646        // "effectively no escalation" floor (10_000, 100_000,
4647        // u32::MAX). Pinning the literal value here surfaces a future
4648        // drift (a relaxation to 10_000, a tightening to 100) as a
4649        // deliberate test edit, not a silent contract narrowing.
4650        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
4651    }
4652
4653    #[test]
4654    fn validate_rejects_empty_child_name() {
4655        let s = SupervisorSpec {
4656            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4657            ..SupervisorSpec::default()
4658        };
4659        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
4660    }
4661
4662    #[test]
4663    fn validate_rejects_empty_child_version() {
4664        let s = SupervisorSpec {
4665            children: vec![child("w", "", RestartPolicy::Permanent)],
4666            ..SupervisorSpec::default()
4667        };
4668        assert!(matches!(
4669            s.validate().unwrap_err(),
4670            SupervisorError::EmptyChildVersion { .. }
4671        ));
4672    }
4673
4674    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
4675
4676    #[test]
4677    fn validate_rejects_invalid_child_versao_requirement() {
4678        // The fail-before-pass-after pin: a non-empty but malformed
4679        // semver requirement (`"^bad-version"`) silently passed
4680        // `validate()` on every pre-gate codebase because the prior
4681        // shape only refused the empty string. The parse failure
4682        // surfaced far downstream at lacre-resolve time with a
4683        // `semver::Error` that didn't name which `:children` entry
4684        // carried the typo. The new gate moves the check to caixa-build
4685        // time at the source caixa.lisp — the third `:versao` typed
4686        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
4687        // structural parity.
4688        let s = SupervisorSpec {
4689            children: vec![
4690                child("worker", "^0.1", RestartPolicy::Permanent),
4691                child("cache", "^bad-version", RestartPolicy::Transient),
4692            ],
4693            ..SupervisorSpec::default()
4694        };
4695        let err = s.validate().unwrap_err();
4696        assert!(
4697            matches!(
4698                err,
4699                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4700                    if caixa == "cache" && versao == "^bad-version"
4701            ),
4702            "got {err:?}"
4703        );
4704    }
4705
4706    #[test]
4707    fn validate_rejects_child_versao_with_double_caret_typo() {
4708        // `"^^0.1"` is the canonical doubled-caret typo — looks
4709        // Cargo-shaped on first glance but fails the parser because
4710        // semver doesn't accept stacked operators. Pin this
4711        // adjacent-shape footgun explicitly so a future relaxation that
4712        // accepts "looks-canonical-but-isn't" forms surfaces here.
4713        let s = SupervisorSpec {
4714            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
4715            ..SupervisorSpec::default()
4716        };
4717        let err = s.validate().unwrap_err();
4718        assert!(
4719            matches!(
4720                err,
4721                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4722                    if caixa == "worker" && versao == "^^0.1"
4723            ),
4724            "got {err:?}"
4725        );
4726    }
4727
4728    #[test]
4729    fn validate_rejects_child_versao_with_v_prefixed_tag() {
4730        // `"v0.1"` is the canonical "git-tag-shape leaking into the
4731        // semver requirement slot" typo — an author copies the
4732        // publish-side git-tag string verbatim into `:versao`, but
4733        // Cargo's semver parser rejects the leading `v`. Same
4734        // adjacent-shape footgun pinned for `:membros :versao`
4735        // (9888b13).
4736        let s = SupervisorSpec {
4737            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
4738            ..SupervisorSpec::default()
4739        };
4740        let err = s.validate().unwrap_err();
4741        assert!(
4742            matches!(
4743                err,
4744                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4745                    if caixa == "worker" && versao == "v0.1"
4746            ),
4747            "got {err:?}"
4748        );
4749    }
4750
4751    #[test]
4752    fn validate_accepts_canonical_child_versao_forms() {
4753        // The Cargo-shaped requirement forms `:deps :versao` and
4754        // `:membros :versao` already accept via
4755        // `crate::parse_requirement` must pass the children gate
4756        // without re-validating at the resolver layer. Pin every leg so
4757        // a future tightening of the canonical set surfaces here as a
4758        // test failure.
4759        for form in [
4760            "^0.1",      // caret — minor-range pin (the most common shape)
4761            "~0.1.2",    // tilde — patch-range pin
4762            "0.1.0",     // exact — single-version pin
4763            "*",         // wildcard — any version (semver::VersionReq::STAR)
4764            ">=0.1, <2", // multi-range — comma-separated comparators
4765        ] {
4766            let s = SupervisorSpec {
4767                children: vec![child("worker", form, RestartPolicy::Permanent)],
4768                ..SupervisorSpec::default()
4769            };
4770            s.validate()
4771                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4772        }
4773    }
4774
4775    #[test]
4776    fn child_versao_empty_takes_precedence_over_invalid() {
4777        // Order pin: the existing `EmptyChildVersion` diagnostic (which
4778        // doesn't try to parse) fires before the new
4779        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
4780        // `:versao` keeps its narrower error message —
4781        // `parse_requirement` would also reject `""`, but the
4782        // empty-string arm is the more self-locating diagnostic for the
4783        // author. Same ordering discipline as
4784        // `membro_versao_empty_takes_precedence_over_invalid` in
4785        // aplicacao.rs.
4786        let s = SupervisorSpec {
4787            children: vec![child("worker", "", RestartPolicy::Permanent)],
4788            ..SupervisorSpec::default()
4789        };
4790        let err = s.validate().unwrap_err();
4791        assert!(
4792            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
4793            "got {err:?}"
4794        );
4795    }
4796
4797    #[test]
4798    fn child_versao_invalid_fires_before_duplicate_check() {
4799        // Order pin: a malformed requirement on a non-duplicate entry
4800        // surfaces *its own* diagnostic (which names the offending
4801        // `:versao` string), even when a later entry would otherwise
4802        // collapse onto an earlier name. The per-entry shape gate runs
4803        // inline before the duplicate-key insert — parallel to
4804        // `membro_versao_invalid_fires_before_duplicate_check` in
4805        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
4806        let s = SupervisorSpec {
4807            children: vec![
4808                child("worker", "^bad", RestartPolicy::Permanent),
4809                child("cache", "^0.1", RestartPolicy::Transient),
4810                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4811            ],
4812            ..SupervisorSpec::default()
4813        };
4814        let err = s.validate().unwrap_err();
4815        assert!(
4816            matches!(
4817                err,
4818                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
4819            ),
4820            "got {err:?}"
4821        );
4822    }
4823
4824    #[test]
4825    fn child_versao_invalid_diagnostic_carries_offending_versao() {
4826        // The diagnostic-shape pin: the error names the offending
4827        // `:versao` value verbatim so the author can grep their
4828        // caixa.lisp without re-running the build, and carries a
4829        // non-empty `reason` from `semver::VersionReq::parse` so the
4830        // parser's own wording flows through to the diagnostic.
4831        let s = SupervisorSpec {
4832            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
4833            ..SupervisorSpec::default()
4834        };
4835        let err = s.validate().unwrap_err();
4836        let SupervisorError::ChildVersaoInvalid {
4837            caixa,
4838            versao,
4839            reason,
4840        } = err
4841        else {
4842            panic!("expected ChildVersaoInvalid, got other variant");
4843        };
4844        assert_eq!(caixa, "worker");
4845        assert_eq!(versao, "not-a-req");
4846        assert!(
4847            !reason.is_empty(),
4848            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
4849        );
4850    }
4851
4852    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
4853
4854    #[test]
4855    fn validate_rejects_child_caixa_with_uppercase() {
4856        // The canonical "I copied the Servico's display name verbatim"
4857        // typo — child caixa names are lowercase per K8s DNS-1123 label
4858        // rule. The diagnostic names the offending name and suggests the
4859        // lower-cased fix in one edit, mirroring the
4860        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
4861        let s = SupervisorSpec {
4862            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
4863            ..SupervisorSpec::default()
4864        };
4865        let err = s.validate().unwrap_err();
4866        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4867            panic!("expected ChildCaixaInvalid, got other variant");
4868        };
4869        assert_eq!(caixa, "Worker");
4870        assert!(
4871            reason.contains("uppercase"),
4872            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
4873        );
4874        assert!(
4875            reason.contains("\"worker\""),
4876            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
4877        );
4878    }
4879
4880    #[test]
4881    fn validate_rejects_child_caixa_with_underscore() {
4882        // The canonical "I'm thinking of a Python module / Postgres
4883        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
4884        // label schema. K8s rejects `metadata.name: my_worker` at
4885        // admission time with an opaque `field is invalid` (no source-
4886        // citing diagnostic). The gate moves it to caixa-build time.
4887        let s = SupervisorSpec {
4888            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
4889            ..SupervisorSpec::default()
4890        };
4891        let err = s.validate().unwrap_err();
4892        assert!(
4893            matches!(
4894                err,
4895                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4896                    if caixa == "my_worker" && reason.contains('_')
4897            ),
4898            "got {err:?}"
4899        );
4900    }
4901
4902    #[test]
4903    fn validate_rejects_child_caixa_with_dot() {
4904        // A `:children :caixa` entry is a single DNS-1123 label, not a
4905        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
4906        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
4907        // (3f9d7a0) on the peer name axis.
4908        let s = SupervisorSpec {
4909            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
4910            ..SupervisorSpec::default()
4911        };
4912        let err = s.validate().unwrap_err();
4913        assert!(
4914            matches!(
4915                err,
4916                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4917                    if caixa == "team.worker" && reason.contains('.')
4918            ),
4919            "got {err:?}"
4920        );
4921    }
4922
4923    #[test]
4924    fn validate_rejects_child_caixa_with_leading_hyphen() {
4925        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
4926        // with an alphanumeric. The K8s apiserver rejects `-worker`
4927        // outright; the renderer would emit a `metadata.name: "-worker"`
4928        // that fails admission far from the source caixa.lisp.
4929        let s = SupervisorSpec {
4930            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
4931            ..SupervisorSpec::default()
4932        };
4933        let err = s.validate().unwrap_err();
4934        assert!(
4935            matches!(
4936                err,
4937                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4938                    if caixa == "-worker" && reason.contains("start and end")
4939            ),
4940            "got {err:?}"
4941        );
4942    }
4943
4944    #[test]
4945    fn validate_rejects_child_caixa_with_trailing_hyphen() {
4946        // The symmetric arm of the boundary rule. Pin separately so
4947        // both ends of the label are covered against a future relaxation
4948        // that only checks one boundary.
4949        let s = SupervisorSpec {
4950            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
4951            ..SupervisorSpec::default()
4952        };
4953        let err = s.validate().unwrap_err();
4954        assert!(
4955            matches!(
4956                err,
4957                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4958                    if caixa == "worker-"
4959            ),
4960            "got {err:?}"
4961        );
4962    }
4963
4964    #[test]
4965    fn validate_rejects_child_caixa_with_unicode() {
4966        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
4967        // (`xn--…`) by the author before it reaches K8s. The byte-by-
4968        // byte ASCII validity check rejects multi-byte UTF-8 sequences
4969        // by the first byte that fails the `[a-z0-9-]` predicate.
4970        let s = SupervisorSpec {
4971            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
4972            ..SupervisorSpec::default()
4973        };
4974        let err = s.validate().unwrap_err();
4975        assert!(
4976            matches!(
4977                err,
4978                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4979                    if caixa == "café"
4980            ),
4981            "got {err:?}"
4982        );
4983    }
4984
4985    #[test]
4986    fn validate_rejects_child_caixa_with_whitespace() {
4987        // Whitespace is the canonical "I pasted from a sketch / doc"
4988        // footgun. The apiserver rejects every `metadata.name` value
4989        // carrying whitespace; pin the gate fires at the right boundary.
4990        let s = SupervisorSpec {
4991            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
4992            ..SupervisorSpec::default()
4993        };
4994        let err = s.validate().unwrap_err();
4995        assert!(
4996            matches!(
4997                err,
4998                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4999                    if caixa == "my worker"
5000            ),
5001            "got {err:?}"
5002        );
5003    }
5004
5005    #[test]
5006    fn validate_rejects_child_caixa_too_long() {
5007        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
5008        // 63 bytes; the K8s apiserver rejects every `metadata.name`
5009        // axis over the limit at admission time. The diagnostic names
5010        // both the cap and the actual length so the author can shorten
5011        // in one edit, mirroring `rejects_membro_caixa_too_long`
5012        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
5013        let too_long = "a".repeat(64);
5014        let s = SupervisorSpec {
5015            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
5016            ..SupervisorSpec::default()
5017        };
5018        let err = s.validate().unwrap_err();
5019        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5020            panic!("expected ChildCaixaInvalid, got other variant");
5021        };
5022        assert_eq!(caixa, too_long);
5023        assert!(
5024            reason.contains("63"),
5025            "diagnostic must name the 63-byte cap (got: {reason:?})"
5026        );
5027        assert!(
5028            reason.contains("64"),
5029            "diagnostic must name the actual length (got: {reason:?})"
5030        );
5031    }
5032
5033    #[test]
5034    fn child_caixa_max_length_validates() {
5035        // The 63-byte boundary control pin — exactly-at-the-cap is
5036        // accepted, mirroring `membro_caixa_max_length_validates`
5037        // (3f9d7a0) and `placement_cluster_max_length_validates`
5038        // (6cbb900). Pinned separately so a future off-by-one tightening
5039        // surfaces here.
5040        let max_label = "a".repeat(63);
5041        let s = SupervisorSpec {
5042            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
5043            ..SupervisorSpec::default()
5044        };
5045        s.validate().unwrap();
5046    }
5047
5048    #[test]
5049    fn validate_accepts_canonical_child_caixa_forms() {
5050        // The realistic shapes a supervised child's `:caixa` carries —
5051        // single-word `worker`, version-suffixed `cache-v2`, single-char
5052        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
5053        // `payment-retry`, all-digit `0`. Pin every leg so a future
5054        // tightening (e.g. requiring a leading lowercase letter) surfaces
5055        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
5056        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
5057        // (6cbb900).
5058        for form in [
5059            "worker",
5060            "cache-v2",
5061            "a",
5062            "db",
5063            "2-pool",
5064            "payment-retry",
5065            "0",
5066        ] {
5067            let s = SupervisorSpec {
5068                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
5069                ..SupervisorSpec::default()
5070            };
5071            s.validate()
5072                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5073        }
5074    }
5075
5076    #[test]
5077    fn child_caixa_empty_takes_precedence_over_invalid() {
5078        // Order pin: the existing `EmptyChildName` diagnostic (which
5079        // doesn't try to parse the DNS-1123 shape) fires before the new
5080        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
5081        // its narrower error message — `is_dns_1123_label` would reject
5082        // the empty string too (boundary check on the first byte), but
5083        // the empty-string arm is the more self-locating diagnostic for
5084        // the author. Same ordering discipline as
5085        // `membro_caixa_empty_takes_precedence_over_invalid` in
5086        // aplicacao.rs.
5087        let s = SupervisorSpec {
5088            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5089            ..SupervisorSpec::default()
5090        };
5091        let err = s.validate().unwrap_err();
5092        assert_eq!(err, SupervisorError::EmptyChildName);
5093    }
5094
5095    #[test]
5096    fn child_caixa_invalid_fires_before_versao_check() {
5097        // Order pin: the per-axis shape gate runs inline before the
5098        // per-entry versao check, so a malformed `:caixa` on an entry
5099        // whose `:versao` would also fail surfaces the more self-
5100        // locating name-axis diagnostic first. Parallel to
5101        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
5102        // and `placement_cluster_invalid_fires_before_duplicate_check`
5103        // (6cbb900).
5104        let s = SupervisorSpec {
5105            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
5106            ..SupervisorSpec::default()
5107        };
5108        let err = s.validate().unwrap_err();
5109        assert!(
5110            matches!(
5111                err,
5112                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
5113            ),
5114            "got {err:?}"
5115        );
5116    }
5117
5118    #[test]
5119    fn child_caixa_invalid_fires_before_duplicate_check() {
5120        // Order pin: a malformed name on a non-duplicate entry surfaces
5121        // its own diagnostic, even when a later entry would otherwise
5122        // collapse onto an earlier name. The per-entry shape gate runs
5123        // inline before the duplicate-key HashSet insert, mirroring
5124        // `placement_cluster_invalid_fires_before_duplicate_check`
5125        // (6cbb900).
5126        let s = SupervisorSpec {
5127            children: vec![
5128                child("Worker", "^0.1", RestartPolicy::Permanent),
5129                child("cache", "^0.1", RestartPolicy::Transient),
5130                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5131            ],
5132            ..SupervisorSpec::default()
5133        };
5134        let err = s.validate().unwrap_err();
5135        assert!(
5136            matches!(
5137                err,
5138                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
5139            ),
5140            "got {err:?}"
5141        );
5142    }
5143
5144    #[test]
5145    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
5146        // The diagnostic-shape pin: the error names the offending
5147        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
5148        // the author can grep their caixa.lisp without re-running the
5149        // build. Mirrors the diagnostic-shape sweep on every prior
5150        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
5151        let s = SupervisorSpec {
5152            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
5153            ..SupervisorSpec::default()
5154        };
5155        let err = s.validate().unwrap_err();
5156        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5157            panic!("expected ChildCaixaInvalid, got other variant");
5158        };
5159        assert_eq!(caixa, "My_Worker");
5160        assert!(
5161            !reason.is_empty(),
5162            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
5163        );
5164    }
5165
5166    // ── value-shape: zero restart_window + duplicate child names ──────────
5167
5168    #[test]
5169    fn validate_accepts_none_restart_window() {
5170        // Omitted `:restart-window` is the "never reset" sentinel —
5171        // valid by design. Mirrors :limits axes where None = unbounded.
5172        let s = SupervisorSpec {
5173            restart_window: None,
5174            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5175            ..SupervisorSpec::default()
5176        };
5177        s.validate().unwrap();
5178    }
5179
5180    #[test]
5181    fn validate_rejects_zero_restart_window() {
5182        // Same "0 means the opposite of what you think" footgun closed
5183        // for :politicas :timeout (Envoy treats 0s as infinite) and
5184        // :limits :wall-clock (wasmtime traps before the call starts).
5185        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
5186        let s = SupervisorSpec {
5187            restart_window: Some(Duration::ZERO),
5188            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5189            ..SupervisorSpec::default()
5190        };
5191        assert_eq!(
5192            s.validate().unwrap_err(),
5193            SupervisorError::RestartWindowZero
5194        );
5195    }
5196
5197    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
5198    //
5199    // The fourth (and last) typed-`Duration` axis in caixa-core to get
5200    // the integer-millisecond canonical-form gate — peer with
5201    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
5202    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
5203    // path is already gated at the shared codec layer (see
5204    // `restart_window_serde_rejects_fractional_seconds`); this arm
5205    // closes the programmatic-struct-literal path the codec gate can't
5206    // see.
5207
5208    #[test]
5209    fn validate_rejects_sub_millisecond_restart_window() {
5210        // The fail-before-pass-after pin: a programmatic
5211        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
5212        // `validate` on every pre-gate codebase, then truncated to
5213        // `as_millis() == 1` on first serialize — the shared codec
5214        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
5215        // 1_000_000 ns, the typed `restart_window` no longer matches
5216        // its rendered form.
5217        let s = SupervisorSpec {
5218            restart_window: Some(Duration::from_micros(1500)),
5219            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5220            ..SupervisorSpec::default()
5221        };
5222        match s.validate().unwrap_err() {
5223            SupervisorError::RestartWindowNotCanonical { window } => {
5224                assert_eq!(window, Duration::from_micros(1500));
5225            }
5226            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5227        }
5228    }
5229
5230    #[test]
5231    fn validate_rejects_one_nanosecond_restart_window() {
5232        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
5233        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
5234        // so the shared codec emits the literal `"0s"` — the next
5235        // serde round-trip would parse back to `Duration::ZERO`, which
5236        // the `RestartWindowZero` arm then rejects on re-validate. The
5237        // canonical-form gate at this layer surfaces a self-locating
5238        // diagnostic naming the offending Duration verbatim rather
5239        // than a downstream `RestartWindowZero` whose remediation
5240        // points at omitting the slot.
5241        let s = SupervisorSpec {
5242            restart_window: Some(Duration::from_nanos(1)),
5243            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5244            ..SupervisorSpec::default()
5245        };
5246        match s.validate().unwrap_err() {
5247            SupervisorError::RestartWindowNotCanonical { window } => {
5248                assert_eq!(window, Duration::from_nanos(1));
5249            }
5250            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5251        }
5252    }
5253
5254    #[test]
5255    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
5256        // The 1-ns-past-1ms boundary case: a `Duration` carrying
5257        // 1_000_001 ns is structurally past the integer-ms granularity
5258        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
5259        // trip would truncate to `1ms` and the consumer would observe
5260        // a 1-ns drift on every emit. Same boundary the peer
5261        // `validate_rejects_nanosecond_past_canonical_boundary` test
5262        // in limits.rs pins for the `:limits :wall-clock` axis.
5263        let w = Duration::from_nanos(1_000_001);
5264        let s = SupervisorSpec {
5265            restart_window: Some(w),
5266            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5267            ..SupervisorSpec::default()
5268        };
5269        assert_eq!(
5270            s.validate().unwrap_err(),
5271            SupervisorError::RestartWindowNotCanonical { window: w }
5272        );
5273    }
5274
5275    #[test]
5276    fn validate_accepts_integer_millisecond_restart_window_values() {
5277        // The positive-control sweep: every `Duration` the shared
5278        // codec can round-trip losslessly — the canonical
5279        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
5280        // pair emits and accepts — passes `validate` without
5281        // surfacing the new canonical-form arm. Mirrors
5282        // `validate_accepts_integer_millisecond_wall_clock_values` on
5283        // the sibling `:limits :wall-clock` axis.
5284        for w in [
5285            Duration::from_millis(1),
5286            Duration::from_millis(500),
5287            Duration::from_millis(1500),
5288            Duration::from_secs(1),
5289            Duration::from_secs(30),
5290            Duration::from_secs(60),
5291            Duration::from_secs(120),
5292            Duration::from_secs(3600),
5293        ] {
5294            let s = SupervisorSpec {
5295                restart_window: Some(w),
5296                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5297                ..SupervisorSpec::default()
5298            };
5299            s.validate()
5300                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
5301        }
5302    }
5303
5304    #[test]
5305    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
5306        // Cross-arm ordering pin: `Duration::ZERO` has
5307        // `subsec_nanos() == 0` and would otherwise pass the
5308        // canonical-form arm — the zero-floor arm must fire first so
5309        // the more self-locating `RestartWindowZero` diagnostic (with
5310        // its omit-axis remediation directly named) leads. Same
5311        // posture every peer zero-then-shape gate uses
5312        // (`WallClockZero` → `WallClockNotCanonical`,
5313        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
5314        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
5315        let s = SupervisorSpec {
5316            restart_window: Some(Duration::ZERO),
5317            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5318            ..SupervisorSpec::default()
5319        };
5320        assert_eq!(
5321            s.validate().unwrap_err(),
5322            SupervisorError::RestartWindowZero
5323        );
5324    }
5325
5326    #[test]
5327    fn restart_window_canonical_diagnostic_carries_offending_duration() {
5328        // Diagnostic-shape pin: the canonical-form arm names the
5329        // offending `Duration` verbatim so the author's grep lands on
5330        // the field's value, not a generic "duration not canonical"
5331        // message. Same shape every other typed-canonical-form arm
5332        // on this surface carries (`WallClockNotCanonical` carries
5333        // the offending `Duration` verbatim,
5334        // `PolicyTimeoutNotCanonical` carries the offending
5335        // `Duration` verbatim).
5336        let w = Duration::from_micros(500);
5337        let s = SupervisorSpec {
5338            restart_window: Some(w),
5339            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5340            ..SupervisorSpec::default()
5341        };
5342        let err = s.validate().unwrap_err();
5343        let msg = err.to_string();
5344        assert!(
5345            msg.contains("500"),
5346            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
5347        );
5348        assert!(
5349            msg.contains("sub-millisecond"),
5350            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
5351        );
5352    }
5353
5354    #[test]
5355    fn restart_window_validated_value_round_trips_through_codec() {
5356        // The structural property the canonical-ms gate enforces:
5357        // every `SupervisorSpec::restart_window` past
5358        // `SupervisorSpec::validate` round-trips losslessly through
5359        // the shared duration codec (serialize → string →
5360        // deserialize → equal value). Pin this end-to-end so a future
5361        // change to either side (the validate gate's accepted
5362        // granularity, the codec's parse/render unit set) that breaks
5363        // the alignment surfaces here. Peer of
5364        // `wall_clock_validated_value_round_trips_through_codec` on
5365        // the sibling `:limits :wall-clock` axis.
5366        for w in [
5367            Duration::from_millis(1),
5368            Duration::from_millis(1500),
5369            Duration::from_secs(30),
5370            Duration::from_secs(3600),
5371        ] {
5372            let s = SupervisorSpec {
5373                restart_window: Some(w),
5374                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5375                ..SupervisorSpec::default()
5376            };
5377            s.validate().unwrap();
5378            let json = serde_json::to_string(&s).unwrap();
5379            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5380            assert_eq!(back.restart_window, Some(w));
5381        }
5382    }
5383
5384    // ── value-shape: upper cap on :restart-window ─────────────────────────
5385    //
5386    // The fourth (and last) typed-`Duration` axis in caixa-core to get
5387    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
5388    // `:politicas :timeout` (2e8ee7e), and `:politicas
5389    // :circuit-breaker :window` (379a814). Brackets the typed
5390    // `:restart-window` axis structurally: every validated value lies
5391    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
5392    // granularity, closing the
5393    // rolling-window-degenerates-to-lifetime-counter footgun the prior
5394    // zero-floor-and-canonical-form-only checks left open.
5395
5396    #[test]
5397    fn validate_rejects_restart_window_above_cap() {
5398        // The fail-before-pass-after pin: 3601s = 1h + 1s is
5399        // structurally one canonical-tick past the
5400        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
5401        // integer-millisecond magnitude the canonical-form arm above
5402        // accepts cleanly, that the shared duration codec round-trips
5403        // losslessly as `"3601s"`, and that silently passed validate on
5404        // every pre-gate codebase because the typed slot's only checks
5405        // were the zero-floor and canonical-form arms. The runtime
5406        // substrate consuming the value (Erlang/OTP's MaxIntensity/
5407        // Period reconciler, the future wasm-operator's per-supervisor
5408        // restart-intensity counter) reaches for a `Duration` so long
5409        // no realistic restart-recovery pattern resets the counter,
5410        // far from the source caixa.lisp.
5411        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5412        let s = SupervisorSpec {
5413            restart_window: Some(w),
5414            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5415            ..SupervisorSpec::default()
5416        };
5417        assert_eq!(
5418            s.validate().unwrap_err(),
5419            SupervisorError::RestartWindowExceedsCap { window: w }
5420        );
5421    }
5422
5423    #[test]
5424    fn validate_rejects_restart_window_one_millisecond_above_cap() {
5425        // Boundary case: exactly 1ms past the cap (the granularity the
5426        // canonical-form gate enforces). Catches a future "strictly
5427        // less than" half-measure and pins the diagnostic to name the
5428        // offending `Duration` verbatim. Peer of
5429        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
5430        // `rejects_policy_timeout_one_millisecond_above_cap` /
5431        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
5432        // on the sibling typed-`Duration` axes' top edges.
5433        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
5434        let s = SupervisorSpec {
5435            restart_window: Some(w),
5436            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5437            ..SupervisorSpec::default()
5438        };
5439        assert_eq!(
5440            s.validate().unwrap_err(),
5441            SupervisorError::RestartWindowExceedsCap { window: w }
5442        );
5443    }
5444
5445    #[test]
5446    fn validate_rejects_restart_window_far_above_cap() {
5447        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
5448        // `(:restart-window "7d")`, or any "I want a lifetime counter
5449        // but wrote a `<integer>h` magnitude anyway" typo — values the
5450        // canonical-form arm accepts as integer-millisecond magnitudes,
5451        // the codec round-trips losslessly through serde, but the
5452        // operator's `MaxIntensity / Period` reconciler cannot honor
5453        // as a meaningful rolling window. Until this gate landed
5454        // validate accepted them. Pin the common above-cap values (24h,
5455        // 7d, ~11.5d) so a future relaxation that drops the upper bound
5456        // surfaces here.
5457        for w in [
5458            Duration::from_secs(86_400),    // 24h
5459            Duration::from_secs(604_800),   // 7d
5460            Duration::from_secs(1_000_000), // ~11.5 days
5461        ] {
5462            let s = SupervisorSpec {
5463                restart_window: Some(w),
5464                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5465                ..SupervisorSpec::default()
5466            };
5467            assert_eq!(
5468                s.validate().unwrap_err(),
5469                SupervisorError::RestartWindowExceedsCap { window: w }
5470            );
5471        }
5472    }
5473
5474    #[test]
5475    fn validate_accepts_restart_window_at_cap() {
5476        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
5477        // (1h) — must validate. The cap is inclusive on the top edge,
5478        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
5479        // [`crate::POLICY_TIMEOUT_MAX`] /
5480        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
5481        // capped axes. Pin the boundary explicitly so a future
5482        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
5483        // instead of `>`) surfaces here as a test failure rather than a
5484        // silent contract narrowing.
5485        let s = SupervisorSpec {
5486            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5487            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5488            ..SupervisorSpec::default()
5489        };
5490        s.validate()
5491            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
5492    }
5493
5494    #[test]
5495    fn validate_accepts_restart_window_typical_values() {
5496        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
5497        // per-supervisor production-playbook band positive-control
5498        // sweep — every value Learn You Some Erlang's `{intensity, 5,
5499        // 60}` worker-supervisor `Period = 60s` default, Elixir's
5500        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
5501        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
5502        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
5503        // default recommend (5s..=300s) must pass, plus a sweep
5504        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
5505        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
5506        // on the sibling `:limits :wall-clock` axis.
5507        for w in [
5508            Duration::from_millis(1),
5509            Duration::from_millis(500),
5510            Duration::from_secs(1),
5511            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
5512            Duration::from_secs(10), // Riak Core lower
5513            Duration::from_secs(30),
5514            Duration::from_secs(60),  // Learn You Some Erlang default
5515            Duration::from_secs(120), // OTP supervisor MaxT typical
5516            Duration::from_secs(300), // Riak Core upper
5517            Duration::from_secs(900), // 15m
5518            Duration::from_secs(1800),
5519            Duration::from_secs(3600), // exactly 1h, the cap
5520        ] {
5521            let s = SupervisorSpec {
5522                restart_window: Some(w),
5523                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5524                ..SupervisorSpec::default()
5525            };
5526            s.validate()
5527                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
5528        }
5529    }
5530
5531    #[test]
5532    fn restart_window_zero_takes_precedence_over_cap() {
5533        // The cross-arm ordering pin: `Duration::ZERO` is structurally
5534        // outside both `>= 1ms` (zero-floor) and `<=
5535        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
5536        // diagnostic is the more self-locating one (it directly names
5537        // the omit-axis remediation), so the validate gate must fire
5538        // on zero first. Same shape every other zero-then-cap ordering
5539        // on this surface uses (`WallClockZero` then
5540        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
5541        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
5542        // `PolicyBreakerWindowExceedsCap`).
5543        let s = SupervisorSpec {
5544            restart_window: Some(Duration::ZERO),
5545            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5546            ..SupervisorSpec::default()
5547        };
5548        assert_eq!(
5549            s.validate().unwrap_err(),
5550            SupervisorError::RestartWindowZero,
5551            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
5552        );
5553    }
5554
5555    #[test]
5556    fn restart_window_canonical_takes_precedence_over_cap() {
5557        // The cross-arm ordering pin: a `Duration` that is *both*
5558        // sub-millisecond (non-canonical-form) and structurally above
5559        // the cap surfaces the canonical-form diagnostic first,
5560        // because the round-trip-shape break is the more fundamental
5561        // issue (the value can't even round-trip through the codec,
5562        // so the cap diagnostic naming `1ms..=1h` would be misleading
5563        // — there's no integer-ms form of the offending value). Pin
5564        // the order so a future refactor that reorders the arms
5565        // surfaces here as a test failure rather than a silent
5566        // diagnostic regression. Peer of
5567        // `wall_clock_canonical_takes_precedence_over_cap` /
5568        // `policy_timeout_canonical_takes_precedence_over_cap`.
5569        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
5570        let s = SupervisorSpec {
5571            restart_window: Some(w),
5572            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5573            ..SupervisorSpec::default()
5574        };
5575        assert_eq!(
5576            s.validate().unwrap_err(),
5577            SupervisorError::RestartWindowNotCanonical { window: w },
5578            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
5579        );
5580    }
5581
5582    #[test]
5583    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
5584        // The cross-arm ordering pin between the `:max-restarts` cap
5585        // and the sibling `:restart-window` cap. A supervisor carrying
5586        // both an over-cap `max_restarts` AND an over-cap window must
5587        // surface the `MaxRestartsExceedsCap` diagnostic first — the
5588        // cap arm is wired immediately after the zero-restart arm and
5589        // strictly before every window-axis arm (zero / canonical /
5590        // cap), so the offending value the diagnostic names matches
5591        // the order the author would discover the gates by reading
5592        // top-to-bottom through `SupervisorSpec::validate`. Pin the
5593        // order so a future refactor that reorders the arms surfaces
5594        // here as a test failure rather than a silent diagnostic
5595        // regression. Peer of
5596        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
5597        // on the sibling zero / canonical window arms.
5598        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5599        let s = SupervisorSpec {
5600            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5601            restart_window: Some(w),
5602            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5603            ..SupervisorSpec::default()
5604        };
5605        assert_eq!(
5606            s.validate().unwrap_err(),
5607            SupervisorError::MaxRestartsExceedsCap {
5608                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5609            },
5610            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5611        );
5612    }
5613
5614    #[test]
5615    fn restart_window_cap_diagnostic_carries_offending_value() {
5616        // The diagnostic-shape pin: the offending `Duration` is
5617        // carried verbatim into the
5618        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
5619        // surfaced error message names the value the author wrote,
5620        // not just the cap. Same self-locating diagnostic shape every
5621        // other typed-cap arm on this surface carries
5622        // (`WallClockExceedsCap` carries the offending `Duration`
5623        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
5624        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
5625        // the offending `Duration` verbatim).
5626        let w = Duration::from_secs(7200); // 2h
5627        let s = SupervisorSpec {
5628            restart_window: Some(w),
5629            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5630            ..SupervisorSpec::default()
5631        };
5632        let err = s.validate().unwrap_err();
5633        assert!(
5634            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
5635            "got {err:?}"
5636        );
5637        let msg = err.to_string();
5638        assert!(
5639            msg.contains("7200"),
5640            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
5641        );
5642    }
5643
5644    #[test]
5645    fn supervisor_restart_window_cap_pins_canonical_value() {
5646        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
5647        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
5648        // shared duration codec emits as a clean canonical string
5649        // (`"<n>h"`). Pinning the literal value here surfaces a future
5650        // drift (a relaxation to 24h, a tightening to 5m) as a
5651        // deliberate test edit, not a silent contract narrowing.
5652        //
5653        // The four typed-`Duration` caps on the validation surface
5654        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
5655        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
5656        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
5657        // single uniform top edge at the codec's largest emitted unit
5658        // — a structural-property invariant the equality assertions
5659        // here enshrine, so a future drift on any of the four
5660        // surfaces as a deliberate test edit. Same shape every other
5661        // typed-cap value pin uses
5662        // (`wall_clock_cap_pins_canonical_value`,
5663        // `policy_timeout_cap_pins_canonical_value`,
5664        // `circuit_breaker_window_cap_pins_canonical_value`).
5665        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
5666        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
5667        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
5668        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
5669        assert_eq!(
5670            SUPERVISOR_RESTART_WINDOW_MAX,
5671            crate::POLICY_BREAKER_WINDOW_MAX
5672        );
5673    }
5674
5675    #[test]
5676    fn restart_window_cap_value_round_trips_through_codec() {
5677        // The codec round-trip property the cap arm preserves: the
5678        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
5679        // through the shared duration codec — every value at the cap
5680        // serializes to the canonical `"1h"` form and parses back
5681        // identically. Pin the round-trip so a future change to the
5682        // codec's unit set or to the cap's magnitude that breaks the
5683        // round-trip property surfaces here. Peer of
5684        // `wall_clock_cap_value_round_trips_through_codec` on the
5685        // sibling `:limits :wall-clock` axis.
5686        let s = SupervisorSpec {
5687            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5688            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5689            ..SupervisorSpec::default()
5690        };
5691        s.validate().unwrap();
5692        let json = serde_json::to_string(&s).unwrap();
5693        assert!(
5694            json.contains("\"1h\""),
5695            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
5696        );
5697        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5698        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
5699    }
5700
5701    #[test]
5702    fn validate_rejects_duplicate_child_caixa() {
5703        // Two children with the same :caixa render to two ComputeUnits
5704        // with the same name in the cluster's HelmRelease values —
5705        // one silently overwrites the other. Erlang/OTP's child_spec.id
5706        // is required-unique per supervisor; same set-not-multiset
5707        // discipline applied here as for :membros / :placement
5708        // :clusters / :entrada :paths.
5709        let s = SupervisorSpec {
5710            children: vec![
5711                child("worker", "^0.1", RestartPolicy::Permanent),
5712                child("cache", "^0.1", RestartPolicy::Transient),
5713                child("worker", "^0.2", RestartPolicy::Permanent),
5714            ],
5715            ..SupervisorSpec::default()
5716        };
5717        let err = s.validate().unwrap_err();
5718        assert!(
5719            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
5720            "got {err:?}"
5721        );
5722    }
5723
5724    #[test]
5725    fn validate_duplicate_child_diagnostic_names_first_collision() {
5726        // Iteration walks the :children list in declaration order —
5727        // the diagnostic names the first repeat, deterministically,
5728        // even when multiple names duplicate.
5729        let s = SupervisorSpec {
5730            children: vec![
5731                child("a", "^0.1", RestartPolicy::Permanent),
5732                child("b", "^0.1", RestartPolicy::Permanent),
5733                child("a", "^0.1", RestartPolicy::Permanent),
5734                child("b", "^0.1", RestartPolicy::Permanent),
5735            ],
5736            ..SupervisorSpec::default()
5737        };
5738        let err = s.validate().unwrap_err();
5739        assert!(
5740            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
5741            "got {err:?}"
5742        );
5743    }
5744
5745    // ── self-supervision cross-slot gate ──────────────────────────
5746
5747    #[test]
5748    fn validate_no_self_supervision_rejects_self_referential_child() {
5749        // A supervisor whose `:children` lists its own `:nome` is a
5750        // one-node reconciliation cycle — rejected, naming the parent.
5751        let children = vec![
5752            child("worker", "^0.1", RestartPolicy::Permanent),
5753            child("orquestra", "^0.1", RestartPolicy::Permanent),
5754        ];
5755        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
5756        assert!(
5757            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
5758            "got {err:?}"
5759        );
5760    }
5761
5762    #[test]
5763    fn validate_no_self_supervision_accepts_distinct_children() {
5764        // Positive control: distinct child names (including a child that
5765        // is itself a supervisor — nested trees are valid OTP) pass.
5766        let children = vec![
5767            child("worker", "^0.1", RestartPolicy::Permanent),
5768            child("sub-tree", "^0.1", RestartPolicy::Permanent),
5769        ];
5770        validate_no_self_supervision(&children, "orquestra").unwrap();
5771    }
5772
5773    #[test]
5774    fn validate_no_self_supervision_empty_children_is_ok() {
5775        // SimpleOneForOne / no-static-children supervisors have nothing
5776        // to self-reference — the gate is vacuously satisfied.
5777        validate_no_self_supervision(&[], "orquestra").unwrap();
5778    }
5779
5780    #[test]
5781    fn validate_simple_one_for_one_skips_uniqueness_check() {
5782        // SimpleOneForOne supervisors carry no static children — the
5783        // duplicate-child loop never runs. A zero-window declaration
5784        // on a SimpleOneForOne supervisor still trips the window check
5785        // (window applies to dynamic children too).
5786        let s = SupervisorSpec {
5787            estrategia: RestartStrategy::SimpleOneForOne,
5788            restart_window: None,
5789            children: vec![],
5790            ..SupervisorSpec::default()
5791        };
5792        s.validate().unwrap();
5793        let s_zero = SupervisorSpec {
5794            estrategia: RestartStrategy::SimpleOneForOne,
5795            restart_window: Some(Duration::ZERO),
5796            children: vec![],
5797            ..SupervisorSpec::default()
5798        };
5799        assert_eq!(
5800            s_zero.validate().unwrap_err(),
5801            SupervisorError::RestartWindowZero
5802        );
5803    }
5804
5805    #[test]
5806    fn validate_zero_window_runs_after_max_restarts_check() {
5807        // Pin the order: max_restarts == 0 fires before
5808        // restart_window == 0s, so an author with both wrong sees the
5809        // counter-axis diagnostic first (matches the order in the
5810        // struct and in the doc comment).
5811        let s = SupervisorSpec {
5812            max_restarts: 0,
5813            restart_window: Some(Duration::ZERO),
5814            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5815            ..SupervisorSpec::default()
5816        };
5817        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5818    }
5819
5820    #[test]
5821    fn round_trip_all_strategies() {
5822        for &strat in RestartStrategy::ALL {
5823            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
5824            // shape partition through the [`gen_platform::IsVariant`]
5825            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
5826            // predicate rather than the raw
5827            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
5828            // open-coded pattern-match — same closed-set-typed-enum
5829            // arm-discriminator dispatch discipline the sibling
5830            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
5831            // (915a934) extended onto its two paired positive / negated
5832            // `matches!` filter sites, and the sibling
5833            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
5834            // predicate convergence (766ec63) extended onto the M3 mesh-
5835            // slot per-`:placement` distribution-strategy `matches!`
5836            // discriminator axis. See the sibling
5837            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
5838            // fixture and the peer `manifest::tests::
5839            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
5840            // fixture — all three sites (the last unlifted
5841            // `matches!`-based arm-discriminator axis on the OTP-shape
5842            // supervisor sibling-restart-strategy closed-set typed enum,
5843            // acknowledged in 915a934's Prior-commits footnote as the
5844            // outstanding follow-up) now consult one typed dispatch on
5845            // the substrate primitive.
5846            let s = SupervisorSpec {
5847                estrategia: strat,
5848                children: if strat.is_simple_one_for_one() {
5849                    vec![]
5850                } else {
5851                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
5852                },
5853                ..SupervisorSpec::default()
5854            };
5855            let json = serde_json::to_string(&s).unwrap();
5856            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5857            assert_eq!(s, back);
5858        }
5859    }
5860
5861    #[test]
5862    fn round_trip_all_restart_policies() {
5863        for policy in [
5864            RestartPolicy::Permanent,
5865            RestartPolicy::Temporary,
5866            RestartPolicy::Transient,
5867        ] {
5868            let c = child("w", "^0.1", policy);
5869            let json = serde_json::to_string(&c).unwrap();
5870            let back: ChildSpec = serde_json::from_str(&json).unwrap();
5871            assert_eq!(c, back);
5872        }
5873    }
5874
5875    #[test]
5876    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
5877        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
5878        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
5879        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
5880        // is the only variant that satisfies `.is_simple_one_for_one()`;
5881        // every static-children-bearing arm (`OneForOne` / `OneForAll`
5882        // / `RestForOne`) returns `false`. This pin makes the partition
5883        // invariant load-bearing at caixa-core test time so a future
5884        // derive regression (a hole that returns `false` for
5885        // `SimpleOneForOne` too, or a byte-collision that flips a second
5886        // variant to `true`) trips here rather than laundering the arm
5887        // at the three test-fixture builder sites (a hole flips the
5888        // `SimpleOneForOne` fixture to carry a non-empty children list
5889        // and the subsequent `SupervisorSpec::validate` would refuse the
5890        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
5891        // a collision flips a peer strategy's fixture to carry an empty
5892        // children list and the subsequent `validate` would refuse with
5893        // [`SupervisorError::NoChildren`] — either way, the pin fires
5894        // here, at the derive site, rather than at the fixture-refusal
5895        // site far away). Peer of the sibling
5896        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
5897        // (915a934) pin on the M2 OTP-appup axis and the sibling
5898        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
5899        // pin on the M0 `:kind` axis.
5900        let cases: &[(RestartStrategy, bool)] = &[
5901            (RestartStrategy::OneForOne, false),
5902            (RestartStrategy::OneForAll, false),
5903            (RestartStrategy::RestForOne, false),
5904            (RestartStrategy::SimpleOneForOne, true),
5905        ];
5906        for (variant, expected) in cases {
5907            assert_eq!(
5908                variant.is_simple_one_for_one(),
5909                *expected,
5910                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
5911                 return {expected} (partition invariant on the \
5912                 IsVariant-derived arm-discriminator predicate — every \
5913                 test-fixture site that partitions the `:children` slot \
5914                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
5915                 off this typed dispatch, so a derive regression must \
5916                 surface here rather than at the fixture-refusal site)"
5917            );
5918        }
5919    }
5920
5921    #[test]
5922    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
5923        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
5924        // fixture-shape partition against the pre-lift
5925        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
5926        // pattern-match every test-fixture builder site previously
5927        // coupled to inline. Asserts the two projections agree byte-for-
5928        // byte on every arm of the enum, so a future derive regression
5929        // that flipped either predicate's arm-set would surface here at
5930        // caixa-core test time rather than at the three fixture-builder
5931        // sites (`supervisor::tests::round_trip_all_strategies`,
5932        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
5933        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
5934        // far from the derive site. Same peer-shape byte-identity pin
5935        // every sibling `IsVariant`-derive-routed convergence carries on
5936        // the substrate's closed-set typed-enum surface (peer of
5937        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
5938        // on the M2 OTP-appup axis).
5939        for &strat in RestartStrategy::ALL {
5940            let via_predicate = strat.is_simple_one_for_one();
5941            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
5942            assert_eq!(
5943                via_predicate, via_matches,
5944                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
5945                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
5946                 the pre-lift open-coded pattern and the \
5947                 IsVariant-derived predicate are the same axis, \
5948                 one typed dispatch"
5949            );
5950        }
5951    }
5952
5953    #[test]
5954    fn duration_codec_round_trip_canonical_units() {
5955        // Note the canonical-form rule: durations serialize to the
5956        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
5957        // "60s" — but the round-trip preserves the underlying Duration.
5958        let cases = [
5959            ("30s", Duration::from_secs(30)),
5960            ("5m", Duration::from_secs(300)),
5961            ("1h", Duration::from_secs(3600)),
5962            ("500ms", Duration::from_millis(500)),
5963        ];
5964        for (lit, dur) in cases {
5965            let s = SupervisorSpec {
5966                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5967                restart_window: Some(dur),
5968                ..SupervisorSpec::default()
5969            };
5970            let json = serde_json::to_string(&s).unwrap();
5971            assert!(
5972                json.contains(&format!("\"{lit}\"")),
5973                "expected \"{lit}\" in {json}"
5974            );
5975            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5976            assert_eq!(back.restart_window, Some(dur));
5977        }
5978    }
5979
5980    #[test]
5981    fn duration_canonicalizes_to_largest_unit() {
5982        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
5983        // typed Duration still equals 60s on the way back.
5984        let s = SupervisorSpec {
5985            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5986            restart_window: Some(Duration::from_secs(60)),
5987            ..SupervisorSpec::default()
5988        };
5989        let json = serde_json::to_string(&s).unwrap();
5990        assert!(json.contains("\"1m\""), "{json}");
5991        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5992        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
5993    }
5994
5995    #[test]
5996    fn three_child_one_for_one_validates() {
5997        let s = SupervisorSpec {
5998            estrategia: RestartStrategy::OneForOne,
5999            max_restarts: 5,
6000            restart_window: Some(Duration::from_secs(60)),
6001            children: vec![
6002                child("worker", "^0.1", RestartPolicy::Permanent),
6003                child("cache", "^0.1", RestartPolicy::Transient),
6004                child("scratch", "^0.1", RestartPolicy::Temporary),
6005            ],
6006        };
6007        s.validate().unwrap();
6008    }
6009
6010    #[test]
6011    fn json_uses_pascal_case_for_strategy_and_policy() {
6012        // Variant names are PascalCase by default in serde, matching
6013        // tatara-lisp's enum convention (`:estrategia OneForOne`).
6014        let c = child("w", "^0.1", RestartPolicy::Permanent);
6015        let json = serde_json::to_string(&c).unwrap();
6016        assert!(json.contains("\"Permanent\""));
6017        assert!(!json.contains("\"permanent\""));
6018
6019        let s = SupervisorSpec {
6020            estrategia: RestartStrategy::OneForOne,
6021            children: vec![c],
6022            ..SupervisorSpec::default()
6023        };
6024        let json = serde_json::to_string(&s).unwrap();
6025        assert!(json.contains("\"estrategia\":\"OneForOne\""));
6026    }
6027
6028    // ── shared duration codec: integer-magnitude canonical-form gate ──
6029    //
6030    // The gate lifts the discipline `crate::limits::parse_duration`
6031    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
6032    // the shared codec backing the remaining three typed-duration
6033    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
6034    // `:politicas :circuit-breaker :window`. Every magnitude `render`
6035    // emits is a non-negative integer with no decimal point and no
6036    // leading sign, so the codec's accepted set must match for
6037    // serialize/deserialize to round-trip without canonical-form
6038    // drift.
6039
6040    #[test]
6041    fn parse_accepts_integer_canonical_units() {
6042        // Pin the happy-path: every canonical author shape `render`
6043        // ever emits parses to the same `Duration` value, so the
6044        // codec's accepted set is at least a superset of its emitted
6045        // set on the canonical-unit axis.
6046        for (lit, dur) in [
6047            ("30s", Duration::from_secs(30)),
6048            ("500ms", Duration::from_millis(500)),
6049            ("2m", Duration::from_secs(120)),
6050            ("1h", Duration::from_secs(3600)),
6051            ("0s", Duration::ZERO),
6052        ] {
6053            assert_eq!(
6054                duration_codec::parse(lit).unwrap(),
6055                dur,
6056                "parse({lit:?}) should be {dur:?}"
6057            );
6058        }
6059    }
6060
6061    #[test]
6062    fn parse_accepts_bare_integer_as_seconds() {
6063        // The `"s" | ""` arm: a bare integer with no unit is read as
6064        // seconds. Pin this so the unit-empty form keeps parsing (it
6065        // renders to `"<n>s"` on serialize — that's a unit-choice
6066        // drift the integer-magnitude gate does NOT close, matching
6067        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
6068        // the peer `:limits :memory` codec).
6069        assert_eq!(
6070            duration_codec::parse("30").unwrap(),
6071            Duration::from_secs(30)
6072        );
6073    }
6074
6075    #[test]
6076    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
6077        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
6078        // on first serialize — DRIFT. The integer-magnitude gate names
6079        // the offending `"1.5"` verbatim and points at the canonical
6080        // remediation `"1500ms"`.
6081        let err = duration_codec::parse("1.5s").unwrap_err();
6082        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
6083        assert!(
6084            err.contains("not a non-negative integer"),
6085            "missing canonical-form reason in {err:?}"
6086        );
6087        assert!(
6088            err.contains("\"1500ms\""),
6089            "missing canonical-form remediation in {err:?}"
6090        );
6091    }
6092
6093    #[test]
6094    fn parse_rejects_decimal_shaped_integer_seconds() {
6095        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
6096        // `1s` exactly, so the round-trip looks correct — but the
6097        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
6098        // decimal-shape-with-integer-value form so author intent is
6099        // never silently rewritten.
6100        let err = duration_codec::parse("1.0s").unwrap_err();
6101        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
6102        assert!(
6103            err.contains("not a non-negative integer"),
6104            "missing canonical-form reason in {err:?}"
6105        );
6106    }
6107
6108    #[test]
6109    fn parse_rejects_half_unit_minute() {
6110        // `"0.5m"` is the unit-fraction footgun — author writes a
6111        // human-readable half-minute, serde silently rewrites to
6112        // `"30s"` on next emit. The gate names the offending
6113        // magnitude `"0.5"` and points at the integer-in-smaller-unit
6114        // form.
6115        let err = duration_codec::parse("0.5m").unwrap_err();
6116        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
6117        assert!(
6118            err.contains("\"30s\""),
6119            "missing canonical-form remediation in {err:?}"
6120        );
6121    }
6122
6123    #[test]
6124    fn parse_rejects_leading_plus_sign() {
6125        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
6126        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
6127        // cleanly to 30s and round-tripped to `"30s"` on next emit
6128        // (DRIFT). The digit-only gate closes the leading-sign class
6129        // first; the diagnostic names `"+30"` verbatim.
6130        let err = duration_codec::parse("+30s").unwrap_err();
6131        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
6132        assert!(
6133            err.contains("not a non-negative integer"),
6134            "missing canonical-form reason in {err:?}"
6135        );
6136    }
6137
6138    #[test]
6139    fn parse_rejects_leading_minus_sign() {
6140        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
6141        // rejected with `"negative duration in \"-30s\""`. Under the
6142        // integer-magnitude gate the diagnostic is unified — `-30` is
6143        // non-digit-only, f64-numeric, and surfaces with the canonical-
6144        // form reason (no leading `+` / `-` sign) naming the offending
6145        // `"-30"` verbatim. Same diagnostic shape as every other
6146        // rejected non-integer magnitude.
6147        let err = duration_codec::parse("-30s").unwrap_err();
6148        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
6149        assert!(
6150            err.contains("not a non-negative integer"),
6151            "missing canonical-form reason in {err:?}"
6152        );
6153    }
6154
6155    #[test]
6156    fn parse_garbage_still_falls_through_to_bad_magnitude() {
6157        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
6158        // through to the narrower "bad duration magnitude" arm — the
6159        // canonical-form diagnostic is reserved for the parser-shape
6160        // footgun case, not the "not a number at all" case. Same
6161        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
6162        // the peer `:limits :memory` codec.
6163        let err = duration_codec::parse("--1s").unwrap_err();
6164        assert!(
6165            err.contains("bad duration magnitude"),
6166            "expected bad-magnitude wording in {err:?}"
6167        );
6168    }
6169
6170    #[test]
6171    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
6172        // The accepted set is now closed under `u64`-exact integer
6173        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
6174        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
6175        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
6176        // possible. Pin the integer-exact arms across the four unit
6177        // suffixes so a future refactor that reaches back for f64
6178        // (`from_secs_f64`, `mul_f64`) surfaces here.
6179        assert_eq!(
6180            duration_codec::parse("3600s").unwrap(),
6181            Duration::from_secs(3600)
6182        );
6183        assert_eq!(
6184            duration_codec::parse("60m").unwrap(),
6185            Duration::from_secs(3600)
6186        );
6187        assert_eq!(
6188            duration_codec::parse("1h").unwrap(),
6189            Duration::from_secs(3600)
6190        );
6191        assert_eq!(
6192            duration_codec::parse("999ms").unwrap(),
6193            Duration::from_millis(999)
6194        );
6195    }
6196
6197    #[test]
6198    fn restart_window_serde_rejects_fractional_seconds() {
6199        // The shared codec backs `SupervisorSpec::restart_window`
6200        // (`with = "duration_codec"`) — so the gate applies on serde
6201        // deserialize for the typed Supervisor slot. A
6202        // `{"restartWindow":"1.5s"}` payload that previously round-
6203        // tripped to a different canonical string on next serialize
6204        // is now refused at deserialize with the integer-magnitude
6205        // diagnostic.
6206        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6207            "restartWindow":"1.5s",
6208            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6209        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6210        let msg = err.to_string();
6211        assert!(
6212            msg.contains("not a non-negative integer"),
6213            "expected integer-magnitude diagnostic in {msg:?}"
6214        );
6215        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
6216    }
6217
6218    #[test]
6219    fn restart_window_serde_rejects_leading_plus() {
6220        // The `u64::from_str` leading-`+` permissiveness gap that
6221        // motivated the digit-only gate (the `f64`-side accepted
6222        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
6223        // is now closed on the shared codec — surfaces as a structured
6224        // diagnostic at the serde layer for every typed-duration slot.
6225        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6226            "restartWindow":"+30s",
6227            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6228        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6229        let msg = err.to_string();
6230        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
6231        assert!(
6232            msg.contains("not a non-negative integer"),
6233            "missing canonical-form reason in {msg:?}"
6234        );
6235    }
6236
6237    #[test]
6238    fn parse_rejects_leading_zero_magnitude() {
6239        // `"030s"` is digit-only, so the existing non-digit-only / sign
6240        // / fractional arm doesn't catch it — `u64::from_str("030")`
6241        // returns `Ok(30)`, so before this gate `"030s"` parsed to
6242        // `Duration::from_secs(30)` and round-tripped through `render`
6243        // to `"30s"` — a *different* canonical string on the next emit,
6244        // breaking the THEORY.md Part V render-determinism contract
6245        // exactly the way `"+30s"` did before the leading-`+` arm
6246        // landed. Peer with the `rate_limit_codec` leading-zero arm
6247        // (4f46830) on the same canonical-form-drift axis.
6248        let err = duration_codec::parse("030s").unwrap_err();
6249        assert!(
6250            err.contains("non-canonical leading zero"),
6251            "expected leading-zero diagnostic in {err:?}"
6252        );
6253        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6254        assert!(
6255            err.contains("\"30s\""),
6256            "missing canonical-form remediation in {err:?}"
6257        );
6258        assert!(
6259            err.contains("THEORY.md"),
6260            "missing render-determinism citation in {err:?}"
6261        );
6262    }
6263
6264    #[test]
6265    fn parse_rejects_multi_digit_zero_magnitude() {
6266        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
6267        // digit-only, parse losslessly to `Duration::ZERO`, but render
6268        // back to `"0s"` (the single-byte canonical form) on the next
6269        // emit. The leading-zero arm refuses the drift class at the
6270        // codec layer; the semantic-zero gate downstream
6271        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
6272        // the single-byte canonical form `"0s"` separately on the
6273        // typed-validate layer.
6274        let err = duration_codec::parse("00s").unwrap_err();
6275        assert!(
6276            err.contains("non-canonical leading zero"),
6277            "expected leading-zero diagnostic in {err:?}"
6278        );
6279        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
6280    }
6281
6282    #[test]
6283    fn parse_rejects_leading_zero_per_hour_window() {
6284        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
6285        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
6286        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
6287        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
6288        // `h` / bare-integer-as-seconds) inherits the same gate.
6289        let err = duration_codec::parse("01h").unwrap_err();
6290        assert!(
6291            err.contains("non-canonical leading zero"),
6292            "expected leading-zero diagnostic in {err:?}"
6293        );
6294        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
6295    }
6296
6297    #[test]
6298    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
6299        // The `parse_accepts_bare_integer_as_seconds` happy-path
6300        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
6301        // multi-byte starts-with-`0`, parses losslessly to
6302        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
6303        // bare-integer surface accepts permissive unit-empty
6304        // shorthand but still must reject leading-zero padding.
6305        let err = duration_codec::parse("030").unwrap_err();
6306        assert!(
6307            err.contains("non-canonical leading zero"),
6308            "expected leading-zero diagnostic in {err:?}"
6309        );
6310        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6311    }
6312
6313    #[test]
6314    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
6315        // The codec-layer / typed-validate-layer boundary: `"0s"` /
6316        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
6317        // each round-trips losslessly through `render`
6318        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
6319        // accepts them. The downstream semantic-zero gates
6320        // (`SupervisorError::ZeroRestartWindow`,
6321        // `AplicacaoError::PolicyTimeoutZero`,
6322        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
6323        // zero-magnitude authoring at the typed-validate layer above,
6324        // peer with the `rate_limit_codec` codec-layer / typed-
6325        // validate-layer partition for `"0/s"`.
6326        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
6327        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
6328        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
6329    }
6330
6331    #[test]
6332    fn parse_accepts_canonical_magnitude_with_leading_one() {
6333        // The complementary boundary: a future tightening cannot
6334        // drift into rejecting valid canonical magnitudes that
6335        // happen to start with `1` (or any digit `[1-9]`). Pin
6336        // every canonical-unit suffix so the leading-zero arm
6337        // remains strictly narrower than the digit-only arm.
6338        assert_eq!(
6339            duration_codec::parse("100ms").unwrap(),
6340            Duration::from_millis(100)
6341        );
6342        assert_eq!(
6343            duration_codec::parse("100s").unwrap(),
6344            Duration::from_secs(100)
6345        );
6346        assert_eq!(
6347            duration_codec::parse("10m").unwrap(),
6348            Duration::from_secs(600)
6349        );
6350        assert_eq!(
6351            duration_codec::parse("10h").unwrap(),
6352            Duration::from_secs(36_000)
6353        );
6354    }
6355
6356    #[test]
6357    fn restart_window_serde_rejects_leading_zero() {
6358        // The shared codec backs `SupervisorSpec::restart_window`
6359        // (`with = "duration_codec"`) — so the leading-zero arm
6360        // applies on serde deserialize for the typed Supervisor slot.
6361        // A `{"restartWindow":"030s"}` payload that previously round-
6362        // tripped to a different canonical string on next serialize
6363        // is now refused at deserialize with the leading-zero
6364        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
6365        // / `restart_window_serde_rejects_fractional_seconds` on the
6366        // same canonical-form-drift axis.
6367        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6368            "restartWindow":"030s",
6369            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6370        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6371        let msg = err.to_string();
6372        assert!(
6373            msg.contains("non-canonical leading zero"),
6374            "expected leading-zero diagnostic in {msg:?}"
6375        );
6376        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
6377    }
6378
6379    #[test]
6380    fn parse_rejects_leading_whitespace() {
6381        // `" 30s"` — the canonical paste-from-aligned-doc /
6382        // paste-from-YAML-quoted-plain-scalar footgun. Before this
6383        // gate the top-level `s.trim()` at parse entry silently ate
6384        // the leading space and parsed the value to
6385        // `Duration::from_secs(30)`, which then round-tripped through
6386        // `render` to `"30s"` (a *different* canonical string on the
6387        // next emit) — the exact canonical-form-drift class the
6388        // leading-`+` / leading-zero arms already close, extended
6389        // to the whitespace-byte class. Peer with the sibling
6390        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
6391        // the M3 `:politicas` axis.
6392        let err = duration_codec::parse(" 30s").unwrap_err();
6393        assert!(
6394            err.contains("contains whitespace byte"),
6395            "expected whitespace diagnostic in {err:?}"
6396        );
6397        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6398        assert!(
6399            err.contains("THEORY.md"),
6400            "missing render-determinism contract citation in {err:?}"
6401        );
6402    }
6403
6404    #[test]
6405    fn parse_rejects_trailing_whitespace() {
6406        // `"30s "` — the canonical shell-history / trailing-space
6407        // paste footgun. Before this gate the top-level `s.trim()`
6408        // silently ate the trailing space and parsed to
6409        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
6410        // next emit — same canonical-form drift as the leading-space
6411        // sibling, closed on the same whitespace-byte arm.
6412        let err = duration_codec::parse("30s ").unwrap_err();
6413        assert!(
6414            err.contains("contains whitespace byte"),
6415            "expected whitespace diagnostic in {err:?}"
6416        );
6417        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6418    }
6419
6420    #[test]
6421    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
6422        // `"30 s"` — the canonical typographically-spaced author
6423        // shape (the same idiom every prose reference to a duration
6424        // renders as, mistakenly retained when the value is pasted
6425        // into a codec-shaped slot). Before this gate the per-part
6426        // `num_part.trim()` / `unit.trim()` calls silently ate the
6427        // whitespace between the magnitude and the unit and parsed
6428        // the value to `Duration::from_secs(30)`, round-tripping to
6429        // `"30s"` — the codec's *internal* whitespace-tolerance
6430        // vector, orthogonal to the leading / trailing surface but
6431        // the same canonical-form-drift class. Pins the arm as
6432        // strictly stronger than the pre-existing top-level
6433        // `s.trim()` behavior: it fires on whitespace anywhere in
6434        // the value, not just at the string boundary.
6435        let err = duration_codec::parse("30 s").unwrap_err();
6436        assert!(
6437            err.contains("contains whitespace byte"),
6438            "expected whitespace diagnostic in {err:?}"
6439        );
6440        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6441    }
6442
6443    #[test]
6444    fn parse_rejects_tab_byte() {
6445        // `"\t30s"` — the canonical paste-from-indented-doc /
6446        // paste-from-YAML-block-scalar footgun where a tab byte leads
6447        // the magnitude. Pins that the gate covers tab (`0x09`) as
6448        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
6449        // members and both would be silently swallowed by `s.trim()`
6450        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
6451        // space alone to the full ASCII-whitespace set (space `0x20`,
6452        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
6453        // the tab arm as a representative of the non-space members.
6454        let err = duration_codec::parse("\t30s").unwrap_err();
6455        assert!(
6456            err.contains("contains whitespace byte"),
6457            "expected whitespace diagnostic in {err:?}"
6458        );
6459        assert!(
6460            err.contains("0x09"),
6461            "missing offending tab byte in {err:?}"
6462        );
6463    }
6464
6465    #[test]
6466    fn restart_window_serde_rejects_whitespace() {
6467        // The shared codec backs `SupervisorSpec::restart_window`
6468        // (`with = "duration_codec"`) — so the whitespace arm
6469        // applies on serde deserialize for the typed Supervisor slot.
6470        // A `{"restartWindow":" 30s"}` payload that previously round-
6471        // tripped to a different canonical string on next serialize
6472        // is now refused at deserialize with the whitespace-byte
6473        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
6474        // / `restart_window_serde_rejects_leading_plus` /
6475        // `restart_window_serde_rejects_fractional_seconds` on the
6476        // same canonical-form-drift axis.
6477        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6478            "restartWindow":" 30s",
6479            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6480        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6481        let msg = err.to_string();
6482        assert!(
6483            msg.contains("contains whitespace byte"),
6484            "expected whitespace diagnostic in {msg:?}"
6485        );
6486        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
6487    }
6488
6489    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
6490    //
6491    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
6492    // duration codec — closes the strictly-complementary class the
6493    // byte-scan cannot see, through the lifted
6494    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
6495    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
6496    // and `:politicas :circuit-breaker :window` simultaneously via
6497    // this shared codec.
6498
6499    #[test]
6500    fn duration_codec_parse_rejects_leading_nbsp() {
6501        // NBSP prefix — the strictly-complementary drift class the
6502        // ASCII byte-scan cannot see. `str::trim` strips it silently
6503        // and the value drifts to `"30s"` on next serialize.
6504        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
6505        assert!(
6506            err.contains("non-ASCII Unicode whitespace character"),
6507            "expected non-ASCII whitespace diagnostic in {err:?}"
6508        );
6509        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
6510    }
6511
6512    #[test]
6513    fn duration_codec_parse_rejects_trailing_line_separator() {
6514        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
6515        // footgun.
6516        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
6517        assert!(
6518            err.contains("non-ASCII Unicode whitespace character"),
6519            "expected non-ASCII whitespace diagnostic in {err:?}"
6520        );
6521        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
6522    }
6523
6524    #[test]
6525    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
6526        // Positive-control pin: every ASCII-only canonical form the
6527        // renderer emits stays accepted through the new arm.
6528        assert_eq!(
6529            duration_codec::parse("30s").unwrap(),
6530            Duration::from_secs(30)
6531        );
6532        assert_eq!(
6533            duration_codec::parse("500ms").unwrap(),
6534            Duration::from_millis(500)
6535        );
6536        assert_eq!(
6537            duration_codec::parse("1h").unwrap(),
6538            Duration::from_secs(3600)
6539        );
6540    }
6541
6542    #[test]
6543    fn restart_window_serde_rejects_non_ascii_whitespace() {
6544        // The shared codec backs `SupervisorSpec::restart_window` — so
6545        // the new non-ASCII Unicode whitespace arm applies on serde
6546        // deserialize for the typed Supervisor slot. A
6547        // `{"restartWindow":" 30s"}` payload that previously
6548        // survived the ASCII byte-scan (only ASCII whitespace was
6549        // refused) is now refused at deserialize with the
6550        // non-ASCII-whitespace-and-codepoint diagnostic.
6551        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
6552            \"restartWindow\":\"\u{00A0}30s\",\
6553            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
6554        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6555        let msg = err.to_string();
6556        assert!(
6557            msg.contains("non-ASCII Unicode whitespace character"),
6558            "expected non-ASCII whitespace diagnostic in {msg:?}"
6559        );
6560        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
6561    }
6562
6563    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
6564
6565    #[test]
6566    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
6567        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
6568        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
6569        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
6570        // name the exact camelCase JSON keys the
6571        // `#[serde(rename_all = "camelCase")]` attribute on
6572        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
6573        // field carries `Some(_)` / non-empty) and pin that each canonical
6574        // byte-sequence appears verbatim in the JSON — a future accidental
6575        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
6576        // name flip at the derive attribute (any of which would silently
6577        // break every downstream JSON consumer that reaches for one of the
6578        // four consts via `Value::get(...)`) surfaces here as a build-time
6579        // test failure at `supervisor.rs`, not as an apply-time
6580        // `.get(<stale-canonical-const>)` returning `None` far from the
6581        // derive-attr drift's commit. Peer with the sibling
6582        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
6583        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
6584        // M2 typed-slot family established, extended here to close the
6585        // top-level Supervisor axis.
6586        let spec = SupervisorSpec {
6587            estrategia: RestartStrategy::OneForOne,
6588            max_restarts: 5,
6589            restart_window: Some(Duration::from_secs(60)),
6590            children: vec![ChildSpec {
6591                caixa: "w".into(),
6592                versao: "^0.1".into(),
6593                restart: RestartPolicy::Permanent,
6594            }],
6595        };
6596        let json = serde_json::to_string(&spec).unwrap();
6597        for key in [
6598            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6599            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6600            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6601            crate::render::SUPERVISOR_KEY_CHILDREN,
6602        ] {
6603            let quoted = format!("\"{key}\"");
6604            assert!(
6605                json.contains(&quoted),
6606                "serialized SupervisorSpec must carry the lifted \
6607                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
6608                 the JSON emission (got: {json})",
6609            );
6610        }
6611    }
6612
6613    #[test]
6614    fn supervisor_key_consts_are_pairwise_distinct() {
6615        // Cross-axis drift-detection pin: a future collapse of two
6616        // canonical top-level byte-strings onto the same value (e.g. an
6617        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
6618        // also read `"estrategia"`) would silently reroute every
6619        // downstream probe on one axis onto the sibling axis's overlay
6620        // entry and pass every propagation-probe test that expected only
6621        // the stale axis's value. Peer of the sibling four-way distinct
6622        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
6623        let all = [
6624            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6625            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6626            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6627            crate::render::SUPERVISOR_KEY_CHILDREN,
6628        ];
6629        for (i, a) in all.iter().enumerate() {
6630            for b in all.iter().skip(i + 1) {
6631                assert_ne!(
6632                    a, b,
6633                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
6634                     canonical byte-sequences — got `{a}` == `{b}`",
6635                );
6636            }
6637        }
6638    }
6639
6640    #[test]
6641    fn supervisor_key_consts_are_lower_camel_case_shape() {
6642        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
6643        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6644        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6645        // capital, no whitespace / dots) — the canonical shape the
6646        // `#[serde(rename_all = "camelCase")]` derive produces on
6647        // `SupervisorSpec`. A future flip to a non-camelCase attribute
6648        // at the derive surfaces both here (this test fails on the
6649        // stale-constant shape) and at
6650        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6651        // (that test fails on the mismatch between const and derive).
6652        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
6653        // (d8b8b4f) on the sibling M2 `:limits` axis.
6654        for key in [
6655            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6656            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6657            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6658            crate::render::SUPERVISOR_KEY_CHILDREN,
6659        ] {
6660            assert!(
6661                !key.is_empty(),
6662                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
6663            );
6664            let first = key.chars().next().unwrap();
6665            assert!(
6666                first.is_ascii_lowercase(),
6667                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
6668                 (got {key:?}, leads with {first:?})",
6669            );
6670            assert!(
6671                key.chars().all(|c| c.is_ascii_alphanumeric()),
6672                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
6673                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6674            );
6675        }
6676    }
6677
6678    #[test]
6679    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
6680        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
6681        // (camelCase JSON keys, no leading colon) must never collide
6682        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
6683        // consts (kebab-case author-facing labels with leading colon)
6684        // that sit next to them at `caixa_core::render`. Both families
6685        // cover the same four typed Supervisor slots on two distinct
6686        // axes (author-side kebab vs renderer-side camelCase);
6687        // collapsing either family onto the other's byte-shape would
6688        // silently reroute the render-side probe onto the author-facing
6689        // surface, or vice versa. Peer of the byte-distinctness
6690        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
6691        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
6692        let pairs = [
6693            (
6694                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6695                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
6696            ),
6697            (
6698                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6699                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
6700            ),
6701            (
6702                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6703                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
6704            ),
6705            (
6706                crate::render::SUPERVISOR_KEY_CHILDREN,
6707                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
6708            ),
6709        ];
6710        for (json_key, author_key) in pairs {
6711            assert_ne!(
6712                json_key, author_key,
6713                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
6714                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
6715                 got JSON `{json_key}` == author `{author_key}`",
6716            );
6717        }
6718    }
6719
6720    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
6721
6722    #[test]
6723    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
6724        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
6725        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
6726        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
6727        // keys the `#[serde(rename_all = "camelCase")]` attribute on
6728        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
6729        // pin that each canonical byte-sequence appears verbatim in the
6730        // JSON — a future accidental `rename_all = "snake_case"` /
6731        // `"kebab-case"` / verbatim-field-name flip at the derive
6732        // attribute (any of which would silently break every downstream
6733        // JSON consumer that reaches for one of the three consts via
6734        // `Value::get(...)`) surfaces here as a build-time test failure at
6735        // `supervisor.rs`, not as an apply-time
6736        // `.get(<stale-canonical-const>)` returning `None` far from the
6737        // derive-attr drift's commit. Peer with the enclosing
6738        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6739        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
6740        // discipline the SupervisorSpec top-level lift established,
6741        // extended here to the sibling per-`:children` entry `ChildSpec`
6742        // derive so the last M2 typed-struct sub-block
6743        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
6744        // surface without a lifted serde-key peer joins the substrate's
6745        // "one canonical byte-string per typed serialized-key axis"
6746        // discipline.
6747        let c = ChildSpec {
6748            caixa: "worker".into(),
6749            versao: "^0.1".into(),
6750            restart: RestartPolicy::Permanent,
6751        };
6752        let json = serde_json::to_string(&c).unwrap();
6753        for key in [
6754            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6755            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6756            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6757        ] {
6758            let quoted = format!("\"{key}\"");
6759            assert!(
6760                json.contains(&quoted),
6761                "serialized ChildSpec must carry the lifted \
6762                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
6763                 in the JSON emission (got: {json})",
6764            );
6765        }
6766    }
6767
6768    #[test]
6769    fn supervisor_child_key_consts_are_pairwise_distinct() {
6770        // Cross-axis drift-detection pin: a future collapse of two
6771        // canonical `ChildSpec` per-entry byte-strings onto the same
6772        // value (e.g. an accidental copy-paste flip of
6773        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
6774        // silently reroute every downstream probe on one axis onto the
6775        // sibling axis's overlay entry and pass every propagation-probe
6776        // test that expected only the stale axis's value. Peer of the
6777        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
6778        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
6779        // pair (ce80ca0).
6780        let all = [
6781            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6782            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6783            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6784        ];
6785        for (i, a) in all.iter().enumerate() {
6786            for b in all.iter().skip(i + 1) {
6787                assert_ne!(
6788                    a, b,
6789                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
6790                     distinct canonical byte-sequences — got `{a}` == `{b}`",
6791                );
6792            }
6793        }
6794    }
6795
6796    #[test]
6797    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
6798        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
6799        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6800        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6801        // capital, no whitespace / dots) — the canonical shape the
6802        // `#[serde(rename_all = "camelCase")]` derive produces on
6803        // `ChildSpec`. A future flip to a non-camelCase attribute at the
6804        // derive surfaces both here (this test fails on the
6805        // stale-constant shape) and at
6806        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
6807        // (that test fails on the mismatch between const and derive).
6808        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
6809        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
6810        for key in [
6811            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6812            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6813            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6814        ] {
6815            assert!(
6816                !key.is_empty(),
6817                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
6818            );
6819            let first = key.chars().next().unwrap();
6820            assert!(
6821                first.is_ascii_lowercase(),
6822                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
6823                 byte (got {key:?}, leads with {first:?})",
6824            );
6825            assert!(
6826                key.chars().all(|c| c.is_ascii_alphanumeric()),
6827                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
6828                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6829            );
6830        }
6831    }
6832
6833    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
6834
6835    #[test]
6836    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
6837        // The fail-before-pass-after pin: pre-lift there was no
6838        // single-source binding between the [`RestartStrategy`] variant
6839        // name the un-`rename`d `Serialize` derive emits under
6840        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
6841        // every downstream cluster-side dispatcher (the future
6842        // wasm-operator's per-supervisor sibling-restart branch, the
6843        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
6844        // admission-time enum-arm bind, the `caixa-operator`'s
6845        // hierarchical reconciliation scheduler's per-strategy fan-out)
6846        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
6847        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
6848        // override, or a variant rename in the source — would silently
6849        // rebrand the emitted scalar under one spelling while every
6850        // downstream dispatcher still probed the other, with the failure
6851        // surfacing at the operator's reconcile posture (subtrees coming
6852        // up under the `default()` `OneForOne` arm rather than the typed
6853        // slot's declared strategy — a bad child would then only take
6854        // itself down instead of the sibling set the author intended, so
6855        // shared-state children fall out of sync) far from the source
6856        // rebrand commit and with no field naming the drift. Pinning the
6857        // two paths (the `Serialize` derive's serialized string AND the
6858        // [`RestartStrategy::as_str`] helper) to the same four lifted
6859        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
6860        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
6861        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
6862        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
6863        // byte-strings makes any future drift on either endpoint fail
6864        // here at caixa-core build time. Peer of the M3
6865        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
6866        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
6867        // three-path-convergence discipline, extended to close the
6868        // OTP-shaped per-supervisor sibling-restart axis.
6869        for (variant, expected) in [
6870            (
6871                RestartStrategy::OneForOne,
6872                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6873            ),
6874            (
6875                RestartStrategy::OneForAll,
6876                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6877            ),
6878            (
6879                RestartStrategy::RestForOne,
6880                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6881            ),
6882            (
6883                RestartStrategy::SimpleOneForOne,
6884                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6885            ),
6886        ] {
6887            let json = serde_json::to_string(&variant).unwrap();
6888            assert_eq!(
6889                json,
6890                format!("\"{expected}\""),
6891                "RestartStrategy::{variant:?} must serialize to {expected:?}"
6892            );
6893            assert_eq!(
6894                variant.as_str(),
6895                expected,
6896                "RestartStrategy::{variant:?}.as_str() must return the lifted \
6897                 SUPERVISOR_ESTRATEGIA_* constant"
6898            );
6899        }
6900    }
6901
6902    #[test]
6903    fn supervisor_estrategia_consts_are_pairwise_distinct() {
6904        // Cross-arm drift-detection pin: a future collapse of two
6905        // canonical variant byte-strings onto the same value (e.g. an
6906        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
6907        // to also read `"OneForOne"`) would silently reroute every
6908        // downstream operator's per-strategy dispatch onto the sibling
6909        // arm's reconcile branch and pass every propagation-probe test
6910        // that expected only the stale arm's value — the mis-strategied
6911        // subtree would come up with the wrong sibling-restart posture
6912        // on every subsequent failure. Peer of the sibling four-way
6913        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
6914        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
6915        let all = [
6916            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6917            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6918            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6919            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6920        ];
6921        for (i, a) in all.iter().enumerate() {
6922            for (j, b) in all.iter().enumerate() {
6923                if i != j {
6924                    assert_ne!(
6925                        a, b,
6926                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
6927                         — got duplicate {a:?} at indices {i} and {j}",
6928                    );
6929                }
6930            }
6931        }
6932    }
6933
6934    #[test]
6935    fn restart_strategy_display_routes_through_as_str_helper() {
6936        // The fail-before-pass-after pin on the first half of the
6937        // three-path convergence: pre-convergence the sibling
6938        // OTP-shape typed enum [`RestartStrategy`] carried a
6939        // [`std::fmt::Display`] surface via its
6940        // `#[discriminant(also_display)]` gen-platform derive route,
6941        // which arrived kebab-case as `"one-for-one"` /
6942        // `"one-for-all"` / `"rest-for-one"` /
6943        // `"simple-one-for-one"` while the wire format ran as
6944        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
6945        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
6946        // Every consumer reaching for a strategy byte-string past the
6947        // wire format had to pick between three paths
6948        // ([`RestartStrategy::as_str`], the `Serialize` derive's
6949        // serialized string, or `format!("{v}")` on the
6950        // discriminant-Display route), any two of which a future
6951        // variant rename or `#[serde(rename_all = "kebab-case")]`
6952        // attribute would silently desynchronize. Wiring
6953        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
6954        // closes the third path: every `format!("{v}")` call reaches
6955        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6956        // const the wire format and the [`RestartStrategy::as_str`]
6957        // helper already route through, so a future variant rename
6958        // lands at exactly one place. Pin the routing here so a future
6959        // `impl std::fmt::Display for RestartStrategy`
6960        // reimplementation that hand-rolls the arms instead of
6961        // delegating to [`RestartStrategy::as_str`] fails at
6962        // caixa-core build time. Peer of the M3
6963        // `placement_strategy_display_routes_through_as_str_helper`
6964        // (cc8f749) which the M3 axis converged first.
6965        for &variant in RestartStrategy::ALL {
6966            assert_eq!(
6967                variant.to_string(),
6968                variant.as_str(),
6969                "RestartStrategy::{variant:?} Display must route through \
6970                 RestartStrategy::as_str (single source of truth: the lifted \
6971                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
6972            );
6973        }
6974    }
6975
6976    #[test]
6977    fn restart_strategy_display_matches_serialized_wire_byte_string() {
6978        // The fail-before-pass-after pin on the second half of the
6979        // three-path convergence: `Display` (user-facing text) agrees
6980        // byte-for-byte with the `Serialize` derive's wire format
6981        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
6982        // scalar) on every variant. Pre-convergence the two paths
6983        // were structurally independent — a future
6984        // `#[serde(rename_all = "kebab-case")]` attribute on the
6985        // enum would silently rebrand the emitted wire scalar
6986        // (`one-for-one`, `one-for-all`, `rest-for-one`,
6987        // `simple-one-for-one`) while every consumer that
6988        // pretty-prints the strategy (the future wasm-operator's
6989        // per-supervisor sibling-restart-strategy diagnostic line,
6990        // the future `feira app graph` per-supervisor strategy line,
6991        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
6992        // materializer's admission-webhook rejection body) would
6993        // still emit the PascalCase form the `as_str` / `Display`
6994        // route returns, with the mismatch surfacing at consumer
6995        // parse time / operator dispatch time far from the source
6996        // rebrand commit. Pin the two paths byte-for-byte here so any
6997        // future serde-attribute or variant-rename drift is a
6998        // caixa-core-build-time test failure at this call, not a
6999        // silent per-consumer dispatch miss. Peer of the M3
7000        // `placement_strategy_display_matches_serialized_wire_byte_string`
7001        // (cc8f749) which the M3 axis converged first.
7002        for &variant in RestartStrategy::ALL {
7003            let wire = serde_json::to_string(&variant).unwrap();
7004            let unquoted = wire
7005                .strip_prefix('"')
7006                .and_then(|s| s.strip_suffix('"'))
7007                .expect("serialized RestartStrategy is a JSON string");
7008            assert_eq!(
7009                variant.to_string(),
7010                unquoted,
7011                "RestartStrategy::{variant:?} Display byte-string must match the \
7012                 Serialize derive's wire byte-string (three-path convergence: \
7013                 Display + as_str + Serialize all resolve to the same \
7014                 SUPERVISOR_ESTRATEGIA_* const)"
7015            );
7016        }
7017    }
7018
7019    #[test]
7020    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
7021        // Fail-before-pass-after byte-parity pin on the lifted
7022        // `impl AsRef<str> for RestartStrategy` — asserts the
7023        // standard-library trait impl and the substrate-primitive
7024        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
7025        // to the same `&str` per instance across the four-arm
7026        // closed set, so any future silent detour that routes the
7027        // impl through a divergent projection (a per-arm inline
7028        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
7029        // re-inlining that opens a compile-time link to the un-lifted
7030        // arm-literal, a swap onto the kebab-case
7031        // [`gen_platform::Discriminant`] catalog identity that would
7032        // collide the wire axis with the dispatcher-catalog axis) trips
7033        // at caixa-core test time under `PartialEq` rather than at a
7034        // downstream `impl AsRef<str>`-bound consumer's silent split.
7035        // Sweeps every one of the four arms
7036        // [`RestartStrategy::ALL`] carries so no arm's projection is
7037        // covered only by the sibling wire-format `Serialize` derive
7038        // path. Peer of the sibling
7039        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
7040        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
7041        // top-level `:versao` typed newtype — the two pins together
7042        // cover the substrate primitive's `AsRef<str>` projection axis
7043        // on the paired newtype + closed-set-typed-enum surface.
7044        for &variant in RestartStrategy::ALL {
7045            assert_eq!(
7046                <RestartStrategy as AsRef<str>>::as_ref(&variant),
7047                variant.as_str(),
7048                "AsRef<str> impl on RestartStrategy::{variant:?} must \
7049                 byte-equal RestartStrategy::as_str on the same instance \
7050                 — divergence signals a silent detour off the substrate-\
7051                 primitive accessor"
7052            );
7053        }
7054    }
7055
7056    #[test]
7057    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
7058        // Fail-before-pass-after byte-parity pin on the three-path
7059        // convergence discipline the M2 sibling-restart primitive now
7060        // carries on the `&str`-projection axis:
7061        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
7062        // lifted impl), `format!("{s}")` (the pre-existing
7063        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
7064        // primitive `pub const fn` accessor both trait impls delegate
7065        // through) must resolve to the same byte-string on every
7066        // instance across the four-arm closed set. Refuses any future
7067        // divergence between the two trait impls (a stray
7068        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7069        // rather than delegating through the shared accessor; a
7070        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7071        // literal cascade) that would silently split the two
7072        // projection paths of the same closed-set typed enum. Mirrors
7073        // the sibling three-path-convergence discipline the peer
7074        // [`crate::CaixaVersion`] typed newtype carries on its
7075        // `AsRef<str>` / `Display` / `as_str` triple
7076        // (version.rs pin
7077        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7078        // 16d5c7e).
7079        for &variant in RestartStrategy::ALL {
7080            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
7081            let via_display: String = format!("{variant}");
7082            let via_accessor: &str = variant.as_str();
7083            assert_eq!(via_as_ref, via_accessor);
7084            assert_eq!(via_display, via_accessor);
7085            assert_eq!(via_as_ref, via_display.as_str());
7086        }
7087    }
7088
7089    #[test]
7090    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
7091        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
7092        // exhaustive-iteration surface: every variant appears exactly
7093        // once, and the slice length matches the arm count of the
7094        // closed set. Every consumer that walks the accepted-strategy
7095        // set (a future `feira supervisor --estrategia …` CLI-side
7096        // arg-parse's "did you mean" hint, a future M4 admission-
7097        // webhook's rejection body naming the accepted-`:estrategia`
7098        // list, the [`RestartStrategy::from_wire`] reverse-projection
7099        // consumers that iterate the accept-set for diagnostic
7100        // rendering) reads through this slice, so a future arm addition
7101        // that grows the enum but forgets to grow [`Self::ALL`]
7102        // silently truncates every downstream consumer's accept-set at
7103        // the same pre-addition boundary — this pin fails at caixa-core
7104        // build time on the pairwise-distinct + arm-count invariants.
7105        //
7106        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
7107        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7108        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7109        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7110        // pins on the peer closed-set typed-enum axes.
7111        let all: &[RestartStrategy] = RestartStrategy::ALL;
7112        assert_eq!(
7113            all.len(),
7114            4,
7115            "RestartStrategy::ALL must enumerate every variant of the \
7116             four-arm closed set (OneForOne, OneForAll, RestForOne, \
7117             SimpleOneForOne); got {all:?}"
7118        );
7119        for (i, a) in all.iter().enumerate() {
7120            for (j, b) in all.iter().enumerate() {
7121                if i != j {
7122                    assert_ne!(
7123                        a, b,
7124                        "RestartStrategy::ALL must carry every variant exactly \
7125                         once — got duplicate {a:?} at indices {i} and {j}"
7126                    );
7127                }
7128            }
7129        }
7130        for variant in [
7131            RestartStrategy::OneForOne,
7132            RestartStrategy::OneForAll,
7133            RestartStrategy::RestForOne,
7134            RestartStrategy::SimpleOneForOne,
7135        ] {
7136            assert!(
7137                all.contains(&variant),
7138                "RestartStrategy::ALL must contain {variant:?} — a future arm \
7139                 addition that grows the enum but forgets to grow the ALL slice \
7140                 silently truncates every downstream consumer's accept-set at \
7141                 the pre-addition boundary"
7142            );
7143        }
7144    }
7145
7146    #[test]
7147    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
7148        // Fail-before-pass-after pin on the forward accept-set of the
7149        // [`RestartStrategy::from_wire`] reverse projection: every
7150        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7151        // constant the [`RestartStrategy::as_str`] emitter walks parses
7152        // back to its paired variant. Any future arm addition that
7153        // grows the emitter's `as_str` match but forgets to grow the
7154        // parser's `from_wire` match silently splits the two halves of
7155        // the round-trip — the wire byte-string one non-serde consumer
7156        // parses from the one the emitter wrote — with the failure
7157        // surfacing at parse time far from the rebrand commit. Pinning
7158        // the four-arm accept-set here catches the drift at caixa-core
7159        // build time.
7160        //
7161        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
7162        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
7163        // accept-set pins on the peer closed-set typed-enum `str → Self`
7164        // axes.
7165        for (wire, expected) in [
7166            (
7167                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7168                RestartStrategy::OneForOne,
7169            ),
7170            (
7171                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7172                RestartStrategy::OneForAll,
7173            ),
7174            (
7175                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7176                RestartStrategy::RestForOne,
7177            ),
7178            (
7179                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7180                RestartStrategy::SimpleOneForOne,
7181            ),
7182        ] {
7183            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7184                panic!(
7185                    "RestartStrategy::from_wire({wire:?}) must accept every \
7186                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
7187                     lifted canonical byte-string that RestartStrategy::{expected:?} \
7188                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
7189                )
7190            });
7191            assert_eq!(
7192                parsed, expected,
7193                "RestartStrategy::from_wire({wire:?}) must return \
7194                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
7195            );
7196        }
7197    }
7198
7199    #[test]
7200    fn restart_strategy_from_wire_round_trips_through_as_str() {
7201        // Fail-before-pass-after pin on the closed round-trip between
7202        // the forward [`RestartStrategy::as_str`] emitter and the
7203        // reverse [`RestartStrategy::from_wire`] parser: for every
7204        // variant in [`RestartStrategy::ALL`], parsing the emitter's
7205        // output must return exactly the same variant. Any per-arm
7206        // divergence — a future arm added to `as_str` but not
7207        // `from_wire`, an accidental copy-paste flip in one but not
7208        // the other — silently splits the emit and parse halves and
7209        // the failure surfaces at consumer parse time far from the
7210        // drift site. The `ALL`-iterating shape means a future arm
7211        // addition picks up the coverage by construction.
7212        //
7213        // Peer of the sibling
7214        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
7215        // (18c7342) round-trip pin on
7216        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
7217        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
7218        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
7219        for &variant in RestartStrategy::ALL {
7220            let wire = variant.as_str();
7221            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7222                panic!(
7223                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7224                     must be Some({variant:?}) — the two halves of the round-trip \
7225                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
7226                     got None on wire byte-string {wire:?}"
7227                )
7228            });
7229            assert_eq!(
7230                parsed, variant,
7231                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7232                 must round-trip to the same variant; got {parsed:?}"
7233            );
7234        }
7235    }
7236
7237    #[test]
7238    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
7239        // Fail-before-pass-after pin on the closed-set refusal
7240        // discipline of [`RestartStrategy::from_wire`]: every
7241        // byte-string outside the four-arm accept-set returns `None`
7242        // rather than silently collapsing onto the [`Default`]
7243        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
7244        // exercised here sweeps the load-bearing drift shapes: the
7245        // empty string (a stripped serde-attribute drift), all-
7246        // whitespace strings (the canonical text-editor accidental
7247        // padding shape), the kebab-case dispatcher-catalog identities
7248        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
7249        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
7250        // derived [`std::str::FromStr`] accept-set, which parses the
7251        // *other* axis of this enum's two-axis split and must not leak
7252        // into the `from_wire` PascalCase-wire accept-set), the
7253        // lowercased single-word forms (`"oneforone"`), the padded
7254        // canonical scalar (`" OneForOne "`), the trailing-newline
7255        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
7256        // (`"AllForOne"` — the canonical typo direction).
7257        //
7258        // Peer of the sibling
7259        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
7260        // (2aa6d23) +
7261        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
7262        // (18c7342) refusal pins on the peer closed-set typed-enum
7263        // axes.
7264        for bad in [
7265            "",
7266            " ",
7267            "\n",
7268            "\t",
7269            "one-for-one",
7270            "one-for-all",
7271            "rest-for-one",
7272            "simple-one-for-one",
7273            "oneforone",
7274            "OneForOnes",
7275            "one_for_one",
7276            "one for one",
7277            "ONEFORONE",
7278            "OneForOne ",
7279            " OneForOne",
7280            " SimpleOneForOne ",
7281            "OneForOne\n",
7282            "restforone",
7283            "REST_FOR_ONE",
7284            "AllForOne",
7285            "Simple",
7286            "?",
7287        ] {
7288            assert!(
7289                RestartStrategy::from_wire(bad).is_none(),
7290                "RestartStrategy::from_wire({bad:?}) must return None — the \
7291                 parser's accept-set is exactly the four RestartStrategy::as_str \
7292                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
7293                 and this byte-string is outside that closed set"
7294            );
7295        }
7296    }
7297
7298    #[test]
7299    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
7300        // Fail-before-pass-after pin on the fourth path of the four-path
7301        // convergence: `from_wire` (the reverse projection) inverts the
7302        // `Serialize` derive's wire byte-string on every variant.
7303        // Together with the pre-existing three-path convergence
7304        // (`Display` + `as_str` + `Serialize` all resolve to the same
7305        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
7306        // pinned by
7307        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
7308        // this closes the round-trip: the wire byte-string the
7309        // `Serialize` derive emits parses back to the same variant
7310        // through `from_wire`, so any future serde-attribute or variant-
7311        // rename drift on the emit half now surfaces as a matched drift
7312        // on the parse half at caixa-core build time — the two halves
7313        // migrate as a unit through the lifted consts on any future
7314        // rename, and the round-trip cannot silently split.
7315        //
7316        // Peer of the sibling
7317        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7318        // (18c7342) wire-format pin on
7319        // [`crate::aplicacao::PlacementStrategy::from_wire`].
7320        for &variant in RestartStrategy::ALL {
7321            let wire = serde_json::to_string(&variant).unwrap();
7322            let unquoted = wire
7323                .strip_prefix('"')
7324                .and_then(|s| s.strip_suffix('"'))
7325                .expect("serialized RestartStrategy is a JSON string");
7326            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
7327                panic!(
7328                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
7329                     Serialize derive's wire byte-string for \
7330                     RestartStrategy::{variant:?} — the four-path convergence \
7331                     (Display + as_str + Serialize + from_wire) resolves through \
7332                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
7333                )
7334            });
7335            assert_eq!(
7336                parsed, variant,
7337                "RestartStrategy::from_wire of the Serialize derive's wire \
7338                 byte-string for RestartStrategy::{variant:?} must round-trip \
7339                 to the same variant; got {parsed:?}"
7340            );
7341        }
7342    }
7343
7344    #[test]
7345    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
7346        // Fail-before-pass-after byte-parity pin on the newly lifted
7347        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
7348        // library trait impl and the substrate-primitive
7349        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
7350        // the same four-arm accept-set across every arm the exhaustive
7351        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7352        // detour that routes the trait impl through a divergent projection
7353        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
7354        // … }` re-inlining that opens a compile-time link to the un-
7355        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
7356        // attribute drift that silently splits the wire byte-string from
7357        // every consumer that reaches for this typed dispatch, an
7358        // accidental swap onto the kebab-case dispatcher-catalog axis the
7359        // pre-existing [`std::str::FromStr`] impl parses through and which
7360        // would collide the two-axis wire/catalog split the sibling
7361        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
7362        // trips at caixa-core test time under `assert_eq!` rather than at
7363        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
7364        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
7365        // carries so no arm's projection is covered only by the sibling
7366        // method-named `from_wire` path. Peer of the sibling
7367        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
7368        // (3c83606),
7369        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
7370        // (bf33136), and the M3
7371        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
7372        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
7373        // onto the first M2-OTP-shape closed-set typed enum on the caixa
7374        // surface.
7375        for &variant in RestartStrategy::ALL {
7376            let wire = variant.as_str();
7377            assert_eq!(
7378                <RestartStrategy as TryFrom<&str>>::try_from(wire),
7379                Ok(variant),
7380                "TryFrom<&str> impl on RestartStrategy must round-trip \
7381                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
7382                 Ok(RestartStrategy::{variant:?}) — divergence from \
7383                 RestartStrategy::from_wire signals a silent detour off \
7384                 the substrate-primitive accessor"
7385            );
7386            assert_eq!(
7387                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
7388                RestartStrategy::from_wire(wire),
7389                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
7390                 RestartStrategy::from_wire on the same input"
7391            );
7392        }
7393    }
7394
7395    #[test]
7396    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
7397        // Rejection witness on the `impl TryFrom<&str> for
7398        // RestartStrategy` — sweeps a candidate set of byte-strings
7399        // outside the four-arm PascalCase wire accept-set the sibling
7400        // [`RestartStrategy::as_str`] emits and asserts every one lands on
7401        // `Err(())`, so a future accidental widening of the trait impl's
7402        // accept-set (a stray additional
7403        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
7404        // path, a silent inclusion of the kebab-case dispatcher-catalog
7405        // byte-string the pre-existing [`std::str::FromStr`] impl the
7406        // [`gen_platform::FromStrKind`] derive installs parses onto the
7407        // wire axis — which would collide the two-axis
7408        // wire/dispatcher-catalog split the sibling
7409        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
7410        // an English-rebrand or plural-arm silent alias that would
7411        // widen the wire accept-set past the OTP-canonical four) trips at
7412        // caixa-core test time. The candidate set includes the empty
7413        // string, whitespace-only padding, the kebab-case dispatcher-
7414        // catalog byte-strings on the sibling axis (a caller who confuses
7415        // the two axes trips here rather than at a downstream consumer's
7416        // silent reject), a lowercase / uppercase / mixed-case fold of
7417        // each PascalCase arm (a caller who assumes case-fold acceptance
7418        // trips here), leading/trailing whitespace padding, the trailing-
7419        // newline shape, quote-wrapped candidates, and a residual set of
7420        // plausible-but-wrong English rebrand candidates. Peer of the
7421        // sibling
7422        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
7423        // (3c83606) and
7424        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
7425        // (6fd00cd) rejection witnesses.
7426        let rejected: &[&str] = &[
7427            "",
7428            " ",
7429            "\n",
7430            "\t",
7431            "one-for-one",
7432            "one-for-all",
7433            "rest-for-one",
7434            "simple-one-for-one",
7435            "oneforone",
7436            "one_for_one",
7437            "OneForOnes",
7438            "ONEFORONE",
7439            "oneforall",
7440            "restforone",
7441            "simpleoneforone",
7442            "OneForOne ",
7443            " OneForOne",
7444            " OneForAll ",
7445            "OneForOne\n",
7446            "RestForOne\t",
7447            "OneForEach",
7448            "AllForOne",
7449            "one for one",
7450            "\"OneForOne\"",
7451            "?",
7452        ];
7453        for &input in rejected {
7454            assert_eq!(
7455                <RestartStrategy as TryFrom<&str>>::try_from(input),
7456                Err(()),
7457                "TryFrom<&str> impl on RestartStrategy must reject the \
7458                 non-wire byte-string {input:?} — silent acceptance signals \
7459                 an accept-set widening off the paired \
7460                 RestartStrategy::from_wire resolver"
7461            );
7462        }
7463    }
7464
7465    #[test]
7466    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
7467        // Cross-axis partition pin: the paired `TryFrom<&str>` and
7468        // `from_wire` reverse projections must resolve identically on
7469        // *every* input, not just the ones [`RestartStrategy::ALL`]
7470        // enumerates. Sweeps a mixed candidate set spanning accepted
7471        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
7472        // dispatcher-catalog byte-strings, empty, whitespace-padded,
7473        // quoted, English-rebrand candidates) inputs and asserts the
7474        // trait's `Result::ok()` projection byte-equals the method-named
7475        // resolver's `Option<Self>` return-shape on each, locking the two
7476        // paths together by construction so any future detour (a stray
7477        // `try_from` special-case that widens or narrows the accept-set
7478        // outside the paired `from_wire` resolver, an accidental swap
7479        // onto the kebab-case [`std::str::FromStr`] impl the
7480        // [`gen_platform::FromStrKind`] derive installs on the sibling
7481        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
7482        // the sibling
7483        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
7484        // pin — extends the round-trip discipline onto the M2-OTP-shape
7485        // sibling-restart axis.
7486        let candidates: &[&str] = &[
7487            "OneForOne",
7488            "OneForAll",
7489            "RestForOne",
7490            "SimpleOneForOne",
7491            "",
7492            "one-for-one",
7493            "one-for-all",
7494            "rest-for-one",
7495            "simple-one-for-one",
7496            "oneforone",
7497            "unknown",
7498            "OneForOne ",
7499            " OneForOne",
7500            "\"OneForOne\"",
7501            "OneForEach",
7502            "?",
7503        ];
7504        for &input in candidates {
7505            let via_trait: Option<RestartStrategy> =
7506                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
7507            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
7508            assert_eq!(
7509                via_trait, via_method,
7510                "TryFrom<&str> and from_wire must resolve identically on \
7511                 input {input:?} — divergence signals the two reverse-\
7512                 projection paths have drifted onto different accept-sets"
7513            );
7514        }
7515    }
7516
7517    #[test]
7518    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
7519        // Fail-before-pass-after byte-parity pin on the newly lifted
7520        // `impl From<RestartStrategy> for &'static str` — asserts the
7521        // standard-library trait impl and the substrate-primitive
7522        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
7523        // the same four-arm emit-set across every arm the exhaustive
7524        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7525        // detour that routes the trait impl through a divergent
7526        // projection (a per-arm inline `match strategy { OneForOne =>
7527        // "OneForOne", … }` re-inlining that opens a compile-time link to
7528        // the un-lifted arm-literal, an accidental swap onto the sibling
7529        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
7530        // would collide the two-axis wire/catalog split the sibling
7531        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
7532        // at caixa-core test time under `assert_eq!` rather than at a
7533        // downstream `impl Into<&'static str>`-bound consumer's silent
7534        // split. Sweeps every one of the four arms
7535        // [`RestartStrategy::ALL`] carries so no arm's projection is
7536        // covered only by the sibling method-named `as_str` /
7537        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
7538        // `<&'static str as From<RestartStrategy>>::from` output in a
7539        // `const`-shape binding to make the `'static` lifetime promise a
7540        // build-time invariant — a future accidental downgrade of any of
7541        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7542        // constants to a non-`&'static str` (a `String::leak()`-produced
7543        // return, a `Box::leak`-cast) trips at caixa-core build time
7544        // rather than at a downstream `'static`-bound consumer.
7545        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7546        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7547        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7548        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7549        for &variant in RestartStrategy::ALL {
7550            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7551            let via_method: &'static str = variant.as_str();
7552            assert_eq!(
7553                via_trait, via_method,
7554                "From<RestartStrategy> for &'static str impl must round-trip \
7555                 RestartStrategy::{variant:?} to the same lifted \
7556                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
7557                 divergence signals a silent detour off the substrate-primitive \
7558                 accessor"
7559            );
7560            let via_into: &'static str = variant.into();
7561            assert_eq!(
7562                via_into, via_method,
7563                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
7564                 byte-equal RestartStrategy::as_str on the same input — the \
7565                 blanket-derived Into shape must resolve to the same as_str \
7566                 dispatch as the explicit From impl"
7567            );
7568        }
7569        assert_eq!(
7570            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7571            [
7572                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7573                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7574                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7575                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7576            ],
7577            "const-context RestartStrategy::as_str must resolve to the four \
7578             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
7579             downgrade of any arm to a non-const or non-static byte-string \
7580             breaks the `&'static str`-lifetime promise the paired \
7581             From<RestartStrategy> for &'static str impl carries by \
7582             construction"
7583        );
7584    }
7585
7586    #[test]
7587    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
7588        // Cross-axis partition pin: the paired trait-idiomatic
7589        // `From<RestartStrategy> for &'static str` forward projection and
7590        // the method-named [`RestartStrategy::as_str`] forward projection
7591        // must resolve identically on *every* arm, not just the ones
7592        // named in the primary byte-parity pin above. Sweeps every
7593        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
7594        // output byte-equals the method-named accessor's return-value on
7595        // each, locking the two forward-projection paths together by
7596        // construction so any future detour (a stray `From` special-case
7597        // that lands on a divergent per-arm literal outside the paired
7598        // `as_str` dispatch, a hypothetical rebrand touching one axis
7599        // without the other) trips at caixa-core test time. Peer of the
7600        // sibling reverse-projection partition pin
7601        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7602        // — extends the round-trip discipline onto the trait-idiomatic
7603        // *forward* axis, closing the two-way `Self ↔ &'static str`
7604        // round-trip on the trait-idiomatic pair
7605        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
7606        // well as the pre-existing method-named pair
7607        // (`as_str` + `from_wire`).
7608        for &variant in RestartStrategy::ALL {
7609            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7610            let via_method: &'static str = variant.as_str();
7611            assert_eq!(
7612                via_trait, via_method,
7613                "From<RestartStrategy> for &'static str and \
7614                 RestartStrategy::as_str must resolve identically on \
7615                 RestartStrategy::{variant:?} — divergence signals the \
7616                 two forward-projection paths have drifted onto different \
7617                 emit-sets"
7618            );
7619        }
7620        // Round-trip witness: every arm's forward `From` output re-parses
7621        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
7622        // to the original variant. Closes the two-way `RestartStrategy ↔
7623        // &'static str` round-trip on the trait-idiomatic axis pair,
7624        // mirroring the pre-existing method-named `as_str` + `from_wire`
7625        // round-trip on the substrate-primitive axis pair.
7626        for &variant in RestartStrategy::ALL {
7627            let emitted: &'static str = variant.into();
7628            let re_parsed: Result<RestartStrategy, ()> =
7629                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7630            assert_eq!(
7631                re_parsed,
7632                Ok(variant),
7633                "trait-idiomatic axis pair must round-trip \
7634                 RestartStrategy::{variant:?} through `.into::<&'static \
7635                 str>()` and back through `TryFrom<&str>` — a break signals \
7636                 the forward-emit and reverse-parse axes have drifted onto \
7637                 different vocabularies"
7638            );
7639        }
7640    }
7641
7642    #[test]
7643    fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
7644        // Fail-before-pass-after byte-parity pin on the newly lifted
7645        // `impl From<&RestartStrategy> for &'static str` — asserts the
7646        // borrowed-input standard-library trait impl and the substrate-
7647        // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
7648        // resolve to the same four-arm emit-set across every arm the
7649        // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
7650        // `From` trait does not auto-derive the borrowed-input sibling
7651        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
7652        // where T: Copy, U: From<T>` blanket in `core`), so the
7653        // borrowed-input axis is a distinct trait-idiomatic surface
7654        // that a `.iter().map(Into::into)` shape over
7655        // [`RestartStrategy::ALL`] (whose iterator yields
7656        // `&RestartStrategy`, not `RestartStrategy`) reaches through
7657        // this impl and no other — the paired owned-input
7658        // [`From<RestartStrategy>`] impl requires an explicit
7659        // `.copied()` / dereference before the trait fires.
7660        // Materializes the `<&'static str as
7661        // From<&RestartStrategy>>::from` output in a `const`-shape
7662        // binding to make the `'static` lifetime promise a build-time
7663        // invariant.
7664        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7665        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7666        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7667        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7668        for variant in RestartStrategy::ALL {
7669            let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
7670            let via_method: &'static str = variant.as_str();
7671            assert_eq!(
7672                via_trait, via_method,
7673                "From<&RestartStrategy> for &'static str impl must \
7674                 round-trip &RestartStrategy::{variant:?} to the same \
7675                 lifted SUPERVISOR_ESTRATEGIA_* const \
7676                 RestartStrategy::as_str returns — divergence signals a \
7677                 silent detour off the substrate-primitive accessor"
7678            );
7679            let via_into: &'static str = variant.into();
7680            assert_eq!(
7681                via_into, via_method,
7682                "Into<&'static str>::into on &RestartStrategy::{variant:?} \
7683                 must byte-equal RestartStrategy::as_str on the same input — \
7684                 the blanket-derived Into shape must resolve to the same \
7685                 as_str dispatch as the explicit From impl"
7686            );
7687        }
7688        assert_eq!(
7689            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7690            [
7691                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7692                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7693                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7694                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7695            ],
7696            "const-context RestartStrategy::as_str must resolve to the \
7697             four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
7698             input From<&RestartStrategy> for &'static str impl inherits \
7699             its `'static` lifetime promise from the same accessor the \
7700             owned-input sibling routes through"
7701        );
7702    }
7703
7704    #[test]
7705    fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
7706        // Cross-axis partition pin: the paired trait-idiomatic
7707        // owned-input `From<RestartStrategy> for &'static str` (523157d
7708        // campaign-shape) and borrowed-input `From<&RestartStrategy> for
7709        // &'static str` (this lift) forward projections must resolve
7710        // identically on every arm, locking the two input-shape paths
7711        // together so any future detour trips at caixa-core test time.
7712        // Then a witness that a `.iter().map(Into::into)` pipe over
7713        // [`RestartStrategy::ALL`] (whose iterator yields
7714        // `&RestartStrategy`) materializes the four-arm accept-set
7715        // through the borrowed-input axis alone — the exact shape a
7716        // future wasm-operator per-supervisor sibling-restart-strategy
7717        // diagnostic line, a future substrate-wide per-arm diagnostic
7718        // column, or a
7719        // `HashMap::<&'static str, RestartStrategy>::from_iter(
7720        //     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
7721        // per-strategy lookup reaches through — closing the two-way
7722        // owned/borrowed input-shape symmetry on the forward-projection
7723        // trait-idiomatic axis. Peer of the sibling
7724        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7725        // (64aa742) /
7726        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7727        // (5ab993a) /
7728        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7729        // (807b0b5) partition pins on the sibling closed-set typed-enum
7730        // discriminator axes — extends the borrowed-input axis
7731        // discipline onto the first M2 OTP-shape sibling-restart
7732        // closed-set typed enum on the caixa surface. Also closes the
7733        // direct two-way `&Self → &'static str → Self` round-trip via
7734        // the paired [`TryFrom<&str>`] axis — unlike the peer
7735        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
7736        // lowercase Portuguese diagnostic bytes while the reverse
7737        // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
7738        // trip through an intermediate wire-vocab hop), the
7739        // [`RestartStrategy::as_str`] emit and
7740        // [`RestartStrategy::from_wire`] parse share the same
7741        // `PascalCase` vocabulary by construction, so the borrowed-
7742        // input forward axis and the reverse axis compose directly.
7743        for &variant in RestartStrategy::ALL {
7744            let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7745            let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
7746            assert_eq!(
7747                owned, borrowed,
7748                "From<RestartStrategy> and From<&RestartStrategy> for \
7749                 &'static str must resolve identically on \
7750                 RestartStrategy::{variant:?} — divergence signals the \
7751                 owned-input and borrowed-input forward-projection paths \
7752                 have drifted onto different emit-sets"
7753            );
7754        }
7755        let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
7756        let via_method: Vec<&'static str> =
7757            RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
7758        assert_eq!(
7759            via_iter, via_method,
7760            "`.iter().map(Into::into)` over RestartStrategy::ALL must \
7761             byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
7762             borrowed-input `From<&RestartStrategy> for &'static str` \
7763             axis is what makes the `.iter().map(Into::into)` shape route \
7764             through the substrate-primitive `RestartStrategy::as_str` \
7765             accessor rather than through a per-call-site `.copied()` / \
7766             dereference detour"
7767        );
7768        for variant in RestartStrategy::ALL {
7769            let emitted: &'static str = variant.into();
7770            let re_parsed: Result<RestartStrategy, ()> =
7771                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7772            assert_eq!(
7773                re_parsed,
7774                Ok(*variant),
7775                "trait-idiomatic borrowed-input forward-projection + \
7776                 reverse-projection axis pair must round-trip \
7777                 &RestartStrategy::{variant:?} through `.into::<&'static \
7778                 str>()` (via the borrowed-input axis) and back through \
7779                 `TryFrom<&str>` — a break signals the borrowed-input \
7780                 forward-emit and reverse-parse axes have drifted onto \
7781                 different vocabularies"
7782            );
7783        }
7784    }
7785
7786    #[test]
7787    fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
7788        // Fail-before-pass-after byte-parity pin on the newly lifted
7789        // `impl From<RestartStrategy> for String` — asserts the
7790        // owned-`String`-returning standard-library trait impl and the
7791        // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
7792        // accessor resolve to the same four-arm emit-set across every
7793        // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
7794        // Rust's standard library does not carry a blanket
7795        // `impl<T: AsRef<str>> From<T> for String` (nor an
7796        // `impl<T: fmt::Display> From<T> for String`), so the
7797        // owned-`String` forward-projection axis is a distinct
7798        // trait-idiomatic surface that a
7799        // `let key: String = strategy.into();`-shaped call site
7800        // reaches through this impl and no other — the paired sibling
7801        // `From<RestartStrategy> for &'static str` impl forces every
7802        // owned-`String` call site through an explicit
7803        // `.to_owned()` / `String::from` restatement.
7804        for &variant in RestartStrategy::ALL {
7805            let via_trait: String = <String as From<RestartStrategy>>::from(variant);
7806            let via_method: &'static str = variant.as_str();
7807            assert_eq!(
7808                via_trait.as_str(),
7809                via_method,
7810                "From<RestartStrategy> for String impl must round-trip \
7811                 RestartStrategy::{variant:?} to the same lifted \
7812                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
7813                 returns — divergence signals a silent detour off the \
7814                 substrate-primitive accessor"
7815            );
7816            let via_into: String = variant.into();
7817            assert_eq!(
7818                via_into.as_str(),
7819                via_method,
7820                "Into<String>::into on RestartStrategy::{variant:?} must \
7821                 byte-equal RestartStrategy::as_str on the same input — the \
7822                 blanket-derived Into shape must resolve to the same as_str \
7823                 dispatch as the explicit From impl"
7824            );
7825        }
7826    }
7827
7828    #[test]
7829    fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
7830        // Cross-axis partition pin: the paired trait-idiomatic
7831        // owned-`String` `From<RestartStrategy> for String` (this lift)
7832        // and owned-`&'static str` `From<RestartStrategy> for &'static
7833        // str` (523157d) forward projections must resolve identically
7834        // on every arm, locking the two return-type-shape paths
7835        // together so any future detour trips at caixa-core test time.
7836        // Also byte-parity witness against the sibling
7837        // [`ToString::to_string`] surface routed through
7838        // [`std::fmt::Display`] — the three owned-heap-string paths
7839        // (`.into::<String>()`, `String::from`, `.to_string()`) must
7840        // resolve identically on every arm so a future consumer that
7841        // picks any of the three lands on the same lifted
7842        // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
7843        // witness through the paired trait-idiomatic reverse
7844        // [`TryFrom<&str>`] axis on the owned-`String`'s
7845        // [`String::as_str`] borrow that closes the two-way
7846        // `Self → String → Self` round-trip on the trait-idiomatic
7847        // owned-`String` forward + reverse axis pair.
7848        for &variant in RestartStrategy::ALL {
7849            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
7850            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7851            assert_eq!(
7852                owned_string.as_str(),
7853                owned_static,
7854                "From<RestartStrategy> for String and From<RestartStrategy> \
7855                 for &'static str must resolve identically on \
7856                 RestartStrategy::{variant:?} — divergence signals the \
7857                 owned-`String` and owned-`&'static str` forward-projection \
7858                 return-type-shape paths have drifted onto different \
7859                 emit-sets"
7860            );
7861            let via_to_string: String = variant.to_string();
7862            assert_eq!(
7863                owned_string, via_to_string,
7864                "From<RestartStrategy> for String must byte-equal \
7865                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
7866                 divergence signals the trait-idiomatic owned-`String` \
7867                 forward-projection axis and the ToString-through-Display \
7868                 axis have drifted onto different emit-sets"
7869            );
7870        }
7871        let via_iter: Vec<String> = RestartStrategy::ALL
7872            .iter()
7873            .copied()
7874            .map(String::from)
7875            .collect();
7876        let via_method: Vec<String> = RestartStrategy::ALL
7877            .iter()
7878            .map(|s| s.as_str().to_owned())
7879            .collect();
7880        assert_eq!(
7881            via_iter, via_method,
7882            "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
7883             must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
7884             every arm — the owned-`String` `From<RestartStrategy> for \
7885             String` axis is what makes the `String::from` composition \
7886             route through the substrate-primitive `RestartStrategy::as_str` \
7887             accessor rather than through a per-call-site `.to_owned()` / \
7888             `String::from(strategy.as_str())` detour"
7889        );
7890        for &variant in RestartStrategy::ALL {
7891            let emitted: String = variant.into();
7892            let re_parsed: Result<RestartStrategy, ()> =
7893                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
7894            assert_eq!(
7895                re_parsed,
7896                Ok(variant),
7897                "trait-idiomatic owned-`String` forward-projection + \
7898                 reverse-projection axis pair must round-trip \
7899                 RestartStrategy::{variant:?} through `.into::<String>()` \
7900                 and back through `TryFrom<&str>` on the owned-`String`'s \
7901                 String::as_str borrow — a break signals the owned-`String` \
7902                 forward-emit and reverse-parse axes have drifted onto \
7903                 different vocabularies"
7904            );
7905        }
7906    }
7907
7908    #[test]
7909    fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
7910        // Fail-before-pass-after byte-parity pin on the newly lifted
7911        // `impl From<&RestartStrategy> for String` — asserts the
7912        // borrowed-input owned-`String`-returning standard-library trait
7913        // impl and the substrate-primitive [`RestartStrategy::as_str`]
7914        // `pub const fn` accessor resolve to the same four-arm emit-set
7915        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
7916        // enumerates. Rust's standard library does not carry a blanket
7917        // `impl<T: AsRef<str>> From<&T> for String` (nor an
7918        // `impl<T: fmt::Display> From<&T> for String`), so the
7919        // borrowed-input owned-`String` forward-projection axis is a
7920        // distinct trait-idiomatic surface that a
7921        // `let key: String = (&strategy).into();`-shaped call site
7922        // reaches through this impl and no other — the paired sibling
7923        // `From<RestartStrategy> for String` impl forces every
7924        // borrowed-input call site through an explicit `Copy` deref
7925        // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
7926        // `.to_string()` detour.
7927        for &variant in RestartStrategy::ALL {
7928            let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
7929            let via_method: &'static str = variant.as_str();
7930            assert_eq!(
7931                via_trait.as_str(),
7932                via_method,
7933                "From<&RestartStrategy> for String impl must round-trip \
7934                 &RestartStrategy::{variant:?} to the same lifted \
7935                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
7936                 returns — divergence signals a silent detour off the \
7937                 substrate-primitive accessor"
7938            );
7939            let via_into: String = (&variant).into();
7940            assert_eq!(
7941                via_into.as_str(),
7942                via_method,
7943                "Into<String>::into on &RestartStrategy::{variant:?} must \
7944                 byte-equal RestartStrategy::as_str on the same input — the \
7945                 blanket-derived Into shape must resolve to the same as_str \
7946                 dispatch as the explicit From impl"
7947            );
7948        }
7949    }
7950
7951    #[test]
7952    fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
7953        // Cross-axis partition pin: the newly lifted trait-idiomatic
7954        // borrowed-input owned-`String` `From<&RestartStrategy> for
7955        // String` (this lift), the paired owned-input owned-`String`
7956        // `From<RestartStrategy> for String` (7baa18a), the paired
7957        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
7958        // for &'static str` (e941836), and the paired owned-input
7959        // owned-`&'static str` `From<RestartStrategy> for &'static str`
7960        // (523157d) — every corner of the `{Self, &Self} × {&'static
7961        // str, String}` 2×2 trait-idiomatic projection family — must
7962        // resolve identically on every arm, locking the four
7963        // return-shape × input-shape paths together so any future
7964        // detour trips at caixa-core test time. Also byte-parity
7965        // witness against the sibling [`ToString::to_string`] surface
7966        // routed through [`std::fmt::Display`] and a direct round-trip
7967        // witness through the paired trait-idiomatic reverse
7968        // [`TryFrom<&str>`] axis on the owned-`String`'s
7969        // [`String::as_str`] borrow that closes the two-way
7970        // `&Self → String → Self` round-trip on the trait-idiomatic
7971        // borrowed-input owned-`String` forward + reverse axis pair.
7972        for &variant in RestartStrategy::ALL {
7973            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
7974            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
7975            let borrowed_static: &'static str =
7976                <&'static str as From<&RestartStrategy>>::from(&variant);
7977            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7978            assert_eq!(
7979                borrowed_string, owned_string,
7980                "From<&RestartStrategy> for String and From<RestartStrategy> \
7981                 for String must resolve identically on \
7982                 RestartStrategy::{variant:?} — divergence signals the \
7983                 borrowed-input and owned-input owned-`String` \
7984                 forward-projection input-shape paths have drifted onto \
7985                 different emit-sets"
7986            );
7987            assert_eq!(
7988                borrowed_string.as_str(),
7989                borrowed_static,
7990                "From<&RestartStrategy> for String and From<&RestartStrategy> \
7991                 for &'static str must resolve identically on \
7992                 RestartStrategy::{variant:?} — divergence signals the \
7993                 borrowed-input `&'static str` and owned-`String` \
7994                 return-shape paths have drifted onto different emit-sets"
7995            );
7996            assert_eq!(
7997                borrowed_string.as_str(),
7998                owned_static,
7999                "From<&RestartStrategy> for String and From<RestartStrategy> \
8000                 for &'static str must resolve identically on \
8001                 RestartStrategy::{variant:?} — divergence signals a break \
8002                 in the diagonal corner of the {{Self, &Self}} × \
8003                 {{&'static str, String}} 2×2 trait-idiomatic \
8004                 projection family"
8005            );
8006            let via_to_string: String = variant.to_string();
8007            assert_eq!(
8008                borrowed_string, via_to_string,
8009                "From<&RestartStrategy> for String must byte-equal \
8010                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8011                 divergence signals the trait-idiomatic borrowed-input \
8012                 owned-`String` forward-projection axis and the \
8013                 ToString-through-Display axis have drifted onto different \
8014                 emit-sets"
8015            );
8016        }
8017        let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
8018        let via_method: Vec<String> = RestartStrategy::ALL
8019            .iter()
8020            .map(|s| s.as_str().to_owned())
8021            .collect();
8022        assert_eq!(
8023            via_iter, via_method,
8024            "`.iter().map(String::from)` over RestartStrategy::ALL — a \
8025             call site whose iteration axis holds `&RestartStrategy` by \
8026             construction — must byte-equal `.iter().map(|s| \
8027             s.as_str().to_owned())` on every arm — the borrowed-input \
8028             owned-`String` `From<&RestartStrategy> for String` axis is \
8029             what makes the `String::from` composition route through the \
8030             substrate-primitive `RestartStrategy::as_str` accessor \
8031             without a spurious `Copy` deref (which would only be \
8032             reachable through the owned-input `From<RestartStrategy> for \
8033             String` axis by first calling `.copied()` on the iterator)"
8034        );
8035        for &variant in RestartStrategy::ALL {
8036            let emitted: String = (&variant).into();
8037            let re_parsed: Result<RestartStrategy, ()> =
8038                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8039            assert_eq!(
8040                re_parsed,
8041                Ok(variant),
8042                "trait-idiomatic borrowed-input owned-`String` \
8043                 forward-projection + reverse-projection axis pair must \
8044                 round-trip &RestartStrategy::{variant:?} through \
8045                 `.into::<String>()` on the borrowed-input surface and \
8046                 back through `TryFrom<&str>` on the owned-`String`'s \
8047                 String::as_str borrow — a break signals the \
8048                 borrowed-input owned-`String` forward-emit and \
8049                 reverse-parse axes have drifted onto different \
8050                 vocabularies"
8051            );
8052        }
8053    }
8054
8055    #[test]
8056    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
8057        // Fail-before-pass-after byte-parity pin on the newly lifted
8058        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
8059        // library trait impl and the substrate-primitive
8060        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
8061        // the same three-arm accept-set across every arm the exhaustive
8062        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
8063        // detour that routes the trait impl through a divergent
8064        // projection (a per-arm inline `match s { "Permanent" =>
8065        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
8066        // link to the un-lifted arm-literal, a hypothetical
8067        // `#[serde(rename_all = "…")]` attribute drift that silently
8068        // splits the wire byte-string from every consumer that reaches
8069        // for this typed dispatch, an accidental swap onto the kebab-case
8070        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
8071        // impl parses through and which would collide the two-axis
8072        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
8073        // doc block makes load-bearing) trips at caixa-core test time
8074        // under `assert_eq!` rather than at a downstream
8075        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
8076        // every one of the three arms [`RestartPolicy::ALL`] carries so
8077        // no arm's projection is covered only by the sibling method-
8078        // named `from_wire` path. Peer of the sibling
8079        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
8080        // (5b828ed) — extends the trait-idiomatic reverse-projection
8081        // axis onto the third and final M2-OTP-shape closed-set typed
8082        // enum on the caixa surface (the paired per-child restart-
8083        // decision-policy sibling on the same M2 `:supervisor` slot).
8084        for &variant in RestartPolicy::ALL {
8085            let wire = variant.as_str();
8086            assert_eq!(
8087                <RestartPolicy as TryFrom<&str>>::try_from(wire),
8088                Ok(variant),
8089                "TryFrom<&str> impl on RestartPolicy must round-trip \
8090                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
8091                 Ok(RestartPolicy::{variant:?}) — divergence from \
8092                 RestartPolicy::from_wire signals a silent detour off \
8093                 the substrate-primitive accessor"
8094            );
8095            assert_eq!(
8096                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
8097                RestartPolicy::from_wire(wire),
8098                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
8099                 equal RestartPolicy::from_wire on the same input"
8100            );
8101        }
8102    }
8103
8104    #[test]
8105    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
8106        // Rejection witness on the `impl TryFrom<&str> for
8107        // RestartPolicy` — sweeps a candidate set of byte-strings
8108        // outside the three-arm PascalCase wire accept-set the sibling
8109        // [`RestartPolicy::as_str`] emits and asserts every one lands on
8110        // `Err(())`, so a future accidental widening of the trait impl's
8111        // accept-set (a stray additional
8112        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
8113        // path, a silent inclusion of the kebab-case dispatcher-catalog
8114        // byte-string the pre-existing [`std::str::FromStr`] impl the
8115        // [`gen_platform::FromStrKind`] derive installs parses onto the
8116        // wire axis — which would collide the two-axis
8117        // wire/dispatcher-catalog split the sibling
8118        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
8119        // an English-rebrand or plural-arm silent alias that would widen
8120        // the wire accept-set past the OTP-canonical three) trips at
8121        // caixa-core test time. The candidate set includes the empty
8122        // string, whitespace-only padding, the kebab-case dispatcher-
8123        // catalog byte-strings on the sibling axis (a caller who
8124        // confuses the two axes trips here rather than at a downstream
8125        // consumer's silent reject), a lowercase / uppercase / mixed-case
8126        // fold of each PascalCase arm (a caller who assumes case-fold
8127        // acceptance trips here), leading/trailing whitespace padding,
8128        // the trailing-newline shape, quote-wrapped candidates, and a
8129        // residual set of plausible-but-wrong English rebrand
8130        // candidates. Peer of the sibling
8131        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
8132        // (5b828ed) rejection witness.
8133        let rejected: &[&str] = &[
8134            "",
8135            " ",
8136            "\n",
8137            "\t",
8138            "permanent",
8139            "temporary",
8140            "transient",
8141            "PERMANENT",
8142            "TEMPORARY",
8143            "TRANSIENT",
8144            "Permanents",
8145            "Permanent ",
8146            " Permanent",
8147            " Temporary ",
8148            "Permanent\n",
8149            "Transient\t",
8150            "\"Permanent\"",
8151            "Ephemeral",
8152            "Always",
8153            "Never",
8154            "OnAbnormalExit",
8155            "intrinsic",
8156            "?",
8157        ];
8158        for &input in rejected {
8159            assert_eq!(
8160                <RestartPolicy as TryFrom<&str>>::try_from(input),
8161                Err(()),
8162                "TryFrom<&str> impl on RestartPolicy must reject the \
8163                 non-wire byte-string {input:?} — silent acceptance \
8164                 signals an accept-set widening off the paired \
8165                 RestartPolicy::from_wire resolver"
8166            );
8167        }
8168    }
8169
8170    #[test]
8171    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
8172        // Cross-axis partition pin: the paired `TryFrom<&str>` and
8173        // `from_wire` reverse projections must resolve identically on
8174        // *every* input, not just the ones [`RestartPolicy::ALL`]
8175        // enumerates. Sweeps a mixed candidate set spanning accepted
8176        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
8177        // case dispatcher-catalog byte-strings, empty, whitespace-
8178        // padded, quoted, English-rebrand candidates) inputs and asserts
8179        // the trait's `Result::ok()` projection byte-equals the method-
8180        // named resolver's `Option<Self>` return-shape on each, locking
8181        // the two paths together by construction so any future detour
8182        // (a stray `try_from` special-case that widens or narrows the
8183        // accept-set outside the paired `from_wire` resolver, an
8184        // accidental swap onto the kebab-case [`std::str::FromStr`]
8185        // impl the [`gen_platform::FromStrKind`] derive installs on the
8186        // sibling dispatcher-catalog axis) trips at caixa-core test
8187        // time. Peer of the sibling
8188        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
8189        // pin — extends the round-trip discipline onto the M2-OTP-shape
8190        // per-child restart-policy axis.
8191        let candidates: &[&str] = &[
8192            "Permanent",
8193            "Temporary",
8194            "Transient",
8195            "",
8196            "permanent",
8197            "temporary",
8198            "transient",
8199            "PERMANENT",
8200            "unknown",
8201            "Permanent ",
8202            " Permanent",
8203            "\"Permanent\"",
8204            "Ephemeral",
8205            "OnAbnormalExit",
8206            "?",
8207        ];
8208        for &input in candidates {
8209            let via_trait: Option<RestartPolicy> =
8210                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
8211            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
8212            assert_eq!(
8213                via_trait, via_method,
8214                "TryFrom<&str> and from_wire must resolve identically on \
8215                 input {input:?} — divergence signals the two reverse-\
8216                 projection paths have drifted onto different accept-sets"
8217            );
8218        }
8219    }
8220
8221    #[test]
8222    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
8223        // Fail-before-pass-after byte-parity pin on the newly lifted
8224        // `impl From<RestartPolicy> for &'static str` — asserts the
8225        // standard-library trait impl and the substrate-primitive
8226        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
8227        // the same three-arm emit-set across every arm the exhaustive
8228        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
8229        // detour that routes the trait impl through a divergent
8230        // projection (a per-arm inline `match policy { Permanent =>
8231        // "Permanent", … }` re-inlining that opens a compile-time link
8232        // to the un-lifted arm-literal, an accidental swap onto the
8233        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
8234        // axis that would collide the two-axis wire/catalog split the
8235        // sibling [`RestartPolicy::from_wire`] doc block makes
8236        // load-bearing) trips at caixa-core test time under
8237        // `assert_eq!` rather than at a downstream
8238        // `impl Into<&'static str>`-bound consumer's silent split.
8239        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
8240        // carries so no arm's projection is covered only by the sibling
8241        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
8242        // paths. Materializes the `<&'static str as
8243        // From<RestartPolicy>>::from` output in a `const`-shape binding
8244        // to make the `'static` lifetime promise a build-time invariant
8245        // — a future accidental downgrade of any of the three arms'
8246        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
8247        // non-`&'static str` (a `String::leak()`-produced return, a
8248        // `Box::leak`-cast) trips at caixa-core build time rather than
8249        // at a downstream `'static`-bound consumer. Peer of the sibling
8250        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
8251        // (523157d) — extends the trait-idiomatic forward-projection
8252        // axis onto the second (and second-of-two-in-M2) closed-set
8253        // typed enum on the caixa surface (the paired per-child
8254        // restart-decision-policy sibling on the same M2 `:supervisor`
8255        // slot).
8256        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
8257        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
8258        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
8259        for &variant in RestartPolicy::ALL {
8260            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8261            let via_method: &'static str = variant.as_str();
8262            assert_eq!(
8263                via_trait, via_method,
8264                "From<RestartPolicy> for &'static str impl must round-trip \
8265                 RestartPolicy::{variant:?} to the same lifted \
8266                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
8267                 divergence signals a silent detour off the substrate-primitive \
8268                 accessor"
8269            );
8270            let via_into: &'static str = variant.into();
8271            assert_eq!(
8272                via_into, via_method,
8273                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
8274                 byte-equal RestartPolicy::as_str on the same input — the \
8275                 blanket-derived Into shape must resolve to the same as_str \
8276                 dispatch as the explicit From impl"
8277            );
8278        }
8279        assert_eq!(
8280            [PERMANENT, TEMPORARY, TRANSIENT],
8281            [
8282                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8283                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8284                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8285            ],
8286            "const-context RestartPolicy::as_str must resolve to the three \
8287             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
8288             downgrade of any arm to a non-const or non-static byte-string \
8289             breaks the `&'static str`-lifetime promise the paired \
8290             From<RestartPolicy> for &'static str impl carries by \
8291             construction"
8292        );
8293    }
8294
8295    #[test]
8296    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
8297        // Cross-axis partition pin: the paired trait-idiomatic
8298        // `From<RestartPolicy> for &'static str` forward projection and
8299        // the method-named [`RestartPolicy::as_str`] forward projection
8300        // must resolve identically on *every* arm, not just the ones
8301        // named in the primary byte-parity pin above. Sweeps every
8302        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
8303        // output byte-equals the method-named accessor's return-value on
8304        // each, locking the two forward-projection paths together by
8305        // construction so any future detour (a stray `From` special-case
8306        // that lands on a divergent per-arm literal outside the paired
8307        // `as_str` dispatch, a hypothetical rebrand touching one axis
8308        // without the other) trips at caixa-core test time. Peer of the
8309        // sibling forward-projection partition pin
8310        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
8311        // (523157d) — extends the round-trip discipline onto the
8312        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
8313        // surface, closing the two-way `Self ↔ &'static str` round-trip
8314        // on the trait-idiomatic pair (`From<Self> for &'static str` +
8315        // `TryFrom<&str> for Self`) as well as the pre-existing method-
8316        // named pair (`as_str` + `from_wire`).
8317        for &variant in RestartPolicy::ALL {
8318            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8319            let via_method: &'static str = variant.as_str();
8320            assert_eq!(
8321                via_trait, via_method,
8322                "From<RestartPolicy> for &'static str and \
8323                 RestartPolicy::as_str must resolve identically on \
8324                 RestartPolicy::{variant:?} — divergence signals the \
8325                 two forward-projection paths have drifted onto different \
8326                 emit-sets"
8327            );
8328        }
8329        // Round-trip witness: every arm's forward `From` output re-parses
8330        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8331        // to the original variant. Closes the two-way `RestartPolicy ↔
8332        // &'static str` round-trip on the trait-idiomatic axis pair,
8333        // mirroring the pre-existing method-named `as_str` + `from_wire`
8334        // round-trip on the substrate-primitive axis pair.
8335        for &variant in RestartPolicy::ALL {
8336            let emitted: &'static str = variant.into();
8337            let re_parsed: Result<RestartPolicy, ()> =
8338                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
8339            assert_eq!(
8340                re_parsed,
8341                Ok(variant),
8342                "trait-idiomatic axis pair must round-trip \
8343                 RestartPolicy::{variant:?} through `.into::<&'static \
8344                 str>()` and back through `TryFrom<&str>` — a break signals \
8345                 the forward-emit and reverse-parse axes have drifted onto \
8346                 different vocabularies"
8347            );
8348        }
8349    }
8350
8351    #[test]
8352    fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
8353        // Fail-before-pass-after byte-parity pin on the newly lifted
8354        // `impl From<&RestartPolicy> for &'static str` — asserts the
8355        // borrowed-input standard-library trait impl and the substrate-
8356        // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
8357        // resolve to the same three-arm emit-set across every arm the
8358        // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
8359        // `From` trait does not auto-derive the borrowed-input sibling
8360        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8361        // where T: Copy, U: From<T>` blanket in `core`), so the
8362        // borrowed-input axis is a distinct trait-idiomatic surface
8363        // that a `.iter().map(Into::into)` shape over
8364        // [`RestartPolicy::ALL`] (whose iterator yields
8365        // `&RestartPolicy`, not `RestartPolicy`) reaches through this
8366        // impl and no other — the paired owned-input
8367        // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
8368        // / dereference before the trait fires. Materializes the
8369        // `<&'static str as From<&RestartPolicy>>::from` output in a
8370        // `const`-shape binding to make the `'static` lifetime promise
8371        // a build-time invariant.
8372        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
8373        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
8374        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
8375        for variant in RestartPolicy::ALL {
8376            let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
8377            let via_method: &'static str = variant.as_str();
8378            assert_eq!(
8379                via_trait, via_method,
8380                "From<&RestartPolicy> for &'static str impl must round-trip \
8381                 &RestartPolicy::{variant:?} to the same lifted \
8382                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
8383                 returns — divergence signals a silent detour off the \
8384                 substrate-primitive accessor"
8385            );
8386            let via_into: &'static str = variant.into();
8387            assert_eq!(
8388                via_into, via_method,
8389                "Into<&'static str>::into on &RestartPolicy::{variant:?} \
8390                 must byte-equal RestartPolicy::as_str on the same input — \
8391                 the blanket-derived Into shape must resolve to the same \
8392                 as_str dispatch as the explicit From impl"
8393            );
8394        }
8395        assert_eq!(
8396            [PERMANENT, TEMPORARY, TRANSIENT],
8397            [
8398                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8399                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8400                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8401            ],
8402            "const-context RestartPolicy::as_str must resolve to the three \
8403             lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
8404             From<&RestartPolicy> for &'static str impl inherits its \
8405             `'static` lifetime promise from the same accessor the \
8406             owned-input sibling routes through"
8407        );
8408    }
8409
8410    #[test]
8411    fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8412        // Cross-axis partition pin: the paired trait-idiomatic
8413        // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
8414        // campaign-shape) and borrowed-input `From<&RestartPolicy> for
8415        // &'static str` (this lift) forward projections must resolve
8416        // identically on every arm, locking the two input-shape paths
8417        // together so any future detour trips at caixa-core test time.
8418        // Then a witness that a `.iter().map(Into::into)` pipe over
8419        // [`RestartPolicy::ALL`] (whose iterator yields
8420        // `&RestartPolicy`) materializes the three-arm accept-set
8421        // through the borrowed-input axis alone — the exact shape a
8422        // future wasm-operator per-child post-exit restart-decision
8423        // diagnostic line, a future substrate-wide per-arm diagnostic
8424        // column, or a
8425        // `HashMap::<&'static str, RestartPolicy>::from_iter(
8426        //     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
8427        // per-policy lookup reaches through — closing the two-way
8428        // owned/borrowed input-shape symmetry on the forward-projection
8429        // trait-idiomatic axis. Peer of the sibling
8430        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8431        // (64aa742) /
8432        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8433        // (5ab993a) /
8434        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8435        // (807b0b5) /
8436        // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8437        // (e941836) partition pins on the sibling closed-set typed-enum
8438        // discriminator axes — extends the borrowed-input axis
8439        // discipline onto the second-of-two M2 OTP-shape closed-set
8440        // typed enum on the caixa surface (per-child restart-decision
8441        // policy). Also closes the direct two-way `&Self → &'static
8442        // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
8443        // — unlike the peer [`crate::CaixaKind`] axis pair (whose
8444        // forward `From` emits lowercase Portuguese diagnostic bytes
8445        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
8446        // forcing the round-trip through an intermediate wire-vocab
8447        // hop), the [`RestartPolicy::as_str`] emit and
8448        // [`RestartPolicy::from_wire`] parse share the same
8449        // `PascalCase` vocabulary by construction, so the borrowed-
8450        // input forward axis and the reverse axis compose directly.
8451        for &variant in RestartPolicy::ALL {
8452            let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8453            let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
8454            assert_eq!(
8455                owned, borrowed,
8456                "From<RestartPolicy> and From<&RestartPolicy> for \
8457                 &'static str must resolve identically on \
8458                 RestartPolicy::{variant:?} — divergence signals the \
8459                 owned-input and borrowed-input forward-projection paths \
8460                 have drifted onto different emit-sets"
8461            );
8462        }
8463        let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
8464        let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
8465        assert_eq!(
8466            via_iter, via_method,
8467            "`.iter().map(Into::into)` over RestartPolicy::ALL must \
8468             byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
8469             borrowed-input `From<&RestartPolicy> for &'static str` axis \
8470             is what makes the `.iter().map(Into::into)` shape route \
8471             through the substrate-primitive `RestartPolicy::as_str` \
8472             accessor rather than through a per-call-site `.copied()` / \
8473             dereference detour"
8474        );
8475        for variant in RestartPolicy::ALL {
8476            let emitted: &'static str = variant.into();
8477            let re_parsed: Result<RestartPolicy, ()> =
8478                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
8479            assert_eq!(
8480                re_parsed,
8481                Ok(*variant),
8482                "trait-idiomatic borrowed-input forward-projection + \
8483                 reverse-projection axis pair must round-trip \
8484                 &RestartPolicy::{variant:?} through `.into::<&'static \
8485                 str>()` (via the borrowed-input axis) and back through \
8486                 `TryFrom<&str>` — a break signals the borrowed-input \
8487                 forward-emit and reverse-parse axes have drifted onto \
8488                 different vocabularies"
8489            );
8490        }
8491    }
8492
8493    #[test]
8494    fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
8495        // Fail-before-pass-after byte-parity pin on the newly lifted
8496        // `impl From<RestartPolicy> for String` — asserts the
8497        // owned-`String`-returning standard-library trait impl and the
8498        // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
8499        // accessor resolve to the same three-arm emit-set across every
8500        // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
8501        // Rust's standard library does not carry a blanket
8502        // `impl<T: AsRef<str>> From<T> for String` (nor an
8503        // `impl<T: fmt::Display> From<T> for String`), so the
8504        // owned-`String` forward-projection axis is a distinct
8505        // trait-idiomatic surface that a `let key: String =
8506        // policy.into();`-shaped call site reaches through this impl
8507        // and no other — the paired sibling `From<RestartPolicy> for
8508        // &'static str` impl forces every owned-`String` call site
8509        // through an explicit `.to_owned()` / `String::from`
8510        // restatement. Peer of the first-mover
8511        // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
8512        // (7baa18a) — extends the trait-idiomatic owned-`String`
8513        // forward-projection axis onto the second-of-two M2 OTP-shape
8514        // closed-set typed enums on the caixa surface (per-child
8515        // restart-decision-policy sibling on the same M2 `:supervisor`
8516        // slot).
8517        for &variant in RestartPolicy::ALL {
8518            let via_trait: String = <String as From<RestartPolicy>>::from(variant);
8519            let via_method: &'static str = variant.as_str();
8520            assert_eq!(
8521                via_trait.as_str(),
8522                via_method,
8523                "From<RestartPolicy> for String impl must round-trip \
8524                 RestartPolicy::{variant:?} to the same lifted \
8525                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
8526                 returns — divergence signals a silent detour off the \
8527                 substrate-primitive accessor"
8528            );
8529            let via_into: String = variant.into();
8530            assert_eq!(
8531                via_into.as_str(),
8532                via_method,
8533                "Into<String>::into on RestartPolicy::{variant:?} must \
8534                 byte-equal RestartPolicy::as_str on the same input — the \
8535                 blanket-derived Into shape must resolve to the same as_str \
8536                 dispatch as the explicit From impl"
8537            );
8538        }
8539    }
8540
8541    #[test]
8542    fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
8543        // Cross-axis partition pin: the paired trait-idiomatic
8544        // owned-`String` `From<RestartPolicy> for String` (this lift)
8545        // and owned-`&'static str` `From<RestartPolicy> for &'static
8546        // str` (9fb37d0) forward projections must resolve identically
8547        // on every arm, locking the two return-type-shape paths
8548        // together so any future detour trips at caixa-core test time.
8549        // Also byte-parity witness against the sibling
8550        // [`ToString::to_string`] surface routed through
8551        // [`std::fmt::Display`] — the three owned-heap-string paths
8552        // (`.into::<String>()`, `String::from`, `.to_string()`) must
8553        // resolve identically on every arm so a future consumer that
8554        // picks any of the three lands on the same lifted
8555        // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
8556        // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
8557        // that materializes the three-arm accept-set through the
8558        // owned-`String` axis alone — the exact shape a future
8559        // wasm-operator per-child post-exit restart-decision
8560        // diagnostic line composer or a
8561        // `HashMap::<String, RestartPolicy>::from_iter(
8562        //     RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
8563        // owned-key per-policy lookup reaches through — closing the
8564        // owned-`String` forward-projection axis's iterator-pipe
8565        // shape. Then a direct round-trip witness through the paired
8566        // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
8567        // owned-`String`'s [`String::as_str`] borrow that closes the
8568        // two-way `Self → String → Self` round-trip on the trait-
8569        // idiomatic owned-`String` forward + reverse axis pair —
8570        // unlike the peer [`crate::CaixaKind`] axis pair (whose
8571        // forward `From` emits lowercase Portuguese diagnostic bytes
8572        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
8573        // forcing the round-trip through an intermediate wire-vocab
8574        // hop), the [`RestartPolicy::as_str`] emit and
8575        // [`RestartPolicy::from_wire`] parse share the same
8576        // `PascalCase` vocabulary by construction, so the owned-
8577        // `String` forward axis and the reverse axis compose directly.
8578        for &variant in RestartPolicy::ALL {
8579            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
8580            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8581            assert_eq!(
8582                owned_string.as_str(),
8583                owned_static,
8584                "From<RestartPolicy> for String and From<RestartPolicy> \
8585                 for &'static str must resolve identically on \
8586                 RestartPolicy::{variant:?} — divergence signals the \
8587                 owned-`String` and owned-`&'static str` forward-projection \
8588                 return-type-shape paths have drifted onto different \
8589                 emit-sets"
8590            );
8591            let via_to_string: String = variant.to_string();
8592            assert_eq!(
8593                owned_string, via_to_string,
8594                "From<RestartPolicy> for String must byte-equal \
8595                 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
8596                 divergence signals the trait-idiomatic owned-`String` \
8597                 forward-projection axis and the ToString-through-Display \
8598                 axis have drifted onto different emit-sets"
8599            );
8600        }
8601        let via_iter: Vec<String> = RestartPolicy::ALL
8602            .iter()
8603            .copied()
8604            .map(String::from)
8605            .collect();
8606        let via_method: Vec<String> = RestartPolicy::ALL
8607            .iter()
8608            .map(|p| p.as_str().to_owned())
8609            .collect();
8610        assert_eq!(
8611            via_iter, via_method,
8612            "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
8613             must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
8614             every arm — the owned-`String` `From<RestartPolicy> for \
8615             String` axis is what makes the `String::from` composition \
8616             route through the substrate-primitive `RestartPolicy::as_str` \
8617             accessor rather than through a per-call-site `.to_owned()` / \
8618             `String::from(policy.as_str())` detour"
8619        );
8620        for &variant in RestartPolicy::ALL {
8621            let emitted: String = variant.into();
8622            let re_parsed: Result<RestartPolicy, ()> =
8623                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
8624            assert_eq!(
8625                re_parsed,
8626                Ok(variant),
8627                "trait-idiomatic owned-`String` forward-projection + \
8628                 reverse-projection axis pair must round-trip \
8629                 RestartPolicy::{variant:?} through `.into::<String>()` \
8630                 and back through `TryFrom<&str>` on the owned-`String`'s \
8631                 String::as_str borrow — a break signals the owned-`String` \
8632                 forward-emit and reverse-parse axes have drifted onto \
8633                 different vocabularies"
8634            );
8635        }
8636    }
8637
8638    #[test]
8639    fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
8640        // Fail-before-pass-after byte-parity pin on the newly lifted
8641        // `impl From<&RestartPolicy> for String` — asserts the
8642        // borrowed-input owned-`String`-returning standard-library
8643        // trait impl and the substrate-primitive
8644        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
8645        // the same three-arm emit-set across every arm the exhaustive
8646        // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
8647        // library does not carry a blanket `impl<T: AsRef<str>>
8648        // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
8649        // for String`), so the borrowed-input owned-`String` forward-
8650        // projection axis is a distinct trait-idiomatic surface that a
8651        // `let key: String = (&policy).into();`-shaped call site
8652        // reaches through this impl and no other — the paired sibling
8653        // `From<RestartPolicy> for String` impl forces every borrowed-
8654        // input call site through an explicit `Copy` deref
8655        // (`String::from(*policy)`) or an `.as_str().to_owned()` /
8656        // `.to_string()` detour. Peer of the first-mover
8657        // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
8658        // (579385f) — extends the trait-idiomatic borrowed-input
8659        // owned-`String` forward-projection axis onto the second-of-
8660        // two M2 OTP-shape closed-set typed enums on the caixa surface
8661        // (per-child restart-decision-policy sibling on the same M2
8662        // `:supervisor` slot).
8663        for &variant in RestartPolicy::ALL {
8664            let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
8665            let via_method: &'static str = variant.as_str();
8666            assert_eq!(
8667                via_trait.as_str(),
8668                via_method,
8669                "From<&RestartPolicy> for String impl must round-trip \
8670                 &RestartPolicy::{variant:?} to the same lifted \
8671                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
8672                 returns — divergence signals a silent detour off the \
8673                 substrate-primitive accessor"
8674            );
8675            let via_into: String = (&variant).into();
8676            assert_eq!(
8677                via_into.as_str(),
8678                via_method,
8679                "Into<String>::into on &RestartPolicy::{variant:?} must \
8680                 byte-equal RestartPolicy::as_str on the same input — \
8681                 the blanket-derived Into shape must resolve to the \
8682                 same as_str dispatch as the explicit From impl"
8683            );
8684        }
8685    }
8686
8687    #[test]
8688    fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
8689        // Cross-axis partition pin: the newly lifted trait-idiomatic
8690        // borrowed-input owned-`String` `From<&RestartPolicy> for
8691        // String` (this lift), the paired owned-input owned-`String`
8692        // `From<RestartPolicy> for String` (7851725), the paired
8693        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
8694        // for &'static str` (842c7f3), and the paired owned-input
8695        // owned-`&'static str` `From<RestartPolicy> for &'static str`
8696        // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
8697        // str, String}` 2×2 trait-idiomatic projection family — must
8698        // resolve identically on every arm, locking the four
8699        // return-shape × input-shape paths together so any future
8700        // detour trips at caixa-core test time. Also byte-parity
8701        // witness against the sibling [`ToString::to_string`] surface
8702        // routed through [`std::fmt::Display`] and a direct round-trip
8703        // witness through the paired trait-idiomatic reverse
8704        // [`TryFrom<&str>`] axis on the owned-`String`'s
8705        // [`String::as_str`] borrow that closes the two-way
8706        // `&Self → String → Self` round-trip on the trait-idiomatic
8707        // borrowed-input owned-`String` forward + reverse axis pair.
8708        // Peer of the first-mover
8709        // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
8710        // (579385f) — closes the whole `{Self, &Self} × {&'static str,
8711        // String}` 2×2 projection corner on both M2 OTP-shape sibling
8712        // peers.
8713        for &variant in RestartPolicy::ALL {
8714            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
8715            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
8716            let borrowed_static: &'static str =
8717                <&'static str as From<&RestartPolicy>>::from(&variant);
8718            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8719            assert_eq!(
8720                borrowed_string, owned_string,
8721                "From<&RestartPolicy> for String and From<RestartPolicy> \
8722                 for String must resolve identically on \
8723                 RestartPolicy::{variant:?} — divergence signals the \
8724                 borrowed-input and owned-input owned-`String` \
8725                 forward-projection input-shape paths have drifted onto \
8726                 different emit-sets"
8727            );
8728            assert_eq!(
8729                borrowed_string.as_str(),
8730                borrowed_static,
8731                "From<&RestartPolicy> for String and From<&RestartPolicy> \
8732                 for &'static str must resolve identically on \
8733                 RestartPolicy::{variant:?} — divergence signals the \
8734                 borrowed-input `&'static str` and owned-`String` \
8735                 return-shape paths have drifted onto different \
8736                 emit-sets"
8737            );
8738            assert_eq!(
8739                borrowed_string.as_str(),
8740                owned_static,
8741                "From<&RestartPolicy> for String and From<RestartPolicy> \
8742                 for &'static str must resolve identically on \
8743                 RestartPolicy::{variant:?} — divergence signals a \
8744                 break in the diagonal corner of the {{Self, &Self}} × \
8745                 {{&'static str, String}} 2×2 trait-idiomatic \
8746                 projection family"
8747            );
8748            let via_to_string: String = variant.to_string();
8749            assert_eq!(
8750                borrowed_string, via_to_string,
8751                "From<&RestartPolicy> for String must byte-equal \
8752                 RestartPolicy::to_string on RestartPolicy::{variant:?} \
8753                 — divergence signals the trait-idiomatic borrowed-input \
8754                 owned-`String` forward-projection axis and the \
8755                 ToString-through-Display axis have drifted onto \
8756                 different emit-sets"
8757            );
8758        }
8759        let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
8760        let via_method: Vec<String> = RestartPolicy::ALL
8761            .iter()
8762            .map(|p| p.as_str().to_owned())
8763            .collect();
8764        assert_eq!(
8765            via_iter, via_method,
8766            "`.iter().map(String::from)` over RestartPolicy::ALL — a \
8767             call site whose iteration axis holds `&RestartPolicy` by \
8768             construction — must byte-equal `.iter().map(|p| \
8769             p.as_str().to_owned())` on every arm — the borrowed-input \
8770             owned-`String` `From<&RestartPolicy> for String` axis is \
8771             what makes the `String::from` composition route through \
8772             the substrate-primitive `RestartPolicy::as_str` accessor \
8773             without a spurious `Copy` deref (which would only be \
8774             reachable through the owned-input `From<RestartPolicy> \
8775             for String` axis by first calling `.copied()` on the \
8776             iterator)"
8777        );
8778        for &variant in RestartPolicy::ALL {
8779            let emitted: String = (&variant).into();
8780            let re_parsed: Result<RestartPolicy, ()> =
8781                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
8782            assert_eq!(
8783                re_parsed,
8784                Ok(variant),
8785                "trait-idiomatic borrowed-input owned-`String` \
8786                 forward-projection + reverse-projection axis pair must \
8787                 round-trip &RestartPolicy::{variant:?} through \
8788                 `.into::<String>()` on the borrowed-input surface and \
8789                 back through `TryFrom<&str>` on the owned-`String`'s \
8790                 String::as_str borrow — a break signals the \
8791                 borrowed-input owned-`String` forward-emit and \
8792                 reverse-parse axes have drifted onto different \
8793                 vocabularies"
8794            );
8795        }
8796    }
8797
8798    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
8799
8800    #[test]
8801    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
8802        // The fail-before-pass-after pin: pre-lift there was no
8803        // single-source binding between the [`RestartPolicy`] variant
8804        // name the un-`rename`d `Serialize` derive emits under
8805        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
8806        // byte-string every downstream cluster-side dispatcher (the
8807        // future wasm-operator's per-child post-exit restart-decision
8808        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8809        // materializer's admission-time enum-arm bind, the
8810        // `caixa-operator`'s hierarchical reconciliation scheduler's
8811        // per-child-policy fan-out) probes verbatim. A future
8812        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
8813        // or a per-variant `#[serde(rename = "…")]` override, or a
8814        // variant rename in the source — would silently rebrand the
8815        // emitted scalar under one spelling while every downstream
8816        // dispatcher still probed the other, with the failure surfacing
8817        // at the operator's reconcile posture (children coming up under
8818        // the `default()` `Permanent` arm rather than the typed slot's
8819        // declared policy — a `:temporary` `oneShot` child would be
8820        // restarted on clean exit, treating the successful-completion
8821        // signal as failure and re-running the completion-terminal
8822        // one-shot indefinitely; a `:transient` child that clean-exited
8823        // would be restarted, masking the clean-completion contract)
8824        // far from the source rebrand commit and with no field naming
8825        // the drift. Pinning the two paths (the `Serialize` derive's
8826        // serialized string AND the [`RestartPolicy::as_str`] helper)
8827        // to the same three lifted
8828        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
8829        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
8830        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
8831        // byte-strings makes any future drift on either endpoint fail
8832        // here at caixa-core build time. Peer of the sibling
8833        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
8834        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
8835        // and the M3
8836        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
8837        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
8838        // same three-path-convergence discipline, extended to close the
8839        // third OTP-shaped closed-enum discriminator axis on the caixa
8840        // typed surface (per-child restart-decision policy).
8841        for (variant, expected) in [
8842            (
8843                RestartPolicy::Permanent,
8844                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8845            ),
8846            (
8847                RestartPolicy::Temporary,
8848                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8849            ),
8850            (
8851                RestartPolicy::Transient,
8852                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8853            ),
8854        ] {
8855            let json = serde_json::to_string(&variant).unwrap();
8856            assert_eq!(
8857                json,
8858                format!("\"{expected}\""),
8859                "RestartPolicy::{variant:?} must serialize to {expected:?}"
8860            );
8861            assert_eq!(
8862                variant.as_str(),
8863                expected,
8864                "RestartPolicy::{variant:?}.as_str() must return the lifted \
8865                 SUPERVISOR_CHILD_RESTART_* constant"
8866            );
8867        }
8868    }
8869
8870    #[test]
8871    fn supervisor_child_restart_consts_are_pairwise_distinct() {
8872        // Cross-arm drift-detection pin: a future collapse of two
8873        // canonical variant byte-strings onto the same value (e.g. an
8874        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
8875        // to also read `"Permanent"`) would silently reroute every
8876        // downstream operator's per-child-policy dispatch onto the
8877        // sibling arm's reconcile branch and pass every propagation-probe
8878        // test that expected only the stale arm's value — a `:transient`
8879        // child would come up under the `:permanent` restart-decision
8880        // posture on every subsequent clean exit, so a completion-terminal
8881        // child would be restarted indefinitely against its declared
8882        // policy. Peer of the sibling
8883        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
8884        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
8885        // and the four-way distinct pin
8886        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
8887        // top-level `SUPERVISOR_KEY_*` axis.
8888        let all = [
8889            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8890            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8891            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8892        ];
8893        for (i, a) in all.iter().enumerate() {
8894            for (j, b) in all.iter().enumerate() {
8895                if i != j {
8896                    assert_ne!(
8897                        a, b,
8898                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
8899                         — got duplicate {a:?} at indices {i} and {j}",
8900                    );
8901                }
8902            }
8903        }
8904    }
8905
8906    #[test]
8907    fn restart_policy_display_routes_through_as_str_helper() {
8908        // The fail-before-pass-after pin on the first half of the
8909        // three-path convergence: pre-convergence [`RestartPolicy`]
8910        // carried a [`std::fmt::Display`] surface via its
8911        // `#[discriminant(also_display)]` gen-platform derive route,
8912        // which arrived kebab-case as `"permanent"` / `"temporary"`
8913        // / `"transient"` on this three-arm enum (whose variant
8914        // names each collapse to their own lowercase form under the
8915        // kebab-case transform) while the wire format ran as
8916        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
8917        // through the un-`rename`d serde derive. Every consumer
8918        // reaching for a policy byte-string past the wire format had
8919        // to pick between three paths ([`RestartPolicy::as_str`],
8920        // the `Serialize` derive's serialized string, or
8921        // `format!("{v}")` on the discriminant-Display route), any
8922        // two of which a future variant rename or
8923        // `#[serde(rename_all = "kebab-case")]` attribute would
8924        // silently desynchronize. Wiring [`std::fmt::Display`]
8925        // through [`RestartPolicy::as_str`] closes the third path:
8926        // every `format!("{v}")` call reaches the same lifted
8927        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
8928        // wire format and the [`RestartPolicy::as_str`] helper
8929        // already route through, so a future variant rename lands at
8930        // exactly one place. Pin the routing here so a future
8931        // `impl std::fmt::Display for RestartPolicy`
8932        // reimplementation that hand-rolls the arms instead of
8933        // delegating to [`RestartPolicy::as_str`] fails at
8934        // caixa-core build time. Peer of the sibling
8935        // [`restart_strategy_display_routes_through_as_str_helper`]
8936        // on the per-supervisor sibling-restart-strategy axis and
8937        // the M3
8938        // `placement_strategy_display_routes_through_as_str_helper`
8939        // (cc8f749) — the third of three OTP-shape closed-enum
8940        // discriminator axes on the caixa typed surface now
8941        // converged onto the same three-path
8942        // (Display → as_str → lifted const) discipline.
8943        for variant in [
8944            RestartPolicy::Permanent,
8945            RestartPolicy::Temporary,
8946            RestartPolicy::Transient,
8947        ] {
8948            assert_eq!(
8949                variant.to_string(),
8950                variant.as_str(),
8951                "RestartPolicy::{variant:?} Display must route through \
8952                 RestartPolicy::as_str (single source of truth: the lifted \
8953                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
8954            );
8955        }
8956    }
8957
8958    #[test]
8959    fn restart_policy_display_matches_serialized_wire_byte_string() {
8960        // The fail-before-pass-after pin on the second half of the
8961        // three-path convergence: `Display` (user-facing text) agrees
8962        // byte-for-byte with the `Serialize` derive's wire format
8963        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
8964        // scalar) on every variant. Pre-convergence the two paths
8965        // were structurally independent — a future
8966        // `#[serde(rename_all = "kebab-case")]` attribute on the
8967        // enum would silently rebrand the emitted wire scalar
8968        // (`permanent`, `temporary`, `transient`) while every
8969        // consumer that pretty-prints the policy (the future
8970        // wasm-operator's per-child post-exit restart-decision
8971        // diagnostic line, the future `feira app graph` per-child
8972        // restart column, the future M4
8973        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
8974        // per-child admission-webhook rejection body) would still
8975        // emit the PascalCase form the `as_str` / `Display` route
8976        // returns, with the mismatch surfacing at consumer parse
8977        // time / operator dispatch time far from the source rebrand
8978        // commit. Pin the two paths byte-for-byte here so any future
8979        // serde-attribute or variant-rename drift is a
8980        // caixa-core-build-time test failure at this call, not a
8981        // silent per-consumer dispatch miss. Peer of the sibling
8982        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
8983        // on the per-supervisor sibling-restart-strategy axis and
8984        // the M3
8985        // `placement_strategy_display_matches_serialized_wire_byte_string`
8986        // (cc8f749).
8987        for variant in [
8988            RestartPolicy::Permanent,
8989            RestartPolicy::Temporary,
8990            RestartPolicy::Transient,
8991        ] {
8992            let wire = serde_json::to_string(&variant).unwrap();
8993            let unquoted = wire
8994                .strip_prefix('"')
8995                .and_then(|s| s.strip_suffix('"'))
8996                .expect("serialized RestartPolicy is a JSON string");
8997            assert_eq!(
8998                variant.to_string(),
8999                unquoted,
9000                "RestartPolicy::{variant:?} Display byte-string must match the \
9001                 Serialize derive's wire byte-string (three-path convergence: \
9002                 Display + as_str + Serialize all resolve to the same \
9003                 SUPERVISOR_CHILD_RESTART_* const)"
9004            );
9005        }
9006    }
9007
9008    #[test]
9009    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
9010        // Fail-before-pass-after byte-parity pin on the lifted
9011        // `impl AsRef<str> for RestartPolicy` — asserts the
9012        // standard-library trait impl and the substrate-primitive
9013        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
9014        // to the same `&str` per instance across the three-arm
9015        // closed set, so any future silent detour that routes the
9016        // impl through a divergent projection (a per-arm inline
9017        // `match self { RestartPolicy::Permanent => "Permanent", … }`
9018        // re-inlining that opens a compile-time link to the un-lifted
9019        // arm-literal, a swap onto the kebab-case
9020        // [`gen_platform::Discriminant`] catalog identity that would
9021        // collide the wire axis with the dispatcher-catalog axis) trips
9022        // at caixa-core test time under `PartialEq` rather than at a
9023        // downstream `impl AsRef<str>`-bound consumer's silent split.
9024        // Sweeps every one of the three arms
9025        // [`RestartPolicy::ALL`] carries so no arm's projection is
9026        // covered only by the sibling wire-format `Serialize` derive
9027        // path. Peer of the sibling
9028        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
9029        // (63eb1a4) on the paired per-supervisor sibling-restart-
9030        // strategy axis and the [`crate::CaixaVersion`]
9031        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
9032        // top-level `:versao` typed newtype — the three pins together
9033        // cover the substrate primitive's `AsRef<str>` projection axis
9034        // on the paired newtype + M2 closed-set-typed-enum surface.
9035        for &variant in RestartPolicy::ALL {
9036            assert_eq!(
9037                <RestartPolicy as AsRef<str>>::as_ref(&variant),
9038                variant.as_str(),
9039                "AsRef<str> impl on RestartPolicy::{variant:?} must \
9040                 byte-equal RestartPolicy::as_str on the same instance \
9041                 — divergence signals a silent detour off the substrate-\
9042                 primitive accessor"
9043            );
9044        }
9045    }
9046
9047    #[test]
9048    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
9049        // Fail-before-pass-after byte-parity pin on the three-path
9050        // convergence discipline the M2 per-child-restart-policy
9051        // primitive now carries on the `&str`-projection axis:
9052        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
9053        // lifted impl), `format!("{v}")` (the pre-existing
9054        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
9055        // primitive `pub const fn` accessor both trait impls delegate
9056        // through) must resolve to the same byte-string on every
9057        // instance across the three-arm closed set. Refuses any future
9058        // divergence between the two trait impls (a stray
9059        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
9060        // rather than delegating through the shared accessor; a
9061        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
9062        // literal cascade) that would silently split the two
9063        // projection paths of the same closed-set typed enum. Mirrors
9064        // the sibling three-path-convergence discipline the peer
9065        // [`RestartStrategy`] typed enum carries on its
9066        // `AsRef<str>` / `Display` / `as_str` triple
9067        // (supervisor.rs pin
9068        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
9069        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
9070        // carries on the same triple (version.rs pin
9071        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
9072        // 16d5c7e).
9073        for &variant in RestartPolicy::ALL {
9074            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
9075            let via_display: String = format!("{variant}");
9076            let via_accessor: &str = variant.as_str();
9077            assert_eq!(via_as_ref, via_accessor);
9078            assert_eq!(via_display, via_accessor);
9079            assert_eq!(via_as_ref, via_display.as_str());
9080        }
9081    }
9082
9083    #[test]
9084    fn restart_policy_all_enumerates_every_variant_exactly_once() {
9085        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
9086        // exhaustive-iteration surface: every variant appears exactly
9087        // once, and the slice length matches the arm count of the
9088        // closed set. Every consumer that walks the accepted-policy
9089        // set (a future `feira supervisor --restart …` CLI-side
9090        // arg-parse's "did you mean" hint, a future M4 admission-
9091        // webhook's per-child rejection body naming the accepted-
9092        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
9093        // projection consumers that iterate the accept-set for
9094        // diagnostic rendering) reads through this slice, so a future
9095        // arm addition that grows the enum but forgets to grow
9096        // [`Self::ALL`] silently truncates every downstream consumer's
9097        // accept-set at the same pre-addition boundary — this pin
9098        // fails at caixa-core build time on the pairwise-distinct +
9099        // arm-count invariants.
9100        //
9101        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
9102        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
9103        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
9104        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
9105        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
9106        // pins on the peer closed-set typed-enum axes.
9107        let all: &[RestartPolicy] = RestartPolicy::ALL;
9108        assert_eq!(
9109            all.len(),
9110            3,
9111            "RestartPolicy::ALL must enumerate every variant of the \
9112             three-arm closed set (Permanent, Temporary, Transient); \
9113             got {all:?}"
9114        );
9115        for (i, a) in all.iter().enumerate() {
9116            for (j, b) in all.iter().enumerate() {
9117                if i != j {
9118                    assert_ne!(
9119                        a, b,
9120                        "RestartPolicy::ALL must carry every variant exactly \
9121                         once — got duplicate {a:?} at indices {i} and {j}"
9122                    );
9123                }
9124            }
9125        }
9126        for variant in [
9127            RestartPolicy::Permanent,
9128            RestartPolicy::Temporary,
9129            RestartPolicy::Transient,
9130        ] {
9131            assert!(
9132                all.contains(&variant),
9133                "RestartPolicy::ALL must contain {variant:?} — a future arm \
9134                 addition that grows the enum but forgets to grow the ALL slice \
9135                 silently truncates every downstream consumer's accept-set at \
9136                 the pre-addition boundary"
9137            );
9138        }
9139    }
9140
9141    #[test]
9142    fn restart_policy_from_wire_accepts_every_lifted_constant() {
9143        // Fail-before-pass-after pin on the forward accept-set of the
9144        // [`RestartPolicy::from_wire`] reverse projection: every
9145        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
9146        // constant the [`RestartPolicy::as_str`] emitter walks parses
9147        // back to its paired variant. Any future arm addition that
9148        // grows the emitter's `as_str` match but forgets to grow the
9149        // parser's `from_wire` match silently splits the two halves of
9150        // the round-trip — the wire byte-string one non-serde consumer
9151        // parses from the one the emitter wrote — with the failure
9152        // surfacing at the operator's reconcile posture (a `:temporary`
9153        // `oneShot` child restarted on clean exit, a `:transient` child
9154        // restarted after clean completion) far from the rebrand
9155        // commit. Pinning the three-arm accept-set here catches the
9156        // drift at caixa-core build time.
9157        //
9158        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
9159        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
9160        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
9161        // accept-set pins on the peer closed-set typed-enum `str → Self`
9162        // axes.
9163        for (wire, expected) in [
9164            (
9165                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9166                RestartPolicy::Permanent,
9167            ),
9168            (
9169                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9170                RestartPolicy::Temporary,
9171            ),
9172            (
9173                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9174                RestartPolicy::Transient,
9175            ),
9176        ] {
9177            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
9178                panic!(
9179                    "RestartPolicy::from_wire({wire:?}) must accept every \
9180                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
9181                     lifted canonical byte-string that RestartPolicy::{expected:?} \
9182                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
9183                )
9184            });
9185            assert_eq!(
9186                parsed, expected,
9187                "RestartPolicy::from_wire({wire:?}) must return \
9188                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
9189            );
9190        }
9191    }
9192
9193    #[test]
9194    fn restart_policy_from_wire_round_trips_through_as_str() {
9195        // Fail-before-pass-after pin on the closed round-trip between
9196        // the forward [`RestartPolicy::as_str`] emitter and the
9197        // reverse [`RestartPolicy::from_wire`] parser: for every
9198        // variant in [`RestartPolicy::ALL`], parsing the emitter's
9199        // output must return exactly the same variant. Any per-arm
9200        // divergence — a future arm added to `as_str` but not
9201        // `from_wire`, an accidental copy-paste flip in one but not
9202        // the other — silently splits the emit and parse halves and
9203        // the failure surfaces at consumer parse time far from the
9204        // drift site. The `ALL`-iterating shape means a future arm
9205        // addition picks up the coverage by construction.
9206        //
9207        // Peer of the sibling
9208        // [`restart_strategy_from_wire_round_trips_through_as_str`]
9209        // (4eec29c) round-trip pin on
9210        // [`RestartStrategy::from_wire`] and the M3
9211        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
9212        // (18c7342) round-trip pin on
9213        // [`crate::aplicacao::PlacementStrategy::from_wire`].
9214        for &variant in RestartPolicy::ALL {
9215            let wire = variant.as_str();
9216            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
9217                panic!(
9218                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
9219                     must be Some({variant:?}) — the two halves of the round-trip \
9220                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
9221                     got None on wire byte-string {wire:?}"
9222                )
9223            });
9224            assert_eq!(
9225                parsed, variant,
9226                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
9227                 must round-trip to the same variant; got {parsed:?}"
9228            );
9229        }
9230    }
9231
9232    #[test]
9233    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
9234        // Fail-before-pass-after pin on the closed-set refusal
9235        // discipline of [`RestartPolicy::from_wire`]: every
9236        // byte-string outside the three-arm accept-set returns `None`
9237        // rather than silently collapsing onto the [`Default`]
9238        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
9239        // exercised here sweeps the load-bearing drift shapes: the
9240        // empty string (a stripped serde-attribute drift), all-
9241        // whitespace strings (the canonical text-editor accidental
9242        // padding shape), the kebab-case dispatcher-catalog identities
9243        // (`"permanent"` / `"temporary"` / `"transient"` — the
9244        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
9245        // accept-set, which parses the *other* axis of this enum's
9246        // two-axis split and must not leak into the `from_wire`
9247        // PascalCase-wire accept-set — a lowercase leak here would
9248        // silently accept the operator's kebab-case
9249        // dispatcher-catalog probe under the wire-axis parser and mis-
9250        // route a `:permanent` intent), the padded canonical scalar
9251        // (`" Permanent "`), the trailing-newline shapes
9252        // (`"Permanent\n"`), the uppercase-single-word forms
9253        // (`"PERMANENT"`), and neighboring-but-unknown arms
9254        // (`"Restart"` — the canonical typo direction toward the
9255        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
9256        //
9257        // Peer of the sibling
9258        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
9259        // (4eec29c) +
9260        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
9261        // (2aa6d23) +
9262        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
9263        // (18c7342) refusal pins on the peer closed-set typed-enum
9264        // axes.
9265        for bad in [
9266            "",
9267            " ",
9268            "\n",
9269            "\t",
9270            "permanent",
9271            "temporary",
9272            "transient",
9273            "PERMANENT",
9274            "TEMPORARY",
9275            "TRANSIENT",
9276            "Permanents",
9277            "Permanent ",
9278            " Permanent",
9279            " Transient ",
9280            "Permanent\n",
9281            "perma",
9282            "Trans",
9283            "OneForOne",
9284            "Restart",
9285            "?",
9286        ] {
9287            assert!(
9288                RestartPolicy::from_wire(bad).is_none(),
9289                "RestartPolicy::from_wire({bad:?}) must return None — the \
9290                 parser's accept-set is exactly the three RestartPolicy::as_str \
9291                 outputs (Permanent, Temporary, Transient), and this \
9292                 byte-string is outside that closed set"
9293            );
9294        }
9295    }
9296
9297    #[test]
9298    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
9299        // Fail-before-pass-after pin on the fourth path of the four-path
9300        // convergence: `from_wire` (the reverse projection) inverts the
9301        // `Serialize` derive's wire byte-string on every variant.
9302        // Together with the pre-existing three-path convergence
9303        // (`Display` + `as_str` + `Serialize` all resolve to the same
9304        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
9305        // pinned by
9306        // [`restart_policy_display_matches_serialized_wire_byte_string`])
9307        // this closes the round-trip: the wire byte-string the
9308        // `Serialize` derive emits parses back to the same variant
9309        // through `from_wire`, so any future serde-attribute or variant-
9310        // rename drift on the emit half now surfaces as a matched drift
9311        // on the parse half at caixa-core build time — the two halves
9312        // migrate as a unit through the lifted consts on any future
9313        // rename, and the round-trip cannot silently split.
9314        //
9315        // Peer of the sibling
9316        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
9317        // (4eec29c) wire-format pin on
9318        // [`RestartStrategy::from_wire`] and the M3
9319        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
9320        // (18c7342) wire-format pin on
9321        // [`crate::aplicacao::PlacementStrategy::from_wire`].
9322        for &variant in RestartPolicy::ALL {
9323            let wire = serde_json::to_string(&variant).unwrap();
9324            let unquoted = wire
9325                .strip_prefix('"')
9326                .and_then(|s| s.strip_suffix('"'))
9327                .expect("serialized RestartPolicy is a JSON string");
9328            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
9329                panic!(
9330                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
9331                     Serialize derive's wire byte-string for \
9332                     RestartPolicy::{variant:?} — the four-path convergence \
9333                     (Display + as_str + Serialize + from_wire) resolves through \
9334                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
9335                )
9336            });
9337            assert_eq!(
9338                parsed, variant,
9339                "RestartPolicy::from_wire of the Serialize derive's wire \
9340                 byte-string for RestartPolicy::{variant:?} must round-trip \
9341                 to the same variant; got {parsed:?}"
9342            );
9343        }
9344    }
9345
9346    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
9347    //
9348    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
9349    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
9350    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
9351    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
9352    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
9353    // the peer per-`:upgrade-from :from` axis. The three pins jointly
9354    // brace the accessor against every future silent detour that would
9355    // desynchronize it from the raw `.caixa` field access every consumer
9356    // previously open-coded.
9357
9358    #[test]
9359    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
9360        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
9361        // [`ChildSpec::nome`] must return the `:children :caixa` field
9362        // byte-for-byte across every DNS-1123-label value the upstream
9363        // [`crate::render::require_valid_dns_1123_label`] gate at
9364        // `SupervisorSpec::validate` admits. Peer of the sibling
9365        // `membro_nome_returns_caixa_byte_equal_across_permutations`
9366        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
9367        // substrate-primitive accessor must byte-equal the raw field
9368        // access verbatim across every author-declared value" discipline
9369        // extended to the M2 supervisor-tree per-`:children` arm. Pins
9370        // against a future silent detour that re-normalized the child
9371        // identity (an accidental `.to_lowercase()` — every `:children
9372        // :caixa` is validated as a DNS-1123 label upstream, so any
9373        // re-normalization is redundant + a drift surface between the
9374        // validator and the accessor), a namespace-prefix rewrite (an
9375        // accidental `format!("{namespace}/{caixa}")` per-CR
9376        // fully-qualified rewrite that didn't land on the peer axes), or
9377        // a per-cluster alias stamp the future wasm-operator's
9378        // hierarchical reconciliation scheduler authors on one consumer
9379        // without the others. Five values sweep the accept-set the
9380        // DNS-1123 gate upstream admits (short single-word / dashed /
9381        // v-suffixed / mixed-digit child names).
9382        for name in [
9383            "worker",
9384            "cache-server",
9385            "scratch-job",
9386            "orders-v2",
9387            "session-8080",
9388        ] {
9389            let c = ChildSpec {
9390                caixa: name.into(),
9391                versao: "^0.1".into(),
9392                restart: RestartPolicy::Permanent,
9393            };
9394            assert_eq!(
9395                c.nome(),
9396                name,
9397                "ChildSpec::nome must return :children :caixa verbatim \
9398                 (got {:?}, expected {name:?})",
9399                c.nome(),
9400            );
9401            assert_eq!(
9402                c.nome(),
9403                c.caixa.as_str(),
9404                "ChildSpec::nome must byte-equal the .caixa field access",
9405            );
9406        }
9407    }
9408
9409    #[test]
9410    fn child_spec_nome_borrows_from_caixa_storage() {
9411        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
9412        // `&str` slice that borrows from the typed slot's own [`String`]
9413        // storage — same-address invariant with `c.caixa.as_str()`. Pins
9414        // against a future silent detour that allocated a fresh `String`
9415        // (`self.caixa.clone()` in the body would type-check but silently
9416        // drop the borrow, and every downstream consumer that assumed
9417        // the returned slice outlives `&self` would break on a stale-
9418        // reference use-after-free — the [`crate::render::insert_first_seen`]
9419        // dedup key at [`SupervisorSpec::validate`], the
9420        // [`validate_no_self_supervision`] equality check against the
9421        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
9422        // borrow — each would silently misbehave if this accessor
9423        // produced a detached copy). Peer of the sibling
9424        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
9425        // M3 per-`:membros` axis and the
9426        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
9427        // first M2 slot scalar accessor.
9428        let c = ChildSpec {
9429            caixa: "worker".into(),
9430            versao: "^0.1".into(),
9431            restart: RestartPolicy::Permanent,
9432        };
9433        let name = c.nome();
9434        let caixa_slice = c.caixa.as_str();
9435        assert_eq!(
9436            name.as_ptr(),
9437            caixa_slice.as_ptr(),
9438            "ChildSpec::nome must borrow from the .caixa String's backing \
9439             storage — a fresh allocation here means the accessor no \
9440             longer names the substrate-primitive typed dispatch and \
9441             every downstream consumer would silently carry a detached \
9442             copy",
9443        );
9444        assert_eq!(
9445            name.len(),
9446            caixa_slice.len(),
9447            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
9448             as well as in address",
9449        );
9450    }
9451
9452    #[test]
9453    fn validate_gates_child_nome_through_lifted_accessor() {
9454        // Bilateral coherence pin: every `:children :caixa` that
9455        // [`SupervisorSpec::validate`] accepts is one
9456        // [`crate::render::require_valid_dns_1123_label`] accepts on the
9457        // accessor-projected value, and vice versa on the reject side.
9458        // This closes the "the validator reads through the accessor"
9459        // contract structurally — a future silent detour that made the
9460        // accessor return a different byte-string than the validator
9461        // gates against would surface here as a coverage mismatch, not
9462        // as an apply-time DNS-1123 rejection at
9463        // `metadata.name: Invalid value` far from the caixa.lisp source.
9464        // Peer of the M2 sibling
9465        // `validate_parses_prior_versao_through_lifted_accessor`
9466        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
9467        // `validate_membros` peer discipline.
9468        //
9469        // Accept-set sweep: five DNS-1123-label values the upstream gate
9470        // admits.
9471        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
9472            let s = SupervisorSpec {
9473                children: vec![ChildSpec {
9474                    caixa: ok_name.into(),
9475                    versao: "^0.1".into(),
9476                    restart: RestartPolicy::Permanent,
9477                }],
9478                ..SupervisorSpec::default()
9479            };
9480            s.validate().unwrap_or_else(|e| {
9481                panic!(
9482                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
9483                     (upstream DNS-1123 gate accepts it): got {e:?}",
9484                );
9485            });
9486            let c = ChildSpec {
9487                caixa: ok_name.into(),
9488                versao: "^0.1".into(),
9489                restart: RestartPolicy::Permanent,
9490            };
9491            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
9492                .unwrap_or_else(|()| {
9493                    panic!(
9494                        "require_valid_dns_1123_label must accept the accessor-projected \
9495                     :children :caixa {ok_name:?}",
9496                    );
9497                });
9498        }
9499        // Reject-set sweep: five DNS-1123-label-violating shapes the
9500        // upstream gate refuses (empty / uppercase / underscore / dot /
9501        // leading-hyphen). Every rejection at the validator must
9502        // correspond to a rejection when the accessor's projected value
9503        // is fed back through the shared gate.
9504        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
9505            let s = SupervisorSpec {
9506                children: vec![ChildSpec {
9507                    caixa: bad_name.into(),
9508                    versao: "^0.1".into(),
9509                    restart: RestartPolicy::Permanent,
9510                }],
9511                ..SupervisorSpec::default()
9512            };
9513            let err = s.validate().unwrap_err();
9514            assert!(
9515                matches!(
9516                    err,
9517                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
9518                ),
9519                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
9520                 via the DNS-1123 gate: got {err:?}",
9521            );
9522            let c = ChildSpec {
9523                caixa: bad_name.into(),
9524                versao: "^0.1".into(),
9525                restart: RestartPolicy::Permanent,
9526            };
9527            assert!(
9528                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
9529                    .is_err(),
9530                "require_valid_dns_1123_label must reject the accessor-projected \
9531                 :children :caixa {bad_name:?}",
9532            );
9533        }
9534    }
9535
9536    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
9537    //
9538    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
9539    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
9540    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
9541    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
9542    // trio on the peer per-`:children` `String`-carry axis. The three pins
9543    // jointly brace the accessor against every future silent detour that
9544    // would desynchronize it from the raw `.versao` field access the
9545    // requirement gate + error carrier previously open-coded.
9546    //
9547    // Closes the last unlifted per-`:children` `String`-carry axis: the
9548    // pair (`nome`, `versao_requirement`) now jointly projects the
9549    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
9550    // consumer that fans on per-child identity + version pin reads,
9551    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
9552    // pair discipline verbatim.
9553    #[test]
9554    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
9555        // The canonical per-`:children` child-`:versao`-scalar pin:
9556        // [`ChildSpec::versao_requirement`] must return the `:children
9557        // :versao` field byte-for-byte across every Cargo-shaped semver
9558        // requirement value the upstream
9559        // [`crate::render::require_valid_versao_requirement`] gate admits.
9560        // Peer of the sibling
9561        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
9562        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
9563        // substrate-primitive accessor must byte-equal the raw field
9564        // access verbatim across every author-declared value" discipline
9565        // extended to the M2 supervisor-tree per-`:children` arm. Pins
9566        // against a future silent detour that re-canonicalized the
9567        // requirement (an accidental `.to_string()` via
9568        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
9569        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
9570        // silently drifted the error carrier's quoted requirement away
9571        // from the source `caixa.lisp`, an accidental whitespace trim on
9572        // `"^ 0.1"` that no consumer ever produced from the field-access
9573        // side, an accidental per-cluster lacre-projected concrete-version
9574        // rewrite that didn't land on the peer requirement-gate call).
9575        // Five values sweep the accept-set the shared
9576        // [`crate::render::require_valid_versao_requirement`] gate admits
9577        // (caret / tilde / exact / wildcard / bare-major).
9578        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
9579            let c = ChildSpec {
9580                caixa: "worker".into(),
9581                versao: req.into(),
9582                restart: RestartPolicy::Permanent,
9583            };
9584            assert_eq!(
9585                c.versao_requirement(),
9586                req,
9587                "ChildSpec::versao_requirement must return :children :versao \
9588                 verbatim (got {:?}, expected {req:?})",
9589                c.versao_requirement(),
9590            );
9591            assert_eq!(
9592                c.versao_requirement(),
9593                c.versao.as_str(),
9594                "ChildSpec::versao_requirement must byte-equal the .versao \
9595                 field access",
9596            );
9597        }
9598    }
9599
9600    #[test]
9601    fn child_spec_versao_requirement_borrows_from_versao_storage() {
9602        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
9603        // return a `&str` slice that borrows from the typed slot's own
9604        // [`String`] storage — same-address invariant with
9605        // `c.versao.as_str()`. Pins against a future silent detour that
9606        // allocated a fresh `String` (`self.versao.clone()` in the body
9607        // would type-check but silently drop the borrow, and every
9608        // downstream consumer that assumed the returned slice outlives
9609        // `&self` — the [`crate::render::require_valid_versao_requirement`]
9610        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
9611        // `.to_string()` carrier's byte-length assumption — would silently
9612        // misbehave if this accessor produced a detached copy). Peer of
9613        // the sibling `child_spec_nome_borrows_from_caixa_storage`
9614        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
9615        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
9616        // pin on the peer per-`:membros` `:versao` axis.
9617        let c = ChildSpec {
9618            caixa: "worker".into(),
9619            versao: "^0.1".into(),
9620            restart: RestartPolicy::Permanent,
9621        };
9622        let req = c.versao_requirement();
9623        let versao_slice = c.versao.as_str();
9624        assert_eq!(
9625            req.as_ptr(),
9626            versao_slice.as_ptr(),
9627            "ChildSpec::versao_requirement must borrow from the .versao \
9628             String's backing storage — a fresh allocation here means the \
9629             accessor no longer names the substrate-primitive typed \
9630             dispatch and every downstream consumer would silently carry \
9631             a detached copy",
9632        );
9633        assert_eq!(
9634            req.len(),
9635            versao_slice.len(),
9636            "ChildSpec::versao_requirement and .versao.as_str() must \
9637             byte-equal in length as well as in address",
9638        );
9639    }
9640
9641    #[test]
9642    fn validate_gates_child_versao_through_lifted_accessor() {
9643        // Bilateral coherence pin: every `:children :versao` that
9644        // [`SupervisorSpec::validate`] accepts is one
9645        // [`crate::render::require_valid_versao_requirement`] accepts on
9646        // the accessor-projected value, and vice versa on the reject side.
9647        // This closes the "the validator reads through the accessor"
9648        // contract structurally — a future silent detour that made the
9649        // accessor return a different byte-string than the validator gates
9650        // against would surface here as a coverage mismatch, not as a
9651        // resolver-time semver-parse rejection at lacre-closure time far
9652        // from the caixa.lisp source. Peer of the sibling
9653        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
9654        // the per-`:children :caixa` axis and the M2
9655        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
9656        // on the peer per-`:upgrade-from :from` axis.
9657        //
9658        // Accept-set sweep: five Cargo-shaped semver requirement values
9659        // the upstream gate admits (caret / tilde / exact / wildcard /
9660        // bare-major).
9661        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
9662            let s = SupervisorSpec {
9663                children: vec![ChildSpec {
9664                    caixa: "worker".into(),
9665                    versao: ok_req.into(),
9666                    restart: RestartPolicy::Permanent,
9667                }],
9668                ..SupervisorSpec::default()
9669            };
9670            s.validate().unwrap_or_else(|e| {
9671                panic!(
9672                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
9673                     (upstream versao-requirement gate accepts it): got {e:?}",
9674                );
9675            });
9676            let c = ChildSpec {
9677                caixa: "worker".into(),
9678                versao: ok_req.into(),
9679                restart: RestartPolicy::Permanent,
9680            };
9681            crate::render::require_valid_versao_requirement(
9682                c.versao_requirement(),
9683                || (),
9684                |_reason| (),
9685            )
9686            .unwrap_or_else(|()| {
9687                panic!(
9688                    "require_valid_versao_requirement must accept the accessor-projected \
9689                     :children :versao {ok_req:?}",
9690                );
9691            });
9692        }
9693        // Reject-set sweep: five requirement-violating shapes the upstream
9694        // gate refuses. The empty string closes the empty-first arm of the
9695        // shared [`crate::render::require_valid_versao_requirement`]
9696        // cascade; the four non-empty arms exercise distinct semver-parse
9697        // failure modes the M3 peer per-`:membros` reject-set already pins
9698        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
9699        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
9700        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
9701        // shared parser routing means the same reject-set must fail
9702        // identically at the M2 supervisor-tree per-`:children` accessor
9703        // arm here. Every rejection at the validator must correspond to a
9704        // rejection when the accessor's projected value is fed back
9705        // through the shared gate.
9706        //
9707        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
9708        // `"not-a-semver"` are intentionally *not* in the reject-set: the
9709        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
9710        // and the identifier-tail arm's grammar admits some non-canonical
9711        // shapes — matching what the M3 peer test suite already documents
9712        // as the shared parser's accept-set edges.)
9713        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
9714            let s = SupervisorSpec {
9715                children: vec![ChildSpec {
9716                    caixa: "worker".into(),
9717                    versao: bad_req.into(),
9718                    restart: RestartPolicy::Permanent,
9719                }],
9720                ..SupervisorSpec::default()
9721            };
9722            let err = s.validate().unwrap_err();
9723            assert!(
9724                matches!(
9725                    err,
9726                    SupervisorError::EmptyChildVersion { .. }
9727                        | SupervisorError::ChildVersaoInvalid { .. }
9728                ),
9729                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
9730                 via the versao-requirement gate: got {err:?}",
9731            );
9732            let c = ChildSpec {
9733                caixa: "worker".into(),
9734                versao: bad_req.into(),
9735                restart: RestartPolicy::Permanent,
9736            };
9737            assert!(
9738                crate::render::require_valid_versao_requirement(
9739                    c.versao_requirement(),
9740                    || (),
9741                    |_reason| (),
9742                )
9743                .is_err(),
9744                "require_valid_versao_requirement must reject the accessor-projected \
9745                 :children :versao {bad_req:?}",
9746            );
9747        }
9748    }
9749
9750    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
9751    //
9752    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
9753    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
9754    // already project the `String`-carry `(caixa, versao)` fields; the
9755    // `Copy`-composite-enum `restart` field is the third and final axis).
9756    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
9757    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
9758    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
9759    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
9760    // strategy scalar accessor — same "one typed dispatch on the substrate
9761    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
9762    // extended onto the M2 supervisor-slot per-`:children` restart-decision
9763    // axis. The pin below covers the accessor's byte-equal projection
9764    // against the raw field access across every variant in the closed
9765    // accept-set (`Permanent`, `Transient`, `Temporary`).
9766
9767    #[test]
9768    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
9769        // The canonical per-`:children` restart-decision-policy-scalar
9770        // pin: [`ChildSpec::restart`] must return the `:children :restart`
9771        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
9772        // typed slot's own [`RestartPolicy`] storage across every variant
9773        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
9774        // Pins against a future silent detour that re-derived the policy
9775        // from a peer axis (an accidental fallback to
9776        // `if is_supervisor_child { Permanent } else { Temporary }` that
9777        // collapsed the child's kind axis into the restart discriminator),
9778        // a variant remap the operator authors on one consumer without the
9779        // other, or a stale-derive detour that substituted
9780        // [`RestartPolicy::default`] when the field held any explicit
9781        // variant (which would silently collapse the distinction between
9782        // "author explicitly declared `:restart Permanent`" and "author
9783        // omitted the slot and inherited the default" the future
9784        // per-cluster restart-decision override slot depends on).
9785        //
9786        // Peer of the sibling per-`:supervisor`
9787        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
9788        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
9789        // axis and the M3
9790        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
9791        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
9792        // — same "the substrate-primitive accessor must byte-equal the raw
9793        // field access verbatim across every author-declared value"
9794        // discipline extended onto the M2 supervisor-slot per-`:children`
9795        // restart-decision-policy axis, closing the last unlifted axis on
9796        // the per-`:children` [`ChildSpec`] type.
9797        for restart in [
9798            RestartPolicy::Permanent,
9799            RestartPolicy::Transient,
9800            RestartPolicy::Temporary,
9801        ] {
9802            let c = ChildSpec {
9803                caixa: "worker".into(),
9804                versao: "^0.1".into(),
9805                restart,
9806            };
9807            assert_eq!(
9808                c.restart(),
9809                restart,
9810                "ChildSpec::restart must return :children :restart \
9811                 verbatim (got {:?}, expected {restart:?})",
9812                c.restart(),
9813            );
9814            assert_eq!(
9815                c.restart(),
9816                c.restart,
9817                "ChildSpec::restart accessor and .restart field access \
9818                 must byte-equal — the accessor is the substrate-primitive \
9819                 typed dispatch every downstream per-child restart-\
9820                 decision consumer must route through",
9821            );
9822        }
9823    }
9824
9825    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
9826    //
9827    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
9828    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
9829    // distribution-strategy accessor discipline onto the M2 supervisor-slot
9830    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
9831    // scalar axis. The two pins below cover (1) the accessor's byte-equal
9832    // projection against the raw field access across every variant in the
9833    // closed accept-set, and (2) the two-consumer coherence between the
9834    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
9835    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
9836    // carrier's `estrategia:` field — peer of the sibling M3
9837    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
9838    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
9839    // pair on the per-`:placement` distribution-strategy axis.
9840
9841    #[test]
9842    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
9843        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
9844        // pin: [`SupervisorSpec::estrategia`] must return the
9845        // `:supervisor :estrategia` field verbatim as a
9846        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
9847        // [`RestartStrategy`] storage across every variant in the closed
9848        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
9849        // `SimpleOneForOne`). Pins against a future silent detour that
9850        // re-derived the strategy from a peer axis (an accidental
9851        // fallback to `if children.is_empty() { SimpleOneForOne } else {
9852        // OneForOne }` collapse that read the children-count axis into
9853        // the strategy discriminator), a variant remap the operator
9854        // authors on one consumer without the other, or a stale-derive
9855        // detour that substituted [`RestartStrategy::default`] when the
9856        // field held any explicit variant (which would silently collapse
9857        // the distinction between "author explicitly declared
9858        // `:estrategia OneForOne`" and "author omitted the slot and
9859        // inherited the default" the future per-cluster strategy override
9860        // slot depends on). Peer of the sibling M3
9861        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
9862        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
9863        // axis — same "the substrate-primitive accessor must byte-equal
9864        // the raw field access verbatim across every author-declared
9865        // value" discipline extended onto the M2 supervisor-slot
9866        // per-`:supervisor` sibling-restart-strategy axis.
9867        for &estrategia in RestartStrategy::ALL {
9868            // `SimpleOneForOne` requires `children.is_empty()`; the peer
9869            // three strategies require a non-empty static children list.
9870            // Build each shape coherently so the pin's fixture would
9871            // itself pass [`SupervisorSpec::validate`] once fed through
9872            // the sibling coherence pin below — the byte-equal projection
9873            // asserted here is a strictly weaker property (a `Copy` field
9874            // read) that does not depend on `validate` running, but
9875            // keeping the fixture validate-clean means a future extension
9876            // of the pin to exercise `validate` end-to-end does not have
9877            // to re-author the children shape.
9878            //
9879            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
9880            // shape partition through the [`gen_platform::IsVariant`]
9881            // derive-generated
9882            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
9883            // than the raw `matches!(estrategia, RestartStrategy::
9884            // SimpleOneForOne)` open-coded pattern-match — same closed-
9885            // set-typed-enum arm-discriminator dispatch discipline the
9886            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
9887            // convergence (915a934) extended onto its two paired positive
9888            // / negated `matches!` sites and the peer
9889            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
9890            // predicate convergence (766ec63) extended onto the M3 mesh-
9891            // slot per-`:placement` distribution-strategy discriminator
9892            // axis. See the sibling `round_trip_all_strategies` and the
9893            // peer `manifest::tests::
9894            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
9895            // fixture for the two peer sites the same lift closes on.
9896            let children = if estrategia.is_simple_one_for_one() {
9897                Vec::new()
9898            } else {
9899                vec![ChildSpec {
9900                    caixa: "worker".into(),
9901                    versao: "^0.1".into(),
9902                    restart: RestartPolicy::Permanent,
9903                }]
9904            };
9905            let s = SupervisorSpec {
9906                estrategia,
9907                children,
9908                ..SupervisorSpec::default()
9909            };
9910            assert_eq!(
9911                s.estrategia(),
9912                estrategia,
9913                "SupervisorSpec::estrategia must return :supervisor :estrategia \
9914                 verbatim (got {:?}, expected {estrategia:?})",
9915                s.estrategia(),
9916            );
9917            assert_eq!(
9918                s.estrategia(),
9919                s.estrategia,
9920                "SupervisorSpec::estrategia accessor and .estrategia field \
9921                 access must byte-equal — the accessor is the substrate-\
9922                 primitive typed dispatch every downstream sibling-restart-\
9923                 strategy consumer must route through",
9924            );
9925        }
9926    }
9927
9928    #[test]
9929    fn validate_reads_through_lifted_estrategia_accessor() {
9930        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
9931        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
9932        // dispatch (which reads through [`SupervisorSpec::estrategia`]
9933        // to fan across the strategy-arm shape-gate cascades) and the
9934        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
9935        // error carrier's `estrategia:` field (which reads through
9936        // [`SupervisorSpec::estrategia`] to name the strategy the empty
9937        // `:children` list was declared against) must both key off the
9938        // lifted accessor, so any future rebrand on the typed slot's
9939        // reader shape lands at exactly one place. Pins the two-site
9940        // coherence by exercising the `NoChildren` error surface end-to-
9941        // end across every non-`SimpleOneForOne` variant and asserting
9942        // the surfaced `estrategia:` field byte-equals the accessor's
9943        // return. Peer of the sibling M3
9944        // `validate_placement_reads_through_lifted_estrategia_accessor`
9945        // (921fe1b) three-consumer coherence pin on the per-`:placement`
9946        // distribution-strategy axis.
9947        for estrategia in [
9948            RestartStrategy::OneForOne,
9949            RestartStrategy::OneForAll,
9950            RestartStrategy::RestForOne,
9951        ] {
9952            let s = SupervisorSpec {
9953                estrategia,
9954                children: Vec::new(),
9955                ..SupervisorSpec::default()
9956            };
9957            let err = s.validate().unwrap_err();
9958            match err {
9959                SupervisorError::NoChildren { estrategia: e } => {
9960                    assert_eq!(
9961                        e,
9962                        s.estrategia(),
9963                        "NoChildren.estrategia must byte-equal \
9964                         SupervisorSpec::estrategia() — the empty-`:children` \
9965                         refusal reads through the lifted accessor",
9966                    );
9967                    assert_eq!(
9968                        e, estrategia,
9969                        "NoChildren.estrategia must carry the author-declared \
9970                         :supervisor :estrategia variant verbatim (got {e:?}, \
9971                         expected {estrategia:?})",
9972                    );
9973                }
9974                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
9975            }
9976        }
9977    }
9978
9979    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
9980    //
9981    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
9982    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
9983    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
9984    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
9985    // The two pins below cover (1) the accessor's byte-equal projection
9986    // against the raw field access across every representative value in
9987    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
9988    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
9989    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
9990    // zero-floor / cap composition — the validate gate and the accessor
9991    // must route through the same substrate-primitive typed dispatch, so
9992    // any future silent detour that had the accessor perform a
9993    // bounds-collapsing clamp would fail here at caixa-core build time.
9994    // Peer of the sibling M3
9995    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
9996    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
9997
9998    #[test]
9999    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
10000        // The canonical per-`:supervisor` restart-budget-count scalar pin:
10001        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
10002        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
10003        // typed slot's own `u32` storage, byte-equal to the raw field
10004        // access across every representative value in the accept-set —
10005        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
10006        // accept-set the surrounding [`SupervisorSpec::validate`] gate
10007        // carves out on the sibling `ZeroMaxRestarts` refusal),
10008        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
10009        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
10010        // (a past-the-guard sentinel that pins the accessor doesn't
10011        // perform a silent bounds-collapse into `1` on the zero arm —
10012        // validate rejects zero but the accessor must ship the raw slot
10013        // verbatim so a validate-time gate regression surfaces at the
10014        // emit boundary rather than being silently absorbed), `u32::MAX`
10015        // (a past-the-guard sentinel that pins the accessor doesn't
10016        // perform a silent bounds-collapse through
10017        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
10018        //
10019        // Peer of the sibling M3
10020        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
10021        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
10022        // required-scalar axis — same "the substrate-primitive accessor
10023        // must byte-equal the raw field access verbatim across every
10024        // value in the `u32` accept-set" discipline extended onto the M2
10025        // supervisor-slot per-`:supervisor` restart-budget-count axis.
10026        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
10027            let s = SupervisorSpec {
10028                max_restarts,
10029                ..SupervisorSpec::default()
10030            };
10031            assert_eq!(
10032                s.max_restarts(),
10033                max_restarts,
10034                "SupervisorSpec::max_restarts must return :supervisor \
10035                 :max-restarts verbatim (got {}, expected {max_restarts})",
10036                s.max_restarts(),
10037            );
10038            assert_eq!(
10039                s.max_restarts(),
10040                s.max_restarts,
10041                "SupervisorSpec::max_restarts accessor and .max_restarts \
10042                 field access must byte-equal — the accessor is the \
10043                 substrate-primitive typed dispatch every downstream \
10044                 restart-budget-count consumer must route through",
10045            );
10046        }
10047    }
10048
10049    #[test]
10050    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
10051        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
10052        // zero-floor + upper-cap bracket must key off
10053        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
10054        // field access. Structurally: a `SupervisorSpec { max_restarts:
10055        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
10056        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
10057        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
10058        // (with the offending count carried verbatim from the accessor
10059        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
10060        // lower boundary of the accept-set) plus a `SupervisorSpec {
10061        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
10062        // boundary) must pass validate. The four together jointly pin the
10063        // accessor + validate-gate composition: any future silent detour
10064        // that had the accessor return a fresh `1` on the zero arm (a
10065        // `.max_restarts().max(1)` collapse) would silently absorb the
10066        // `ZeroMaxRestarts` refusal at the accessor boundary and the
10067        // validate gate would accept a struct-literal `SupervisorSpec {
10068        // max_restarts: 0, .. }` — the composition pin catches that at
10069        // caixa-core build time.
10070        //
10071        // Peer of the sibling M3
10072        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
10073        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
10074        // composition axis — same "the validate / shape-gate predicate
10075        // must route through the substrate-primitive typed dispatch"
10076        // discipline extended onto the peer M2 supervisor-slot
10077        // required-`u32` composition axis.
10078        let child = ChildSpec {
10079            caixa: "worker".into(),
10080            versao: "^0.1".into(),
10081            restart: RestartPolicy::Permanent,
10082        };
10083        // Zero-floor arm.
10084        let s = SupervisorSpec {
10085            max_restarts: 0,
10086            children: vec![child.clone()],
10087            ..SupervisorSpec::default()
10088        };
10089        assert_eq!(
10090            s.validate().unwrap_err(),
10091            SupervisorError::ZeroMaxRestarts,
10092            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
10093             — the accessor and the validate gate must route through the \
10094             same substrate-primitive typed dispatch on the zero-floor arm",
10095        );
10096        // Cap arm — the surfaced `max_restarts:` field must byte-equal
10097        // the accessor's return so a future rebrand on the accessor
10098        // lands in the diagnostic without a coordinated rewrite.
10099        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
10100        let s = SupervisorSpec {
10101            max_restarts: over_cap,
10102            children: vec![child.clone()],
10103            ..SupervisorSpec::default()
10104        };
10105        match s.validate().unwrap_err() {
10106            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
10107                assert_eq!(
10108                    max_restarts,
10109                    s.max_restarts(),
10110                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
10111                     SupervisorSpec::max_restarts() — the cap-arm refusal \
10112                     reads through the lifted accessor",
10113                );
10114                assert_eq!(
10115                    max_restarts, over_cap,
10116                    "MaxRestartsExceedsCap.max_restarts must carry the \
10117                     author-declared :supervisor :max-restarts value \
10118                     verbatim (got {max_restarts}, expected {over_cap})",
10119                );
10120            }
10121            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
10122        }
10123        // Lower + upper accept-set boundaries.
10124        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
10125            let s = SupervisorSpec {
10126                max_restarts,
10127                children: vec![child.clone()],
10128                ..SupervisorSpec::default()
10129            };
10130            assert!(
10131                s.validate().is_ok(),
10132                "validate must accept max_restarts == {max_restarts} \
10133                 (an accept-set boundary of \
10134                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
10135            );
10136        }
10137    }
10138
10139    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
10140    //
10141    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
10142    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
10143    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
10144    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
10145    // supervisor-slot per-`:supervisor` restart-intensity-denominator
10146    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
10147    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
10148    // per-`:supervisor` scalar-value axis. The three pins below cover
10149    // (1) the accessor's byte-equal projection against the raw field
10150    // access across every representative value in the `Option<Duration>`
10151    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
10152    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
10153    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
10154    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
10155    // `if let Some(w) = self.restart_window() { … }` bracket-arm
10156    // composition — the validate gate and the accessor must route through
10157    // the same substrate-primitive typed dispatch, so any future silent
10158    // detour that had the accessor perform a bounds-collapsing clamp
10159    // would fail here at caixa-core build time, and (3) the accessor's
10160    // by-copy idempotence pin — the returned `Option<Duration>` must
10161    // outlive `&self` and two successive calls must return byte-equal
10162    // values. Peer of the sibling M2
10163    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
10164    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
10165    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
10166    // (7073d0f) pin on the per-`:politicas :timeout` axis.
10167
10168    #[test]
10169    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
10170        // The canonical per-`:supervisor` restart-intensity-denominator
10171        // scalar pin: [`SupervisorSpec::restart_window`] must return the
10172        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
10173        // `Option<Duration>`, `Copy`-projected from the typed slot's own
10174        // `Option<Duration>` storage, byte-equal to the raw field access
10175        // across every representative value in the accept-set — `None`
10176        // (the "never reset — every restart across the supervisor's
10177        // lifetime counts against the sibling `:max-restarts` budget"
10178        // sentinel the field's own docstring names and the peer
10179        // `validate_accepts_none_restart_window` pin locks in on the
10180        // [`SupervisorSpec::validate`] entry-side),
10181        // `Some(Duration::from_millis(1))` (the structural minimum a
10182        // validated `:restart-window` may carry, the integer-millisecond
10183        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
10184        // everything sub-ms; `Duration::ZERO` is separately rejected by
10185        // [`SupervisorError::RestartWindowZero`]),
10186        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
10187        // surrounding [`SupervisorSpec::validate`] gate carves out on the
10188        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
10189        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
10190        // accessor doesn't perform a silent bounds-collapse into `None` on
10191        // the zero-Duration arm — validate rejects zero but the accessor
10192        // must ship the raw slot verbatim so a validate-time gate
10193        // regression surfaces at the emit boundary rather than being
10194        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
10195        // sentinel that pins the accessor doesn't perform a silent
10196        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
10197        // return path).
10198        //
10199        // Peer of the sibling M2
10200        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
10201        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
10202        // sibling M3
10203        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
10204        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
10205        // substrate-primitive accessor must byte-equal the raw field
10206        // access verbatim across every value in the `Option<Duration>`
10207        // accept-set" discipline extended onto the M2 supervisor-slot
10208        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
10209        // silent detour that re-derived the restart-window from a peer
10210        // axis (an accidental `.max_restarts.into()` collapse that read
10211        // the restart-budget-count as a duration — the two axes serve
10212        // different halves of the `MaxIntensity / Period` restart-
10213        // intensity ratio, and confusing them silently inverts the
10214        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
10215        // "zero means never reset" collapse (the canonical
10216        // `Option<Duration>` → `Duration` collapse footgun the
10217        // [`SupervisorError::RestartWindowZero`] validate arm guards on
10218        // the peer zero-floor axis; a zero period either trips on the
10219        // first failure or never trips depending on operator
10220        // interpretation, neither of which is the author's "never reset"
10221        // intent that `None` expresses structurally), or a per-arm
10222        // variant swap that landed on one consumer without the other.
10223        for restart_window in [
10224            None,
10225            Some(Duration::from_millis(1)),
10226            Some(SUPERVISOR_RESTART_WINDOW_MAX),
10227            Some(Duration::ZERO),
10228            Some(Duration::MAX),
10229        ] {
10230            let s = SupervisorSpec {
10231                restart_window,
10232                ..SupervisorSpec::default()
10233            };
10234            assert_eq!(
10235                s.restart_window(),
10236                restart_window,
10237                "SupervisorSpec::restart_window must return :supervisor \
10238                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
10239                s.restart_window(),
10240            );
10241            assert_eq!(
10242                s.restart_window(),
10243                s.restart_window,
10244                "SupervisorSpec::restart_window accessor and \
10245                 .restart_window field access must byte-equal — the \
10246                 accessor is the substrate-primitive typed dispatch every \
10247                 downstream restart-intensity-denominator consumer must \
10248                 route through",
10249            );
10250        }
10251    }
10252
10253    #[test]
10254    fn validate_restart_window_bracket_arm_routes_through_accessor() {
10255        // Composition pin: [`SupervisorSpec::validate`]'s
10256        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
10257        // zero-floor + integer-millisecond canonical-form + upper-cap
10258        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
10259        // the raw `.restart_window` field access. Structurally: a
10260        // `SupervisorSpec { restart_window: None, .. }` must pass the
10261        // arm gate structurally (the `if let Some(_)` shape returns
10262        // early on the `None` arm — the accessor and the validate gate
10263        // must agree on `None → skip the bracket cascade` so an authored
10264        // `:restart-window ()` structurally routes through the "never
10265        // reset" sentinel path), a `SupervisorSpec { restart_window:
10266        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
10267        // refusal exactly, a `SupervisorSpec { restart_window:
10268        // Some(Duration::from_micros(1500)), .. }` must surface the
10269        // `RestartWindowNotCanonical` refusal exactly (with the offending
10270        // duration carried verbatim from the accessor return), a
10271        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
10272        // + Duration::from_millis(1)), .. }` must surface the
10273        // `RestartWindowExceedsCap` refusal exactly (with the offending
10274        // duration carried verbatim from the accessor return), and a
10275        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
10276        // .. }` (the lower boundary of the accept-set) plus a
10277        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
10278        // .. }` (the upper boundary) must pass validate. The six together
10279        // jointly pin the accessor + validate-gate composition: any future
10280        // silent detour that had the accessor return a fresh `None` on any
10281        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
10282        // collapse) would silently absorb the `RestartWindowZero` refusal
10283        // at the accessor boundary and the validate gate would accept a
10284        // struct-literal `SupervisorSpec { restart_window:
10285        // Some(Duration::ZERO), .. }` — the composition pin catches that
10286        // at caixa-core build time.
10287        //
10288        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
10289        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
10290        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
10291        // accessor-composition pin on the per-`:politicas :timeout` axis —
10292        // same "the validate / shape-gate predicate must route through
10293        // the substrate-primitive typed dispatch" discipline extended
10294        // onto the peer M2 supervisor-slot optional-`Duration` axis.
10295        let child = ChildSpec {
10296            caixa: "worker".into(),
10297            versao: "^0.1".into(),
10298            restart: RestartPolicy::Permanent,
10299        };
10300        // None arm — must not surface any :restart-window-shaped refusal;
10301        // the `if let Some(_)` bracket returns early on `None` structurally.
10302        let s = SupervisorSpec {
10303            restart_window: None,
10304            children: vec![child.clone()],
10305            ..SupervisorSpec::default()
10306        };
10307        assert!(
10308            s.validate().is_ok(),
10309            "validate must accept restart_window: None (the never-reset \
10310             sentinel) — the `if let Some(_)` bracket returns early on \
10311             the None arm and the accessor must agree",
10312        );
10313        // Zero-floor arm.
10314        let s = SupervisorSpec {
10315            restart_window: Some(Duration::ZERO),
10316            children: vec![child.clone()],
10317            ..SupervisorSpec::default()
10318        };
10319        assert_eq!(
10320            s.validate().unwrap_err(),
10321            SupervisorError::RestartWindowZero,
10322            "validate must reject restart_window == Some(Duration::ZERO) \
10323             with RestartWindowZero — the accessor and the validate gate \
10324             must route through the same substrate-primitive typed \
10325             dispatch on the zero-floor arm",
10326        );
10327        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
10328        // byte-equal the accessor's return so a future rebrand on the
10329        // accessor lands in the diagnostic without a coordinated rewrite.
10330        let sub_ms = Duration::from_micros(1500);
10331        let s = SupervisorSpec {
10332            restart_window: Some(sub_ms),
10333            children: vec![child.clone()],
10334            ..SupervisorSpec::default()
10335        };
10336        match s.validate().unwrap_err() {
10337            SupervisorError::RestartWindowNotCanonical { window } => {
10338                assert_eq!(
10339                    Some(window),
10340                    s.restart_window(),
10341                    "RestartWindowNotCanonical.window must byte-equal \
10342                     SupervisorSpec::restart_window().unwrap() — the \
10343                     non-canonical-arm refusal reads through the lifted \
10344                     accessor",
10345                );
10346                assert_eq!(
10347                    window, sub_ms,
10348                    "RestartWindowNotCanonical.window must carry the \
10349                     author-declared :supervisor :restart-window value \
10350                     verbatim (got {window:?}, expected {sub_ms:?})",
10351                );
10352            }
10353            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
10354        }
10355        // Cap arm — the surfaced `window:` field must byte-equal the
10356        // accessor's return.
10357        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
10358        let s = SupervisorSpec {
10359            restart_window: Some(over_cap),
10360            children: vec![child.clone()],
10361            ..SupervisorSpec::default()
10362        };
10363        match s.validate().unwrap_err() {
10364            SupervisorError::RestartWindowExceedsCap { window } => {
10365                assert_eq!(
10366                    Some(window),
10367                    s.restart_window(),
10368                    "RestartWindowExceedsCap.window must byte-equal \
10369                     SupervisorSpec::restart_window().unwrap() — the \
10370                     cap-arm refusal reads through the lifted accessor",
10371                );
10372                assert_eq!(
10373                    window, over_cap,
10374                    "RestartWindowExceedsCap.window must carry the \
10375                     author-declared :supervisor :restart-window value \
10376                     verbatim (got {window:?}, expected {over_cap:?})",
10377                );
10378            }
10379            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
10380        }
10381        // Lower + upper accept-set boundaries.
10382        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
10383            let s = SupervisorSpec {
10384                restart_window: Some(restart_window),
10385                children: vec![child.clone()],
10386                ..SupervisorSpec::default()
10387            };
10388            assert!(
10389                s.validate().is_ok(),
10390                "validate must accept restart_window == Some({restart_window:?}) \
10391                 (an accept-set boundary of \
10392                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
10393            );
10394        }
10395    }
10396
10397    #[test]
10398    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
10399        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
10400        // `Option<Duration>` by copy — `Duration` is `Copy` (so
10401        // `Option<Duration>` is `Copy`) and the accessor must return by
10402        // value, not by reference. Peer of the sibling M2
10403        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
10404        // per-`:limits :wall-clock` axis and the sibling M3
10405        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
10406        // per-`:politicas :timeout` axis, extended onto the peer M2
10407        // supervisor-slot `Option<Duration>` copy-invariant shape — the
10408        // accessor's returned `Option<Duration>` must outlive `&self`
10409        // (multiple calls must return equal values from a dropped-`&self`
10410        // copy, since the returned Option carries no borrow), and calling
10411        // the accessor twice on the same SupervisorSpec must yield the
10412        // same `Option<Duration>` verbatim (idempotent, no side effects
10413        // on `&self`).
10414        //
10415        // Pins against a future silent detour that returned
10416        // `Option<&Duration>` (which would type-check but silently break
10417        // every downstream caller — the future wasm-operator's
10418        // per-supervisor restart-intensity counter consumes `Duration` by
10419        // value and `&Duration` would fold to a detached copy at the call
10420        // site), an accidental `Option::as_ref()` projection
10421        // (`self.restart_window.as_ref()` would also type-check but
10422        // return `Option<&Duration>`), or a one-arm-only accessor that
10423        // reads `Some(*w)` in the Some arm but reads a fresh
10424        // `Default::default()` (which would collapse to `Duration::ZERO`,
10425        // not `None`) in the None arm — a footgun the
10426        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
10427        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
10428        // requires `Period > 0` and `None` structurally expresses "never
10429        // reset" instead.
10430        for restart_window in [
10431            None,
10432            Some(Duration::from_millis(1)),
10433            Some(Duration::from_secs(60)),
10434            Some(SUPERVISOR_RESTART_WINDOW_MAX),
10435        ] {
10436            let s = SupervisorSpec {
10437                restart_window,
10438                ..SupervisorSpec::default()
10439            };
10440            let first = s.restart_window();
10441            let second = s.restart_window();
10442            assert_eq!(
10443                first, second,
10444                "SupervisorSpec::restart_window must be idempotent — two \
10445                 successive calls on the same &self must return the \
10446                 same Option<Duration>",
10447            );
10448            assert_eq!(
10449                first, restart_window,
10450                "SupervisorSpec::restart_window must return :supervisor \
10451                 :restart-window verbatim by copy — got {first:?}, \
10452                 expected {restart_window:?}",
10453            );
10454        }
10455    }
10456
10457    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
10458    //
10459    // The [`SupervisorSpec::children`] accessor lift is the seed of the
10460    // slice-return (`&[T]`) accessor discipline on the substrate — the four
10461    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
10462    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
10463    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
10464    // access at the time of this seed, and inherit this pin family's
10465    // discipline as future compounding runs migrate their consumers. The
10466    // three pins below cover (1) the accessor's byte-equal projection
10467    // against the raw field access across the empty / singleton / cohort
10468    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
10469    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
10470    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
10471    // consumer routing through the accessor on both arms, and (3) the
10472    // per-child validate loop's traversal reading the same slice-view the
10473    // accessor projects. Peer of the sibling M2
10474    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
10475    // two-consumer coherence pin on the per-`:supervisor`
10476    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
10477    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
10478
10479    #[test]
10480    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
10481        // The canonical per-`:supervisor` static-child-list scalar-shape
10482        // pin: [`SupervisorSpec::children`] must return the `:supervisor
10483        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
10484        // slice-view over the same backing buffer the raw
10485        // `self.children.as_slice()` field access borrows from, byte-
10486        // equal across every representative fixture in the accept-set —
10487        // the empty slice (the `SimpleOneForOne`-arm sentinel),
10488        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
10489        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
10490        // with the peer three restart-policy variants in play).
10491        //
10492        // Pins against a future silent detour that returned
10493        // `&Vec<ChildSpec>` (which would type-check but leak the
10494        // storage-side `Vec`'s grow/push/reserve surface no consumer of
10495        // the typed view reaches for), a fresh-allocated
10496        // `Vec<ChildSpec>` copy (which would type-check via a coercion
10497        // but silently break every downstream caller that relied on the
10498        // slice sharing the backing buffer's identity), or an
10499        // out-of-order or length-drifted projection (which would silently
10500        // split the per-child validate loop's traversal input from the
10501        // paired partition-dispatch `.is_empty()` probe's input).
10502        //
10503        // Peer of the sibling
10504        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
10505        // (eafb619) `Copy`-composite-enum byte-equal pin on the
10506        // per-`:supervisor` sibling-restart-strategy axis, extended onto
10507        // the per-`:supervisor` static-child-list `Vec`-carry axis.
10508        let fixtures: Vec<Vec<ChildSpec>> = vec![
10509            Vec::new(),
10510            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
10511            vec![
10512                child("worker", "^0.1", RestartPolicy::Permanent),
10513                child("cache-server", "^0.1", RestartPolicy::Transient),
10514            ],
10515            vec![
10516                child("worker", "^0.1", RestartPolicy::Permanent),
10517                child("cache-server", "^0.1", RestartPolicy::Transient),
10518                child("scratch-job", "^0.1", RestartPolicy::Temporary),
10519            ],
10520        ];
10521        for children in fixtures {
10522            let s = SupervisorSpec {
10523                children: children.clone(),
10524                ..SupervisorSpec::default()
10525            };
10526            assert_eq!(
10527                s.children(),
10528                children.as_slice(),
10529                "SupervisorSpec::children must return :supervisor \
10530                 :children verbatim (got {:?}, expected {:?})",
10531                s.children(),
10532                children.as_slice(),
10533            );
10534            assert_eq!(
10535                s.children(),
10536                s.children.as_slice(),
10537                "SupervisorSpec::children accessor and \
10538                 .children.as_slice() field access must byte-equal — \
10539                 the accessor is the substrate-primitive typed \
10540                 dispatch every downstream static-child-list consumer \
10541                 must route through",
10542            );
10543            assert_eq!(
10544                s.children().len(),
10545                s.children.len(),
10546                "SupervisorSpec::children().len() must byte-equal \
10547                 self.children.len() — a length-drift would silently \
10548                 split the paired partition-dispatch `.is_empty()` \
10549                 probe input from the per-child validate loop's \
10550                 traversal input",
10551            );
10552        }
10553    }
10554
10555    #[test]
10556    fn validate_reads_through_lifted_children_accessor() {
10557        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
10558        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
10559        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
10560        // when the accessor projects a non-empty slice under a
10561        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
10562        // `self.children().is_empty()` refusal probe (which must trip
10563        // [`SupervisorError::NoChildren`] when the accessor projects the
10564        // empty slice under any peer estrategia), and the per-child
10565        // validate loop's `for child in self.children()` traversal
10566        // (which must reach every entry in the same order the accessor
10567        // projects) must all key off the lifted accessor, so any future
10568        // rebrand on the typed slot's reader shape lands at exactly one
10569        // place. Pins the three-site coherence by exercising each
10570        // production consumer end-to-end: (1) the
10571        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
10572        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
10573        // refusal under the empty slice + non-`SimpleOneForOne`
10574        // estrategia across every peer variant, and (3) the per-child
10575        // duplicate-detection surface fires on the second entry of a
10576        // two-child cohort that shares a `:caixa` name (which requires
10577        // the loop to reach both entries — a first-entry-only projection
10578        // would silently pass since the dedup HashSet has room for the
10579        // first insert).
10580        //
10581        // Peer of the sibling M2
10582        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
10583        // two-consumer coherence pin on the per-`:supervisor`
10584        // sibling-restart-strategy axis, extended onto the
10585        // per-`:supervisor` static-child-list `Vec`-carry axis.
10586
10587        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
10588        // `SimpleOneForOne` estrategia must trip
10589        // `SimpleOneForOneWithStaticChildren`.
10590        let s = SupervisorSpec {
10591            estrategia: RestartStrategy::SimpleOneForOne,
10592            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
10593            ..SupervisorSpec::default()
10594        };
10595        assert_eq!(
10596            s.validate().unwrap_err(),
10597            SupervisorError::SimpleOneForOneWithStaticChildren,
10598            "SimpleOneForOne + non-empty children must trip \
10599             SimpleOneForOneWithStaticChildren — the accessor projects \
10600             a non-empty slice, and the SimpleOneForOne-arm refusal \
10601             probe reads through the lifted accessor",
10602        );
10603        assert!(
10604            !s.children().is_empty(),
10605            "the SimpleOneForOne-arm refusal input must be a non-empty \
10606             slice per the accessor's projection",
10607        );
10608
10609        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
10610        // under any peer estrategia must trip `NoChildren`.
10611        for estrategia in [
10612            RestartStrategy::OneForOne,
10613            RestartStrategy::OneForAll,
10614            RestartStrategy::RestForOne,
10615        ] {
10616            let s = SupervisorSpec {
10617                estrategia,
10618                children: Vec::new(),
10619                ..SupervisorSpec::default()
10620            };
10621            match s.validate().unwrap_err() {
10622                SupervisorError::NoChildren { estrategia: e } => {
10623                    assert_eq!(
10624                        e, estrategia,
10625                        "NoChildren.estrategia must carry the author-\
10626                         declared :supervisor :estrategia variant \
10627                         verbatim (got {e:?}, expected {estrategia:?})",
10628                    );
10629                }
10630                other => panic!(
10631                    "expected NoChildren, got {other:?} for \
10632                     estrategia={estrategia:?}"
10633                ),
10634            }
10635            assert!(
10636                s.children().is_empty(),
10637                "the non-SimpleOneForOne-arm refusal input must be the \
10638                 empty slice per the accessor's projection",
10639            );
10640        }
10641
10642        // (3) Per-child validate loop: a two-child cohort that shares a
10643        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
10644        // reach both entries through the accessor.
10645        let s = SupervisorSpec {
10646            estrategia: RestartStrategy::OneForOne,
10647            children: vec![
10648                child("worker", "^0.1", RestartPolicy::Permanent),
10649                child("worker", "^0.2", RestartPolicy::Transient),
10650            ],
10651            ..SupervisorSpec::default()
10652        };
10653        match s.validate().unwrap_err() {
10654            SupervisorError::DuplicateChildCaixa { caixa } => {
10655                assert_eq!(
10656                    caixa, "worker",
10657                    "DuplicateChildCaixa.caixa must carry the shared \
10658                     child `:caixa` name verbatim",
10659                );
10660            }
10661            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
10662        }
10663        assert_eq!(
10664            s.children().len(),
10665            2,
10666            "the per-child validate loop's traversal input must be a \
10667             two-element slice per the accessor's projection",
10668        );
10669    }
10670
10671    // Shared helper for the M2 per-`:children` per-slot-gate ≡
10672    // `validate` equivalence pins: builds an `OneForOne`-estrategia
10673    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
10674    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
10675    // bracket all pass cleanly so the sole failing surface is the
10676    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
10677    // pins the two-altitude equivalence on the paired probe.
10678    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
10679        let s = SupervisorSpec {
10680            estrategia: RestartStrategy::OneForOne,
10681            children,
10682            ..SupervisorSpec::default()
10683        };
10684        let via_gate = s.validate_children().unwrap_err();
10685        let via_validate = s.validate().unwrap_err();
10686        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
10687        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
10688        assert_eq!(
10689            via_gate, via_validate,
10690            "per-slot gate ≡ validate() must discriminate the same \
10691             refusal shape",
10692        );
10693    }
10694
10695    #[test]
10696    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
10697        // Fail-before-pass-after equivalence pin on the M2
10698        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
10699        // convergence — sibling of the M3 mesh-slot
10700        // `validate_membros_*` / `validate_contratos_*` /
10701        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
10702        // peer per-entry axes. Sweeps four of the five refusal shapes
10703        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
10704        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
10705        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
10706        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
10707        // duplicate-`:caixa` fan-out. Companion pin
10708        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
10709        // covers `ChildVersaoInvalid` (whose parser-owned reason string
10710        // needs pattern-matching, not equality) and the clean-pass
10711        // canonical fixture; together the two pins guarantee the
10712        // per-slot gate and `validate` discriminate the same set on
10713        // every per-child-covered input.
10714        assert_validate_children_matches_gate(
10715            vec![child("", "^0.1", RestartPolicy::Permanent)],
10716            &SupervisorError::EmptyChildName,
10717        );
10718        assert_validate_children_matches_gate(
10719            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
10720            &SupervisorError::ChildCaixaInvalid {
10721                caixa: "Worker".into(),
10722                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
10723            },
10724        );
10725        assert_validate_children_matches_gate(
10726            vec![child("worker", "", RestartPolicy::Permanent)],
10727            &SupervisorError::EmptyChildVersion {
10728                caixa: "worker".into(),
10729            },
10730        );
10731        assert_validate_children_matches_gate(
10732            vec![
10733                child("worker", "^0.1", RestartPolicy::Permanent),
10734                child("worker", "^0.2", RestartPolicy::Transient),
10735            ],
10736            &SupervisorError::DuplicateChildCaixa {
10737                caixa: "worker".into(),
10738            },
10739        );
10740    }
10741
10742    #[test]
10743    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
10744        // Second half of the two-altitude equivalence pin — covers the
10745        // one refusal shape whose reason string is parser-owned
10746        // (`ChildVersaoInvalid`, whose reason comes from the shared
10747        // [`crate::version::parse_requirement`] impl and may drift) and
10748        // the clean-pass canonical fixture. Sibling pin
10749        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
10750        // covers the four equality-comparable refusal shapes.
10751        let s_bad_versao = SupervisorSpec {
10752            estrategia: RestartStrategy::OneForOne,
10753            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
10754            ..SupervisorSpec::default()
10755        };
10756        let via_gate = s_bad_versao.validate_children().unwrap_err();
10757        let via_validate = s_bad_versao.validate().unwrap_err();
10758        match (&via_gate, &via_validate) {
10759            (
10760                SupervisorError::ChildVersaoInvalid {
10761                    caixa: cg,
10762                    versao: vg,
10763                    ..
10764                },
10765                SupervisorError::ChildVersaoInvalid {
10766                    caixa: cv,
10767                    versao: vv,
10768                    ..
10769                },
10770            ) => {
10771                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
10772                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
10773                assert_eq!(cv, "worker", "validate() :caixa carrier");
10774                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
10775            }
10776            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
10777        }
10778        assert_eq!(
10779            via_gate, via_validate,
10780            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
10781        );
10782
10783        let s_ok = SupervisorSpec {
10784            estrategia: RestartStrategy::OneForOne,
10785            children: vec![
10786                child("worker-a", "^0.1", RestartPolicy::Permanent),
10787                child("worker-b", "~0.2.3", RestartPolicy::Transient),
10788                child("collector", "*", RestartPolicy::Temporary),
10789            ],
10790            ..SupervisorSpec::default()
10791        };
10792        s_ok.validate_children()
10793            .expect("per-slot gate must accept the clean-pass fixture");
10794        s_ok.validate()
10795            .expect("validate() must accept the clean-pass fixture");
10796    }
10797
10798    #[test]
10799    fn validate_children_is_self_contained_on_children_slot() {
10800        // Self-containment pin: [`SupervisorSpec::validate_children`]
10801        // resolves the per-child cascade against `&self` alone, without
10802        // depending on the peer `:estrategia`/`:max-restarts`/
10803        // `:restart-window` gates having run first — same posture the M3
10804        // peer per-slot gates carry (`validate_membros`,
10805        // `validate_contratos`, `validate_entrada`, `validate_placement`,
10806        // routing through their own oracles rather than borrowing state
10807        // threaded down from `validate`). A future consumer that reaches
10808        // the per-slot gate directly on a spec whose peer slots would
10809        // fail `validate` still surfaces the per-child refusal, not the
10810        // peer refusal.
10811        //
10812        // Construct a spec whose `:max-restarts` is `0` (which would
10813        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
10814        // the partition-dispatch) and whose `:children` carries a
10815        // `DuplicateChildCaixa` shape: the per-slot gate called directly
10816        // must surface `DuplicateChildCaixa`, proving it does not depend
10817        // on the peer `:max-restarts` gate running first.
10818        let s = SupervisorSpec {
10819            estrategia: RestartStrategy::OneForOne,
10820            max_restarts: 0,
10821            restart_window: Some(Duration::from_secs(60)),
10822            children: vec![
10823                child("worker", "^0.1", RestartPolicy::Permanent),
10824                child("worker", "^0.2", RestartPolicy::Transient),
10825            ],
10826        };
10827        assert_eq!(
10828            s.validate_children().unwrap_err(),
10829            SupervisorError::DuplicateChildCaixa {
10830                caixa: "worker".into(),
10831            },
10832            "per-slot gate must resolve per-child refusal directly against \
10833             `&self` — a dependency on the peer `:max-restarts` gate \
10834             running first would surface ZeroMaxRestarts here instead",
10835        );
10836        // The peer gate is still the surface `validate` reaches — pin
10837        // the ordering to establish that `validate_children` truly runs
10838        // last in `validate`'s dispatch, so a direct call bypasses the
10839        // peer gates on any spec whose per-child cascade would fail.
10840        assert_eq!(
10841            s.validate().unwrap_err(),
10842            SupervisorError::ZeroMaxRestarts,
10843            "validate() must surface the peer `:max-restarts` gate before \
10844             reaching the per-child cascade — this pins the dispatch \
10845             ordering the per-slot gate's self-containment complements",
10846        );
10847    }
10848
10849    #[test]
10850    fn child_spec_restart_accessor_is_const_fn() {
10851        // The [`ChildSpec::restart`] per-`:children` restart-decision-
10852        // policy `Copy`-return scalar accessor is declared
10853        // `#[must_use] pub const fn` — matching the sibling M2
10854        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
10855        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
10856        // both converted in this commit), the sibling M2
10857        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
10858        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
10859        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
10860        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
10861        // `Copy`-return `pub const fn` scalar accessors on the sibling
10862        // M3 surface. Pin the `const`-eval posture here so a future
10863        // accidental downgrade to non-`const` (an added runtime helper
10864        // reachable only from a non-`const` context, an
10865        // `Option<RestartPolicy>`-shape migration on the per-child
10866        // restart-decision axis once heterogeneous per-cluster
10867        // restart-policy overlays land that would silently drop the
10868        // `const` qualifier, a manual hand-rolled shadow) trips at
10869        // caixa-core build time rather than surfacing as a downstream
10870        // `const`-context regression far from the declaration.
10871        //
10872        // Same shape as the sibling M3
10873        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
10874        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
10875        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
10876        // accessor axis — the load-bearing witness lives in the
10877        // module-scope `const fn` wrapper `restart_via_const_fn` below:
10878        // a body that calls [`ChildSpec::restart`] under a `const fn`
10879        // signature is well-formed only when the callee is itself
10880        // `const fn`, so any future accidental downgrade of
10881        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
10882        // build time (const-eval E0015 `cannot call non-const method`),
10883        // strictly stronger than a runtime `assert!(CONST)` and
10884        // side-stepping the destructor-in-const restriction that
10885        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
10886        // items on `ChildSpec`'s `String` carriers.
10887        //
10888        // The runtime body sweeps every closed-set [`RestartPolicy`]
10889        // arm and asserts the wrapped and direct dispatches agree.
10890        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
10891            c.restart()
10892        }
10893        for restart in [
10894            RestartPolicy::Permanent,
10895            RestartPolicy::Transient,
10896            RestartPolicy::Temporary,
10897        ] {
10898            let c = ChildSpec {
10899                caixa: "worker".into(),
10900                versao: "^0.1".into(),
10901                restart,
10902            };
10903            assert_eq!(
10904                restart_via_const_fn(&c),
10905                c.restart(),
10906                "const-fn-wrapped and direct dispatch on \
10907                 ChildSpec::restart must agree for {restart:?}",
10908            );
10909            assert_eq!(
10910                c.restart(),
10911                restart,
10912                "ChildSpec::restart must return the storage-side \
10913                 RestartPolicy verbatim for {restart:?} (a violation \
10914                 means the accessor stopped being a raw field-return \
10915                 copy)",
10916            );
10917        }
10918    }
10919
10920    #[test]
10921    fn supervisor_spec_estrategia_accessor_is_const_fn() {
10922        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
10923        // sibling-restart-strategy `Copy`-return scalar accessor is
10924        // declared `#[must_use] pub const fn` — matching the sibling M2
10925        // per-`:children` [`ChildSpec::restart`] (pinned by
10926        // [`child_spec_restart_accessor_is_const_fn`] above, both
10927        // converted in this commit), the sibling M2 per-`:supervisor`
10928        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
10929        // accessor already `pub const fn`, and mirroring the peer M3
10930        // mesh-slot per-`:placement`
10931        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
10932        // `pub const fn` scalar accessor whose method-name discipline
10933        // the [`SupervisorSpec::estrategia`] method was authored to
10934        // match. Pin the `const`-eval posture here so a future
10935        // accidental downgrade to non-`const` (an added runtime helper
10936        // reachable only from a non-`const` context, an
10937        // `Option<RestartStrategy>`-shape migration once the substrate
10938        // grows per-cluster strategy overlays that would silently drop
10939        // the `const` qualifier, a manual hand-rolled shadow) trips at
10940        // caixa-core build time rather than surfacing as a downstream
10941        // `const`-context regression far from the declaration.
10942        //
10943        // Same shape as the sibling
10944        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
10945        // load-bearing witness lives in the module-scope `const fn`
10946        // wrapper `estrategia_via_const_fn` below: a body that calls
10947        // [`SupervisorSpec::estrategia`] under a `const fn` signature
10948        // is well-formed only when the callee is itself `const fn`,
10949        // side-stepping the destructor-in-const restriction that would
10950        // otherwise block a direct
10951        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
10952        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
10953        // carriers.
10954        //
10955        // The runtime body sweeps every closed-set [`RestartStrategy`]
10956        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
10957        // direct dispatches agree.
10958        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
10959            s.estrategia()
10960        }
10961        for &estrategia in RestartStrategy::ALL {
10962            let s = SupervisorSpec {
10963                estrategia,
10964                max_restarts: 5,
10965                restart_window: Some(Duration::from_secs(60)),
10966                children: Vec::new(),
10967            };
10968            assert_eq!(
10969                estrategia_via_const_fn(&s),
10970                s.estrategia(),
10971                "const-fn-wrapped and direct dispatch on \
10972                 SupervisorSpec::estrategia must agree for {estrategia:?}",
10973            );
10974            assert_eq!(
10975                s.estrategia(),
10976                estrategia,
10977                "SupervisorSpec::estrategia must return the storage-side \
10978                 RestartStrategy verbatim for {estrategia:?} (a violation \
10979                 means the accessor stopped being a raw field-return \
10980                 copy)",
10981            );
10982        }
10983    }
10984
10985    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
10986    // macro definition (see the paired doc-block above the macro
10987    // definition) — every generated `<ctor>(caixa: &str) -> Self`
10988    // constructor folds the uniform `Self::<Variant> { caixa:
10989    // caixa.to_string() }` one-field struct-literal onto one substrate
10990    // primitive. The three per-variant equivalence pins below
10991    // (fail-before-pass-after by construction — a byte-mismatched macro
10992    // arm would trip its equivalence pin first) lock each generated
10993    // constructor to its struct-literal peer under `PartialEq`, so
10994    // every wire-up in [`SupervisorSpec::validate_children`] and
10995    // [`validate_no_self_supervision`] on that variant produces a
10996    // byte-equal `SupervisorError` to the pre-lift open-coded
10997    // struct-literal. The cross-axis pin that follows (non-default
10998    // caixa name) routes the sole constructor input axis through
10999    // `.to_string()`, so the fold does not silently collapse onto a
11000    // fixed name.
11001    //
11002    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
11003    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
11004    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
11005    // `missing_entry_ctor_matches_struct_literal_wrap` /
11006    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
11007    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
11008    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
11009    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
11010    // on the six sibling ctor families the recent trajectory closed
11011    // on the peer `LayoutError` / `AplicacaoError` envelopes.
11012
11013    #[test]
11014    fn empty_child_version_ctor_matches_struct_literal_wrap() {
11015        assert_eq!(
11016            SupervisorError::empty_child_version("worker"),
11017            SupervisorError::EmptyChildVersion {
11018                caixa: "worker".to_string(),
11019            },
11020            "generated empty_child_version ctor must produce byte-equal \
11021             SupervisorError to the open-coded struct-literal wrap on the \
11022             same &str fixture",
11023        );
11024    }
11025
11026    #[test]
11027    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
11028        assert_eq!(
11029            SupervisorError::duplicate_child_caixa("worker"),
11030            SupervisorError::DuplicateChildCaixa {
11031                caixa: "worker".to_string(),
11032            },
11033            "generated duplicate_child_caixa ctor must produce byte-equal \
11034             SupervisorError to the open-coded struct-literal wrap on the \
11035             same &str fixture",
11036        );
11037    }
11038
11039    #[test]
11040    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
11041        assert_eq!(
11042            SupervisorError::child_supervises_self("orquestra"),
11043            SupervisorError::ChildSupervisesSelf {
11044                caixa: "orquestra".to_string(),
11045            },
11046            "generated child_supervises_self ctor must produce byte-equal \
11047             SupervisorError to the open-coded struct-literal wrap on the \
11048             same &str fixture",
11049        );
11050    }
11051
11052    // Per-variant equivalence pins for the two lifted
11053    // [`SupervisorError::child_caixa_invalid`] /
11054    // [`SupervisorError::child_versao_invalid`] inherent constructors
11055    // (fail-before-pass-after by construction — a byte-mismatched ctor body
11056    // would trip its equivalence pin first). Each pins the ctor output to
11057    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
11058    // in [`SupervisorSpec::validate_children`] on the two variants
11059    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
11060    // struct-literal on the same scalar fixtures. Peers of the sibling
11061    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
11062    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
11063    // the peer `AplicacaoError` envelope's
11064    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
11065
11066    #[test]
11067    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
11068        let caixa = "Worker";
11069        let reason = "sample reason text";
11070        assert_eq!(
11071            SupervisorError::child_caixa_invalid(caixa, reason),
11072            SupervisorError::ChildCaixaInvalid {
11073                caixa: caixa.to_string(),
11074                reason: reason.to_string(),
11075            },
11076            "lifted child_caixa_invalid ctor must produce byte-equal \
11077             SupervisorError to the open-coded struct-literal wrap on the \
11078             same (&str, reason) fixture",
11079        );
11080    }
11081
11082    #[test]
11083    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
11084        let caixa = "worker";
11085        let versao = "not-a-req";
11086        let reason = "sample reason text";
11087        assert_eq!(
11088            SupervisorError::child_versao_invalid(caixa, versao, reason),
11089            SupervisorError::ChildVersaoInvalid {
11090                caixa: caixa.to_string(),
11091                versao: versao.to_string(),
11092                reason: reason.to_string(),
11093            },
11094            "lifted child_versao_invalid ctor must produce byte-equal \
11095             SupervisorError to the open-coded struct-literal wrap on the \
11096             same (&str, &str, reason) fixture",
11097        );
11098    }
11099
11100    #[test]
11101    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
11102        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
11103        // against a `&str`-literal vs. `format!(…)` reason input to pin
11104        // both constructors accept the `impl Into<String>` bound
11105        // uniformly, so neither wire-up site drifts under a per-arm
11106        // wrapper transformation on the caller-side `reason` axis. Peer
11107        // of the sibling
11108        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
11109        // sweep on the peer `AplicacaoError` envelope.
11110        let via_literal = "literal reason text";
11111        let via_format = format!("{} reason text", "literal");
11112        assert_eq!(
11113            SupervisorError::child_caixa_invalid("Worker", via_literal),
11114            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
11115        );
11116        assert_eq!(
11117            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
11118            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
11119        );
11120    }
11121
11122    #[test]
11123    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
11124        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
11125        // &str`) through a non-default fixture name against every
11126        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
11127        // so any wrapper-side lowercase / trim / truncate / re-order on
11128        // the `caixa.to_string()` sole-field construction surfaces
11129        // here rather than at a downstream diagnostic-shape mismatch.
11130        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
11131        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
11132        // through_to_string` / `contrato_target_ctors_route_edge_
11133        // triple_through_verbatim` / `contrato_empty_pair_ctors_
11134        // route_edge_pair_through_verbatim` cross-axis routing pins on
11135        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
11136        // here onto the `SupervisorError` `{ caixa: String }` envelope
11137        // so every substrate-primitive ctor family in caixa-core
11138        // guarantees the sole-field construction routes the caller's
11139        // `&str` through `.to_string()` verbatim.
11140        let name = "cache-v2";
11141        assert_eq!(
11142            SupervisorError::empty_child_version(name),
11143            SupervisorError::EmptyChildVersion {
11144                caixa: name.to_string(),
11145            },
11146        );
11147        assert_eq!(
11148            SupervisorError::duplicate_child_caixa(name),
11149            SupervisorError::DuplicateChildCaixa {
11150                caixa: name.to_string(),
11151            },
11152        );
11153        assert_eq!(
11154            SupervisorError::child_supervises_self(name),
11155            SupervisorError::ChildSupervisesSelf {
11156                caixa: name.to_string(),
11157            },
11158        );
11159    }
11160
11161    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
11162    //
11163    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
11164    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
11165    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
11166    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
11167    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
11168    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
11169    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
11170    // / silent constant-substitution on any one variant surfaces here rather
11171    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
11172    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
11173    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
11174    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
11175    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
11176    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
11177    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
11178    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
11179    #[test]
11180    fn no_children_ctor_matches_struct_literal_wrap() {
11181        let estrategia = RestartStrategy::OneForAll;
11182        assert_eq!(
11183            SupervisorError::no_children(estrategia),
11184            SupervisorError::NoChildren { estrategia },
11185            "generated no_children ctor must produce byte-equal \
11186             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
11187             on the same `Copy`-`RestartStrategy` fixture",
11188        );
11189    }
11190
11191    #[test]
11192    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
11193        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
11194        assert_eq!(
11195            SupervisorError::max_restarts_exceeds_cap(max_restarts),
11196            SupervisorError::MaxRestartsExceedsCap { max_restarts },
11197            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
11198             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
11199             struct-literal wrap on the same `Copy`-`u32` fixture",
11200        );
11201    }
11202
11203    #[test]
11204    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
11205        let window = Duration::from_micros(1_500);
11206        assert_eq!(
11207            SupervisorError::restart_window_not_canonical(window),
11208            SupervisorError::RestartWindowNotCanonical { window },
11209            "generated restart_window_not_canonical ctor must produce \
11210             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
11211             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
11212        );
11213    }
11214
11215    #[test]
11216    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
11217        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
11218        assert_eq!(
11219            SupervisorError::restart_window_exceeds_cap(window),
11220            SupervisorError::RestartWindowExceedsCap { window },
11221            "generated restart_window_exceeds_cap ctor must produce \
11222             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
11223             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
11224        );
11225    }
11226
11227    #[test]
11228    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
11229        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
11230        // constructor input axis through a non-default `Copy` fixture against
11231        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
11232        // side silent `.into()` / silent constant-substitution / silent field
11233        // re-name away from the canonical `estrategia | max_restarts | window`
11234        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
11235        // axis silently rerouted through some other `Copy` coercion, surfaces
11236        // here rather than at a downstream per-`:supervisor` diagnostic-shape
11237        // drift. Peer of the sibling
11238        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
11239        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
11240        // envelope's per-`:politicas` per-axis ctor family, extended here onto
11241        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
11242        // variant family folded onto a substrate primitive.
11243        //
11244        // Fixtures picked out of each variant's accept-set boundary rather
11245        // than the default value so a silent constant-substitution to a per-
11246        // variant sentinel surfaces here on the structural-equality assertion.
11247        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
11248        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
11249        // isn't the `SimpleOneForOne` arm the sibling
11250        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
11251        // `max_restarts` fixture picks an above-cap magnitude the cap arm
11252        // rejects; the two `Duration` fixtures pick the sub-millisecond and
11253        // above-cap ends of the `:restart-window` canonical-form + cap
11254        // bracket respectively.
11255        let estrategia = RestartStrategy::RestForOne;
11256        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
11257        let sub_ms = Duration::from_micros(1_500);
11258        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
11259        assert_eq!(
11260            SupervisorError::no_children(estrategia),
11261            SupervisorError::NoChildren { estrategia },
11262        );
11263        assert_eq!(
11264            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
11265            SupervisorError::MaxRestartsExceedsCap {
11266                max_restarts: above_cap_restarts,
11267            },
11268        );
11269        assert_eq!(
11270            SupervisorError::restart_window_not_canonical(sub_ms),
11271            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
11272        );
11273        assert_eq!(
11274            SupervisorError::restart_window_exceeds_cap(above_hour),
11275            SupervisorError::RestartWindowExceedsCap { window: above_hour },
11276        );
11277    }
11278
11279    #[test]
11280    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
11281        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
11282        // generated ctor `const fn` so a caller can pin a `SupervisorError`
11283        // at compile time — the same zero-runtime-work property the pre-lift
11284        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
11285        // its `Copy`-pass-through construction path (no `.to_string()` /
11286        // `.into()` allocation, no branching). If any future edit silently
11287        // drops the `const` qualifier from the macro body the per-arm `const`
11288        // bindings below fail to compile, which surfaces the regression at
11289        // the substrate-primitive definition rather than at some downstream
11290        // consumer that had come to rely on the `const`-constructibility.
11291        // Peer of the sibling
11292        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
11293        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
11294        // per-`:politicas` per-axis ctor family.
11295        const NO_CHILDREN: SupervisorError =
11296            SupervisorError::no_children(RestartStrategy::OneForAll);
11297        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
11298        const WINDOW_NC: SupervisorError =
11299            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
11300        const WINDOW_CAP: SupervisorError =
11301            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
11302        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
11303        assert!(matches!(
11304            MAX_RESTARTS_CAP,
11305            SupervisorError::MaxRestartsExceedsCap { .. }
11306        ));
11307        assert!(matches!(
11308            WINDOW_NC,
11309            SupervisorError::RestartWindowNotCanonical { .. }
11310        ));
11311        assert!(matches!(
11312            WINDOW_CAP,
11313            SupervisorError::RestartWindowExceedsCap { .. }
11314        ));
11315    }
11316}