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/// Per-child restart policy.
434///
435/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
436#[derive(
437    Serialize,
438    Deserialize,
439    Debug,
440    Clone,
441    Copy,
442    PartialEq,
443    Eq,
444    Hash,
445    gen_platform::TypedDispatcher,
446    gen_platform::Discriminant,
447    gen_platform::IsVariant,
448    gen_platform::FromStrKind,
449)]
450pub enum RestartPolicy {
451    /// Always restart the child, regardless of how it died. Used for
452    /// long-running services that must always be up.
453    Permanent,
454    /// Never restart. Used for one-shot work whose completion is
455    /// itself the success signal (`oneShot` triggers map here).
456    Temporary,
457    /// Restart only when the child died *abnormally* (non-zero exit
458    /// or unhandled exception). A clean exit completes the child.
459    Transient,
460}
461
462impl Default for RestartPolicy {
463    fn default() -> Self {
464        // Route the [`Default for RestartPolicy`] impl's return arm through
465        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
466        // `pub const` rather than a raw `Self::Permanent` arm — one source
467        // of truth for the Erlang/OTP-canonical `permanent` worker-child
468        // default across the two production consumers that currently
469        // dispatch on it (this impl at the [`RestartPolicy::default`] call
470        // and the serde-side `#[serde(default)]` on
471        // [`ChildSpec::restart`] that resolves an author-omitted
472        // `:children :restart` slot through `RestartPolicy::default()`).
473        // Peer of the sibling per-`:supervisor` axis
474        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
475        // route (95ffacc) — the two impls now share one substrate-primitive
476        // lift discipline, so any future coherent rebrand of the OTP-shape
477        // supervisor+child default set migrates through typed constants in
478        // lockstep instead of splitting a lifted supervisor half against
479        // an open-coded child half. Pinned by
480        // `restart_policy_default_routes_through_lifted_default` +
481        // `child_spec_serde_default_restart_routes_through_lifted_default`
482        // in the tests module.
483        SUPERVISOR_CHILD_RESTART_DEFAULT
484    }
485}
486
487impl RestartPolicy {
488    /// Exhaustive iteration surface for every consumer that walks the
489    /// closed three-arm [`RestartPolicy`] discriminator set (the future
490    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
491    /// per-child admission-webhook rejection body naming the accepted-
492    /// `:restart` list, a future `feira supervisor --restart …` CLI
493    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
494    /// over the slice, the future `feira app graph` per-child restart
495    /// column, any future round-trip fuzz harness that sweeps every
496    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
497    /// theory
498    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
499    /// might reach for once the three canonical OTP restart policies
500    /// stop covering the substrate's discovered load-shape) extends
501    /// this slice as one edit and every consumer picks up the new entry
502    /// by construction; the compiler-checked exhaustiveness on the
503    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
504    /// is the build-time guarantee that no arm forgets to grow.
505    ///
506    /// Peer of the sibling closed-set typed enums'
507    /// [`RestartStrategy::ALL`] (4eec29c) /
508    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
509    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
510    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
511    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
512    /// surfaces — the sixth (and the third and final M2 OTP-shape)
513    /// closed-set typed enum on the caixa surface to converge onto the
514    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
515    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
516    /// sibling-restart-strategy axis; this closes the per-child
517    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
518    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
519
520    /// Canonical PascalCase discriminator scalar this variant serializes
521    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
522    /// arms return the paired
523    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
524    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
525    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
526    /// constants so every substrate consumer that dispatches on the
527    /// per-child restart-decision policy (the future wasm-operator's
528    /// per-child post-exit restart-decision branch, the future M4
529    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
530    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
531    /// reconciliation scheduler's per-child-policy fan-out) reads the
532    /// same byte-string the `Serialize` derive emits — the pin test in
533    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
534    /// asserts the two paths agree, peer of the M2
535    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
536    /// sibling-restart-strategy axis and the M3
537    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
538    /// per-Aplicacao distribution-strategy axis — the third of three
539    /// OTP-shaped closed-enum discriminator axes on the caixa typed
540    /// surface to converge onto the same three-path-convergence
541    /// (`Serialize` derive → `as_str` helper → lifted constant)
542    /// drift-detection posture.
543    #[must_use]
544    pub const fn as_str(self) -> &'static str {
545        match self {
546            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
547            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
548            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
549        }
550    }
551
552    /// Substrate-canonical reverse projection on the `:children :restart`
553    /// closed-set axis — parses the `PascalCase` discriminator scalar
554    /// back to the typed variant, or `None` when `s` is outside the
555    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
556    /// the same lifted
557    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
558    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
559    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
560    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
561    /// of the round-trip migrate through one caixa-core edit on any
562    /// future arm addition.
563    ///
564    /// Prior to this lift the substrate carried only the forward
565    /// `Self → &str` projection on the OTP per-child restart-policy
566    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
567    /// impl routed through it, the `Serialize` derive that emits the
568    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
569    /// plus the kebab-case dispatcher-catalog identity via
570    /// [`Self::discriminant`] — every non-serde consumer that wanted to
571    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
572    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
573    /// "Transient" => …, _ => … }` cascade that expressed no
574    /// compile-time link back to the typed variant's canonical lifted
575    /// constant. A future variant rename or per-arm serde-attribute
576    /// drift would silently split the wire byte-string one non-serde
577    /// consumer parsed from the one the emitter wrote, with the failure
578    /// surfacing at the operator's reconcile posture (a `:temporary`
579    /// `oneShot` child being restarted on clean exit, treating the
580    /// successful-completion signal as failure and re-running the
581    /// completion-terminal one-shot indefinitely; a `:transient` child
582    /// that clean-exited being restarted, masking the clean-completion
583    /// contract) far from the rebrand commit and with no field naming
584    /// the drift.
585    ///
586    /// Distinct axis from the [`std::str::FromStr`] impl the
587    /// [`gen_platform::FromStrKind`] derive already installs on this
588    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
589    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
590    /// `"transient"` — the inverse of [`Self::discriminant`]), while
591    /// this method inverts the `PascalCase` wire byte-string
592    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
593    /// catalog identity live in kebab-case (where every peer catalog
594    /// identifier already lives) without forcing a wire-format rename
595    /// on the tatara-lisp author surface (`:restart Permanent`,
596    /// `PascalCase`) — the same two-axis distinction the sibling
597    /// [`RestartStrategy::from_wire`] (4eec29c) /
598    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
599    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
600    /// carry on their peer closed-set typed-enum wire round-trips.
601    ///
602    /// Same closed-set-reverse-projection discipline the sibling
603    /// [`RestartStrategy::from_wire`] (4eec29c) /
604    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
605    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
606    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
607    /// carry on the peer wire-side `str → Self` axes — extended onto
608    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
609    /// sixth substrate-side closed-set typed enum (and the third and
610    /// final OTP-shape closed-enum discriminator axis) to converge on
611    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
612    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
613    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
614    /// derive already installs on the sibling kebab-case axis. Returns
615    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
616    /// shapes: the caller picks the diagnostic form appropriate for
617    /// its use site.
618    #[must_use]
619    pub fn from_wire(s: &str) -> Option<Self> {
620        match s {
621            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
622            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
623            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
624            _ => None,
625        }
626    }
627}
628
629/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
630/// pretty-printed byte-string every consumer that formats the policy as
631/// user-facing text lands on (the future wasm-operator's per-child
632/// post-exit restart-decision diagnostic line, the future `feira app
633/// graph` per-child restart column, the future M4
634/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
635/// admission-webhook rejection body) reaches for the same lifted
636/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
637/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
638/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
639/// wire-format `Serialize` derive already emits under
640/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
641/// [`RestartPolicy::as_str`] helper already returns.
642///
643/// Pre-convergence the two paths structurally disagreed — the
644/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
645/// route (now retired here) sent [`std::fmt::Display`] through the
646/// gen-platform discriminant catalog string, which arrives kebab-case as
647/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
648/// (whose variant names each collapse to their own lowercase form under
649/// the kebab-case transform), while the wire format ran as `PascalCase`
650/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
651/// serde derive. Every consumer that formatted the policy for a
652/// diagnostic line, a graph column, or a rejection body under
653/// `format!("{v}")` therefore landed under a different byte-string than
654/// the wire format the operator's per-child-policy dispatch keyed off —
655/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
656/// diagnostic quoting `"permanent"` while the wire scalar the operator
657/// probed was `"Permanent"`) surfaced as a confused correlate at
658/// operator-log time far from the two-declaration site.
659///
660/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
661/// path: every `format!("{v}")` call reaches the same lifted
662/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
663/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
664/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
665/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
666/// byte-string per variant. A future variant rename or
667/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
668/// exactly one place, structurally.
669///
670/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
671/// (from `#[derive(gen_platform::Discriminant)]`) still returns
672/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
673/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
674/// registration keys the catalog off the same kebab identity. The two
675/// naming worlds now live on separate typed methods (`Display` /
676/// `as_str` for the wire byte-string, `discriminant` for the catalog
677/// identity) rather than sharing one `Display` route that structurally
678/// disagrees with the wire format.
679///
680/// Pin tests
681/// [`tests::restart_policy_display_routes_through_as_str_helper`]
682/// and
683/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
684/// assert the three paths agree byte-for-byte on every variant, so a
685/// future variant rename or per-arm serde attribute drift is a build
686/// error visible at caixa-core test time, not a silent per-consumer
687/// dispatch miss at apply / reconcile time.
688///
689/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
690/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
691/// and the sibling [`RestartStrategy`] `Display` impl on the
692/// per-supervisor sibling-restart-strategy axis — same three-path-
693/// convergence discipline, extended to close the third and final of
694/// three OTP-shaped closed-enum discriminator axes on the caixa typed
695/// surface.
696impl std::fmt::Display for RestartPolicy {
697    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
698        f.write_str(self.as_str())
699    }
700}
701
702/// Substrate-canonical [`AsRef<str>`] projection on the M2
703/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
704/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
705/// scalar accessor the paired [`std::fmt::Display`] impl and the
706/// un-`rename`d [`serde::Serialize`] derive already key off, so any
707/// future consumer that binds a [`RestartPolicy`] through the
708/// standard-library `impl AsRef<str>` bound (a future
709/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
710/// composes the emitted `PascalCase` wire scalar into a
711/// [`std::process::Command::arg`] shell-out of the future
712/// wasm-operator's per-child admission gate, a per-child structured-
713/// log recorder on the future `caixa-operator`'s hierarchical
714/// reconciliation surface that accepts `impl AsRef<str>` at the
715/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
716/// lookup keyed on the restart-policy wire byte through
717/// `map.get::<str>(policy.as_ref())` on a future per-policy
718/// dispatch table) reaches the paired
719/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
720/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
721/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
722/// lifted-const through one substrate-primitive dispatch rather
723/// than an open-coded `.as_str()` projection at every wire-up.
724///
725/// Peer of the sibling [`std::fmt::Display`] impl on the same
726/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
727/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
728/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
729/// byte-string per instance by construction. A future variant rename
730/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
731/// enum reaches every one of the three paths (plus the wire-format
732/// `Serialize` derive that already routes through the same lifted
733/// const) through exactly one caixa-core edit.
734///
735/// Same "route the trait impl through the substrate-primitive
736/// accessor" discipline the sibling [`crate::CaixaVersion`]
737/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
738/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
739/// the axis onto the paired per-child-restart-decision-policy
740/// sibling on the same M2 `:supervisor` slot (the second M2
741/// OTP-shape closed-set typed enum to converge onto the standard-
742/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
743/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
744/// primitive so a caller who has one has both; before this lift,
745/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
746/// [`AsRef<str>`] impl the convention names.
747///
748/// Pinned load-bearing by
749/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
750/// (byte-parity pin against [`RestartPolicy::as_str`] across the
751/// three-arm closed set) and
752/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
753/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
754/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
755/// arm) — any future silent detour that routes the impl through a
756/// divergent projection (a per-arm inline `match self { … }`
757/// re-inlining that opens a compile-time link to the un-lifted
758/// arm-literal, a swap onto the kebab-case
759/// [`gen_platform::Discriminant`] catalog identity that would
760/// collide the wire axis with the dispatcher-catalog axis) trips at
761/// caixa-core test time under `assert_eq!` rather than at a
762/// downstream `impl AsRef<str>`-bound consumer's silent split.
763impl AsRef<str> for RestartPolicy {
764    fn as_ref(&self) -> &str {
765        self.as_str()
766    }
767}
768
769/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
770/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
771/// byte-for-byte through the paired substrate-primitive
772/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
773/// consumer that binds a `PascalCase` `:children :restart` wire
774/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
775/// axis (a future [`caixa-feira`] `feira supervisor --restart
776/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
777/// `let restart: RestartPolicy = s.try_into()?`, a future
778/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
779/// `spec.children[*].restart: String` field through
780/// `RestartPolicy::try_from(&s)?`, a generic
781/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
782/// set typed enums) reaches the same three-arm accept-set the sibling
783/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
784/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
785/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
786/// … }` cascade whose arm-set has no compile-time link back to the
787/// substrate primitive.
788///
789/// Complements the pre-existing forward-projection triple
790/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
791/// with the paired trait-idiomatic reverse-projection axis: Rust-side
792/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
793/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
794/// caller who can project *out to* a `&str` can also project *in from*
795/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
796/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
797/// lint the sibling method-named [`RestartPolicy::from_wire`] would
798/// trigger under a `FromStr` impl and to avoid colliding with the
799/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
800/// already installs on the paired *kebab-case dispatcher-catalog* axis
801/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
802/// inverse of [`Self::discriminant`]) — this impl closes the trait-
803/// idiomatic reverse axis on the *`PascalCase` wire* half without
804/// disturbing either the method-named `from_wire` shape every sibling
805/// closed-set typed enum on the substrate already carries or the
806/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
807/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
808///
809/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
810/// `Option<Self>` return-shape's deliberate deferral of error typing: the
811/// caller picks the diagnostic form appropriate for its use site (a
812/// future `feira supervisor --restart` arg-parse composes its own
813/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
814/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
815/// wraps the `Err(())` outcome with the accepted-set enumeration for
816/// operator diagnostics, a `Result::map_err` at the call site lifts the
817/// unit-error to a per-verb error type). Same shape the peer
818/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
819/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
820/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
821/// their peer closed-set typed enums' reverse projections.
822///
823/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
824/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
825/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
826/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
827/// might reach for once the three canonical OTP restart policies stop
828/// covering the substrate's discovered load-shape) grows the trait-
829/// idiomatic axis by construction — one caixa-core edit on
830/// [`RestartPolicy::from_wire`] extends both the method-named reverse
831/// projection every existing consumer keys off and the trait-idiomatic
832/// reverse projection this impl exposes, without a coordinated rewrite
833/// across every future `TryFrom<&str>`-bound consumer's arm-set.
834///
835/// Extends the substrate-wide closed-set-enum reverse-projection family
836/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
837/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
838/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
839/// closed-enum discriminator axis on the caixa surface — the paired
840/// per-child `:children :restart` closed set the future wasm-operator's
841/// hierarchical reconciliation scheduler's per-child post-exit
842/// restart-decision branch keys off end-to-end.
843///
844/// Pinned load-bearing by
845/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
846/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
847/// three-arm accept-set),
848/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
849/// (rejection witness against silent accept-set widening), and
850/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
851/// (cross-axis partition pin locking the trait and method-named
852/// projections onto one accept-set).
853impl TryFrom<&str> for RestartPolicy {
854    type Error = ();
855
856    fn try_from(s: &str) -> Result<Self, Self::Error> {
857        Self::from_wire(s).ok_or(())
858    }
859}
860
861// Fleet-wide dispatcher-catalog registrations for caixa's OTP
862// supervisor surface — two more typed shadows over Erlang/OTP
863// primitives the substrate now mechanically tracks (see
864// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
865// theory/TYPED-ABSORPTION.md for the absorption arc).
866gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
867gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
868
869/// One child entry in the supervisor's `:children` list.
870///
871/// Every child references another caixa by `:caixa <nome>` + version
872/// constraint. The supervisor materializes one ComputeUnit per entry.
873#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
874#[serde(rename_all = "camelCase")]
875pub struct ChildSpec {
876    /// The child caixa's `:nome`. Must resolve via the same dependency
877    /// resolution path as `:deps` (caixa-resolver).
878    pub caixa: String,
879
880    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
881    /// [`crate::dep::Dep::versao`].
882    pub versao: String,
883
884    /// Restart policy — an author-omitted slot degrades onto the
885    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
886    /// (`permanent`, the Erlang/OTP worker-child default) through the
887    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
888    /// to.
889    #[serde(default)]
890    pub restart: RestartPolicy,
891}
892
893impl ChildSpec {
894    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
895    /// accessor every consumer that reads the OTP-shape supervised
896    /// child's identity keys off — returns the author-declared
897    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
898    /// from the typed slot's own [`String`] storage.
899    ///
900    /// The `:children :caixa` slot carries the DNS-1123 label — the
901    /// child caixa's `:nome` — that every emitted cluster artifact
902    /// derives its `metadata.name` from verbatim: the rendered
903    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
904    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
905    /// identity, and the per-child K8s Service `metadata.name` the
906    /// future wasm-operator (M3) provisions for inter-child supervision-
907    /// tree wiring. Every downstream consumer that fans on the child's
908    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
909    /// per-child DNS-1123 gate at
910    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
911    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
912    /// [`validate_no_self_supervision`] cross-slot equality check
913    /// against the parent's `:nome`, every `SupervisorError` variant
914    /// carrying the offending child caixa verbatim for `feira lint`
915    /// rendering, the future wasm-operator's hierarchical reconciliation
916    /// scheduler's per-child ComputeUnit-name projection, the future M4
917    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
918    /// admission webhook).
919    ///
920    /// Prior to this lift the `.caixa` byte-string was accessed inline
921    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
922    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
923    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
924    /// carriers' `child.caixa.clone()`, the dedup key's
925    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
926    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
927    /// field-accesses that expressed no compile-time link back to the
928    /// typed slot. A future extension of the `:children :caixa` axis to
929    /// a richer author surface (a per-cluster alias table the operator
930    /// pins through a future `:placement`-scoped slot on the supervisor
931    /// tree, a namespace-qualified rewrite the M4 CR materializer
932    /// applies per-CR, a per-child overlay from the future `:children
933    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
934    /// acknowledges) would have had to be threaded through every
935    /// open-coded copy in lockstep or one consumer would silently
936    /// disagree with the peers on which caixa a given child resolves to
937    /// — a child-set lookup that treated the name as `"cart-worker"`
938    /// while the peer duplicate-detector treated it as
939    /// `"tenant-a/cart-worker"` would silently split the
940    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
941    /// self-supervision detector's parent-equality check, a two-consumer
942    /// split at the validator far from the source `caixa.lisp` with no
943    /// field naming the identity-drift root cause. Lifting the resolution
944    /// rule to a typed method on the substrate primitive means every
945    /// downstream consumer of the Supervisor's per-`:children` identity
946    /// surface reaches for exactly one typed dispatch — the resolver's
947    /// accept-set migrates as a unit on any future axis addition.
948    ///
949    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
950    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
951    /// mesh-slot surface — same "one typed dispatch on the substrate
952    /// primitive, thin projections at each consumer" discipline extended
953    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
954    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
955    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
956    /// accessor discipline for the shared substrate concept "another
957    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
958    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
959    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
960    /// slot family's typed-accessor discipline now spans both the
961    /// upgrade axis (`:upgrade-from`) and the supervision axis
962    /// (`:children`), matching the closed M3 mesh-slot accessor family's
963    /// shape. Named `nome()` to match the tatara-lisp author-surface
964    /// term the field's docstring already reaches for ("The child
965    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
966    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
967    /// discipline the substrate already carries — the accessor's name
968    /// maps directly onto the canonical caixa-identity vocabulary rather
969    /// than shadowing the field's storage-side `caixa` label.
970    #[must_use]
971    pub const fn nome(&self) -> &str {
972        self.caixa.as_str()
973    }
974
975    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
976    /// requirement scalar accessor every consumer that reads the OTP-shape
977    /// supervised child's version pin keys off — returns the author-declared
978    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
979    /// the typed slot's own [`String`] storage.
980    ///
981    /// The `:children :versao` slot carries the Cargo-shaped semver
982    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
983    /// which release of the supervised child caixa the OTP-shape supervisor
984    /// tree materializes against — the same requirement grammar the peer
985    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
986    /// shared [`crate::render::require_valid_versao_requirement`] cascade
987    /// and the shared [`crate::version::parse_requirement`] parser. Every
988    /// downstream consumer that fans on the child's version pin keys off
989    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
990    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
991    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
992    /// for `feira lint` rendering, every future per-cluster version-lock
993    /// overlay the caixa-operator's hierarchical reconciliation scheduler
994    /// pins through a future `:placement`-scoped supervisor-tree slot, the
995    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
996    /// per-child version resolver, the future wasm-operator's per-child
997    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
998    ///
999    /// Prior to this lift the `.versao` byte-string was accessed inline at
1000    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
1001    /// [`SupervisorSpec::validate`] requirement-gate call
1002    /// `require_valid_versao_requirement(&child.versao, …)` and the
1003    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
1004    /// `versao: child.versao.clone()` — two open-coded field-accesses that
1005    /// expressed no compile-time link back to the typed slot. A future
1006    /// extension of the `:children :versao` axis to a richer author surface
1007    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1008    /// flow, a lacre-projected concrete-version rewrite the operator
1009    /// materializes at CR-admission time, a future `:children :versao-lock`
1010    /// per-cluster override slot the wasm-operator's hierarchical
1011    /// reconciliation scheduler authors per-CR) would have had to be
1012    /// threaded through both open-coded copies in lockstep or one consumer
1013    /// would silently disagree with the peer on which release constraint a
1014    /// given child resolves to — the requirement-gate call reading
1015    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
1016    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
1017    /// the actual gate rejection input, a two-consumer split at the
1018    /// validator far from the source `caixa.lisp` with no field naming the
1019    /// version-pin drift root cause. Lifting the resolution rule to a typed
1020    /// method on the substrate primitive means every downstream
1021    /// requirement-facing consumer of the Supervisor's per-`:children`
1022    /// version-pin surface reaches for exactly one typed dispatch — the
1023    /// resolver's accept-set migrates as a unit on any future axis addition.
1024    ///
1025    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
1026    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
1027    /// surface — same "one typed dispatch on the substrate primitive, thin
1028    /// projections at each consumer" discipline extended onto the M2
1029    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
1030    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
1031    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
1032    /// one accessor discipline for the shared substrate concept "another
1033    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
1034    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
1035    /// `:nome` scalar accessor — the pair
1036    /// `(nome(), versao_requirement())` jointly projects the
1037    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
1038    /// that fans on per-child identity + version pin keys off, closing the
1039    /// last unlifted per-`:children` `String`-carry axis so every downstream
1040    /// per-`:children` reader now routes through a typed dispatch on the
1041    /// substrate primitive. Named `versao_requirement()` rather than
1042    /// `versao()` because the field's storage-side `.versao` label is
1043    /// already the author-surface term (`:versao`); the accessor's name
1044    /// carries the semantic role — the semver *requirement* string the
1045    /// shared [`crate::version::parse_requirement`] entry-point consumes —
1046    /// so a raw field access and a typed dispatch read differently at every
1047    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
1048    /// naming discipline verbatim.
1049    #[must_use]
1050    pub const fn versao_requirement(&self) -> &str {
1051        self.versao.as_str()
1052    }
1053
1054    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
1055    /// per-child post-exit restart-decision policy scalar accessor every
1056    /// consumer that dispatches on the supervised child's post-exit
1057    /// reconcile posture keys off — returns the author-declared
1058    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
1059    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
1060    /// storage.
1061    ///
1062    /// The `:children :restart` slot carries the closed-set OTP-shaped
1063    /// per-child restart-decision policy discriminator
1064    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
1065    /// worker-child default; [`RestartPolicy::Transient`] — restart only
1066    /// on abnormal exit, the OTP `transient` clean-completion-aware
1067    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
1068    /// `temporary` one-shot default) that every downstream consumer of
1069    /// the Supervisor's per-child post-exit reconcile branch keys off.
1070    /// Every future downstream consumer that fans on the per-child
1071    /// restart-decision keys off this scalar (the future `feira app
1072    /// graph` per-child restart column, the future wasm-operator's
1073    /// per-child post-exit restart-decision branch, the future M4
1074    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1075    /// admission webhook, the `caixa-operator`'s hierarchical
1076    /// reconciliation scheduler's per-child post-exit reconcile branch,
1077    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
1078    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1079    /// pin threads through).
1080    ///
1081    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
1082    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
1083    /// scalar accessor and the M3 mesh-slot
1084    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
1085    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
1086    /// — same "one typed dispatch on the substrate primitive,
1087    /// `Copy`-projected closed-set enum-arm discriminator that partitions
1088    /// the downstream renderer's per-arm fan-out" discipline extended
1089    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
1090    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
1091    /// [`ChildSpec`] type — companion to the sibling per-`:children`
1092    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
1093    /// and the per-`:children` [`ChildSpec::versao_requirement`]
1094    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
1095    /// on the sibling `String`-carry axes. The triple
1096    /// `(nome(), versao_requirement(), restart())` jointly projects the
1097    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
1098    /// tree consumer that fans on per-child identity + version pin +
1099    /// restart-decision keys off, closing the last unlifted per-`:children`
1100    /// axis so every downstream per-`:children` reader now routes through
1101    /// a typed dispatch on the substrate primitive. Named `restart()` to
1102    /// match the storage field's name and the author-surface
1103    /// `:children :restart` slot term verbatim; the accessor's identity
1104    /// name maps onto the canonical OTP-shape per-child restart-decision-
1105    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
1106    /// carries.
1107    ///
1108    /// Declared `pub const fn` to close the last non-`const`
1109    /// `Copy`-return raw-field-getter posture on the M2
1110    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
1111    /// of the sibling M2 per-`:supervisor`
1112    /// [`SupervisorSpec::estrategia`] (converted in this commit)
1113    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
1114    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1115    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
1116    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
1117    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
1118    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
1119    /// downstream substrate-side `const`-context consumer of the
1120    /// per-`:children` restart-decision-policy scalar (a future
1121    /// module-scope `const _:() = assert!(matches!(child.restart(),
1122    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
1123    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1124    /// admission-webhook `const fn` per-child restart-decision floor
1125    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
1126    /// composer over the substrate primitive that fans on the per-child
1127    /// restart-decision policy at compile time) now reaches through the
1128    /// same typed dispatch on the substrate primitive at const-eval
1129    /// time as at runtime. A future non-`Copy`-return promotion of the
1130    /// scalar (an `Option<RestartPolicy>`-shape migration on the
1131    /// per-child restart-decision axis once heterogeneous per-cluster
1132    /// restart-policy overlays land, a per-tenant restart-policy-alias
1133    /// table the M4 CR materializer resolves per-CR) that would drop
1134    /// the `const` qualifier fails the fail-before-pass-after pin
1135    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
1136    /// build time rather than surfacing as a downstream consumer
1137    /// regression.
1138    #[must_use]
1139    pub const fn restart(&self) -> RestartPolicy {
1140        self.restart
1141    }
1142}
1143
1144/// Supervisor-typed slots that live alongside the standard Caixa
1145/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
1146/// the manifest stays a single typed form; this struct exists for
1147/// validation + conversion.
1148#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1149#[serde(rename_all = "camelCase")]
1150pub struct SupervisorSpec {
1151    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
1152    #[serde(default)]
1153    pub estrategia: RestartStrategy,
1154
1155    /// Max restarts within [`Self::restart_window`] before the
1156    /// supervisor itself terminates (and its parent supervisor decides
1157    /// what to do). Default 5.
1158    #[serde(default = "default_max_restarts")]
1159    pub max_restarts: u32,
1160
1161    /// Sliding window for `max_restarts`. Authored as a duration
1162    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
1163    /// is rejected by [`Self::validate`] — Erlang/OTP's
1164    /// `MaxIntensity / Period` invariant requires a positive window
1165    /// (a zero-period supervisor either trips on the first failure or
1166    /// never trips, depending on operator interpretation, neither of
1167    /// which is the author's intent). Omit the slot to express "no
1168    /// reset"; carry a positive duration to express the sliding window.
1169    #[serde(
1170        default,
1171        skip_serializing_if = "Option::is_none",
1172        with = "duration_codec"
1173    )]
1174    pub restart_window: Option<Duration>,
1175
1176    /// Static children. Empty for `SimpleOneForOne` (children added
1177    /// dynamically); required for the other three strategies.
1178    #[serde(default)]
1179    pub children: Vec<ChildSpec>,
1180}
1181
1182const fn default_max_restarts() -> u32 {
1183    // Route the private serde-`#[serde(default = "…")]` helper through
1184    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
1185    // `pub const` rather than the raw `5` literal — one source of truth
1186    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
1187    // default across the two production consumers that currently
1188    // dispatch on it (this helper via `#[serde(default = "…")]` on
1189    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
1190    // impl at line 962). Pinned by
1191    // `default_max_restarts_helper_routes_through_lifted_default` +
1192    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
1193    // in the tests module; peer of the sibling caixa-core
1194    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
1195    // that now routes its author-omitted `:max-restarts` arm through
1196    // the same lifted constant.
1197    SUPERVISOR_MAX_RESTARTS_DEFAULT
1198}
1199
1200/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
1201/// count default for the `:supervisor :max-restarts` axis — the
1202/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
1203/// Erlang's worker-supervisor default, extracted as a typed `pub const`
1204/// so every substrate-side consumer that resolves "what
1205/// [`SupervisorSpec::max_restarts`] value does an author-omitted
1206/// `:max-restarts` slot degrade onto?" reaches for exactly one
1207/// substrate-primitive `u32`.
1208///
1209/// The `:max-restarts` default axis has two production consumers on the
1210/// substrate side today (both prior to this lift folded onto raw `5`
1211/// literals with no compile-time link back to a shared truth): the
1212/// serde-`#[serde(default = "default_max_restarts")]` helper on
1213/// [`SupervisorSpec::max_restarts`] that every author-omitted
1214/// `:supervisor :max-restarts` slot lands in past the derive-macro's
1215/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
1216/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
1217/// the composed [`SupervisorSpec`] altitude reaches through
1218/// (`feira app graph`, the future wasm-operator's per-supervisor
1219/// restart-intensity counter, the future M4
1220/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1221/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
1222/// A pair of open-coded `5`s across two files that expressed no
1223/// compile-time link back to the shared OTP-canonical default — a
1224/// future rebrand of the default (a tightening to Elixir's
1225/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
1226/// the operator pins through a future
1227/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
1228/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1229/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
1230/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
1231/// per-child-cohort roadmap lands) would have had to be threaded
1232/// through both open-coded copies in lockstep or the wire-format
1233/// author-omitted arm and the view-construction author-omitted arm
1234/// would silently disagree on which restart-budget an omitted
1235/// `:max-restarts` resolves to (an author writing `:supervisor
1236/// (:max-restarts ())` would round-trip through serde with the new
1237/// default while `supervisor_view` silently continued to compose the
1238/// stale `5`, or vice versa), a two-consumer split at the composition
1239/// boundary far from the source `caixa.lisp` with no field naming the
1240/// default-drift root cause. Lifting the resolution rule to a typed
1241/// `pub const` on the substrate primitive means every downstream
1242/// consumer of the per-Supervisor default-restart-budget-count surface
1243/// reaches for exactly one substrate-primitive `u32` — the resolver's
1244/// accepted value migrates as a unit on any future axis change.
1245///
1246/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1247/// worker-supervisor default (the closest canonical OTP-shape
1248/// production reference the substrate carries, matching the sibling
1249/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
1250/// this constant with on the paired sliding-window axis). Two orders of
1251/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
1252/// (the upper bracket on the same axis, sibling of this lower default;
1253/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
1254/// axis and now share one accessor discipline on the substrate) and
1255/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
1256/// restart floor — the "one restart, then escalate" default is
1257/// deliberately loose enough to absorb a short burst of transient
1258/// child failures without escalating past the supervisor's parent
1259/// while remaining tight enough to trip the `MaxIntensity / Period`
1260/// ratio's escalation on a genuinely-stuck child within the sibling
1261/// `60s` sliding window.
1262///
1263/// Lifted as a typed `pub const` so the bound has exactly one source
1264/// of truth — the serde-side wire-format author-omitted arm at
1265/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
1266/// struct-literal default field, and the caixa-core
1267/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
1268/// arm all read from one place. Same shape every other typed default
1269/// in this crate carries (the sibling
1270/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
1271/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
1272/// sibling `:restart-window` axis, and the peer
1273/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1274/// per-renderer defaults on the caixa-flux / caixa-helm rendering
1275/// axes).
1276pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
1277
1278/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
1279/// validated [`SupervisorSpec::max_restarts`] past
1280/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
1281///
1282/// The typed field is `u32` (the zero-floor arm
1283/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
1284/// so a programmatic struct literal
1285/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
1286/// author-surface form (`:max-restarts 4294967295` or any
1287/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
1288/// cleanly through serde — a structurally unbounded `u32` ceiling. The
1289/// runtime substrate consuming the value (Erlang/OTP's
1290/// `MaxIntensity / Period` ratio, the future wasm-operator's
1291/// per-supervisor restart-intensity counter, the M4
1292/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
1293/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
1294/// escalation threshold is structurally so high that no realistic
1295/// restarts-per-`:restart-window` traffic shape can reach it, the
1296/// supervisor never escalates to its parent, and a bad child can loop
1297/// inside the window indefinitely with the parent supervisor structurally
1298/// never receiving the "this subtree has exceeded its restart budget"
1299/// signal the typed slot is meant to express — the canonical
1300/// "supervisor intensity declared, no escalation" footgun, exactly the
1301/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
1302/// on the `:politicas :circuit-breaker :max-failures` axis (both are
1303/// "trip the next-higher protection layer after N events in a rolling
1304/// window" counters with identical degenerate-at-the-high-end shape).
1305///
1306/// The `1000` ceiling matches the sibling
1307/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
1308/// peer — same "events-per-window trip threshold" semantics, same `u32`
1309/// type, same no-op-at-the-high-end failure mode) so the M4
1310/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
1311/// and the future wasm-operator's per-supervisor restart-intensity
1312/// counter reach for either field knowing the value is in `1..=1000`
1313/// without re-validating at the reconciler layer. The cap sits two
1314/// orders of magnitude above every documented Erlang/OTP production
1315/// playbook recommendation (Learn You Some Erlang's
1316/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
1317/// `max_restarts: 3` default, OTP's `supervisor` callback module
1318/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
1319/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
1320/// default) and below the clearly-pathological "effectively no
1321/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
1322/// author can plausibly want at hyperscale (a long-running supervisor
1323/// over a very-flaky pool tolerating thousands of transient restarts
1324/// before escalating), but a hard wall above which the typed policy is
1325/// structurally a no-op carried verbatim on every emitted child-restart
1326/// reconciliation contract.
1327///
1328/// Lifted as a typed `pub const` so the bound has exactly one source of
1329/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1330/// materializer's admission webhook and the wasm-operator-side
1331/// per-supervisor restart-intensity reconciler read from one place. Same
1332/// shape every other typed upper bound in this crate carries
1333/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1334/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1335/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1336/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1337/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1338/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1339pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
1340
1341/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
1342/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
1343/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
1344/// (inclusive on both ends, integer-millisecond magnitudes by the
1345/// canonical-form gate immediately preceding).
1346///
1347/// The typed field is `Option<Duration>` (the zero-floor arm
1348/// [`SupervisorError::RestartWindowZero`] already rejects
1349/// `Some(Duration::ZERO)`, and the canonical-form arm
1350/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
1351/// sub-millisecond residue), so a programmatic struct literal
1352/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
1353/// .. }` — 24h) and the equivalent author-surface form
1354/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
1355/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
1356/// cleanly through serde — a structurally unbounded `Duration` ceiling.
1357/// A `:restart-window` value far above the documented Erlang/OTP
1358/// `MaxIntensity / Period` production-playbook band (Learn You Some
1359/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
1360/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
1361/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
1362/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
1363/// degenerates the supervisor's restart-intensity counter into a
1364/// lifetime counter: the rolling failure-counting window is structurally
1365/// so long that transient restarts are never forgotten, so the
1366/// `MaxIntensity / Period` ratio degenerates from "trip the parent
1367/// supervisor when the child has exceeded its restart budget *within
1368/// the recent window*" to "trip the parent when the child has exceeded
1369/// its restart budget *over its lifetime*" — every transient restart
1370/// counts against the budget forever, the supervisor's reset semantic
1371/// never reaches the child, and the typed `:restart-window` slot
1372/// becomes a no-op rolling window carried on every emitted hierarchical
1373/// reconciliation contract. The canonical
1374/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
1375/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
1376/// `:politicas :circuit-breaker :window` axis with identical shape (both
1377/// are "rolling failure-counting window with a per-`Period` reset" Duration
1378/// axes whose lifetime-counter degenerate at the high end is the same
1379/// "the reset semantic never fires" CSE invariant violation).
1380///
1381/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
1382/// the shared duration codec emits (`"<n>h"` for any integer-hour
1383/// magnitude) — every value in the canonical authoring form's
1384/// `<integer><unit>` grammar at or below this cap renders to a clean
1385/// canonical string — and matches the three sibling typed-`Duration`
1386/// caps already lifted to this surface
1387/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1388/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
1389/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
1390/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
1391/// per-supervisor `:supervisor :restart-window` — now share a single
1392/// uniform top edge at the codec's largest emitted unit so the next
1393/// typed-slot wiring (the future wasm-operator's per-supervisor
1394/// `MaxIntensity / Period` reconciler, the M4
1395/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1396/// webhook, the `caixa-operator`'s hierarchical reconciliation
1397/// scheduler) reaches for any of the four knowing the value is in
1398/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
1399/// two orders of magnitude above every documented Erlang/OTP / Elixir /
1400/// Riak Core / RabbitMQ production-playbook recommendation band
1401/// (`5s..=300s`) and below the clearly-pathological "rolling window
1402/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
1403/// a value the author can plausibly want for a very-low-traffic
1404/// long-tail failure-restart window over a hyperscale-flaky child pool,
1405/// but a hard wall above which the rolling-window contract is
1406/// structurally a lifetime-counter contract.
1407///
1408/// Lifted as a typed `pub const` so the bound has exactly one source
1409/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1410/// materializer's admission webhook, the wasm-operator-side
1411/// per-supervisor `MaxIntensity / Period` reconciler, and the
1412/// `caixa-operator`'s hierarchical reconciliation scheduler all read
1413/// from one place. Same shape every other typed upper bound in this
1414/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
1415/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1416/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1417/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1418/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1419/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1420/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
1421/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1422/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1423pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
1424
1425/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
1426/// default for the `:supervisor :restart-window` axis — the canonical
1427/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
1428/// worker-supervisor default, extracted as a typed `pub const` so every
1429/// substrate-side consumer that resolves "what
1430/// [`SupervisorSpec::restart_window`] value does an author-omitted
1431/// `:restart-window` slot degrade onto?" reaches for exactly one
1432/// substrate-primitive [`Duration`].
1433///
1434/// The `:restart-window` default axis has one production consumer on the
1435/// substrate side today: the [`Default for SupervisorSpec`] impl's
1436/// struct-literal `restart_window` field, which prior to this lift folded
1437/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
1438/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
1439/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
1440/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
1441/// *not* fall back to this default on the sibling `:restart-window` axis
1442/// — an author-omitted `:supervisor :restart-window` composes to
1443/// `restart_window: None` (the shared codec's soft-swallow shape),
1444/// keeping author-declared intent ("no reset — never escalate on rolling
1445/// window") distinct from the [`Default for SupervisorSpec`] "canonical
1446/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
1447/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
1448/// default was split across two files with no compile-time link between
1449/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
1450/// `MaxIntensity` half at the substrate primitive while the `Period`
1451/// half rode as an open-coded literal at the composition site, so a
1452/// future coherent rebrand of the paired canonical (a tightening to
1453/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
1454/// per-cluster overlay the operator pins through a future
1455/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
1456/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1457/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
1458/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
1459/// roadmap lands) would have had to migrate the `MaxIntensity` half
1460/// through the lifted constant and the `Period` half through a raw
1461/// literal in lockstep or the two halves of the same OTP-canonical
1462/// default would silently drift out of pairing. Lifting the resolution
1463/// rule to a typed `pub const` on the substrate primitive means the
1464/// paired OTP-canonical default migrates as one unit on any future
1465/// axis change.
1466///
1467/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1468/// worker-supervisor default (the closest canonical OTP-shape
1469/// production reference the substrate carries, matching the paired
1470/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
1471/// constant is the `Period` denominator of on the same
1472/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
1473/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
1474/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
1475/// this lower default; both are typed [`Duration`] const bounds on the
1476/// `:supervisor :restart-window` axis and now share one accessor
1477/// discipline on the substrate) and above the OTP-`supervisor`
1478/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
1479/// rolling window" default is deliberately loose enough to absorb a
1480/// short burst of transient child failures without escalating past the
1481/// supervisor's parent while remaining tight enough for the paired
1482/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
1483/// stuck child within a human-scale observation window.
1484///
1485/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1486/// exactly one source of truth on each half — the sibling
1487/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
1488/// `Period` `60s` half now share the same substrate-primitive lift
1489/// discipline. Same shape every other typed default in this crate
1490/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
1491/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
1492/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
1493/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
1494/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
1495/// caixa-flux / caixa-helm rendering axes).
1496pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
1497
1498/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
1499/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
1500/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
1501/// worker-supervisor default, extracted as a typed `pub const` so every
1502/// substrate-side consumer that resolves "what
1503/// [`SupervisorSpec::estrategia`] variant does an author-omitted
1504/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
1505/// primitive [`RestartStrategy`].
1506///
1507/// The `:estrategia` default axis has three production consumers on the
1508/// substrate side today: the [`Default for RestartStrategy`] impl's
1509/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
1510/// `estrategia` field, and the
1511/// [`crate::manifest::Caixa::supervisor_view`] fold's
1512/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
1513/// collapse arm — three entry points onto the same OTP-canonical
1514/// `one_for_one` value that prior to this lift folded onto a raw
1515/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
1516/// implicit `RestartStrategy::default()` routes at the sibling consumers,
1517/// with no compile-time link back to the paired
1518/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
1519/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
1520/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
1521/// triple was split across three altitudes with no compile-time link
1522/// between the halves: the `MaxIntensity` half rode through the lifted
1523/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
1524/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1525/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
1526/// discriminator at the [`Default for RestartStrategy`] impl, so a future
1527/// coherent rebrand of the triple (Elixir's `{:one_for_one,
1528/// max_restarts: 3, max_seconds: 5}` — same strategy, different
1529/// intensity/period; an OTP `rest_for_one` widening once the substrate
1530/// discovers startup-order-coupled child cohorts as the more common
1531/// worker-supervisor default; a per-cluster overlay the operator pins
1532/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
1533/// §III.2 supervision-canary roadmap acknowledges) would have had to
1534/// migrate the `MaxIntensity` + `Period` halves through the lifted
1535/// constants and the `one_for_one` half through an open-coded arm in
1536/// lockstep or the three halves of the same OTP-canonical default would
1537/// silently drift out of pairing. Lifting the resolution rule to a typed
1538/// `pub const` on the substrate primitive means the paired OTP-canonical
1539/// worker-supervisor default migrates as one unit on any future axis
1540/// change.
1541///
1542/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
1543/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
1544/// closest canonical OTP-shape production reference the substrate
1545/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
1546/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1547/// `60s` `Period` half). The `one_for_one` strategy — restart only the
1548/// failed child, leaving siblings untouched — is the default for tree-of-
1549/// independent-workers use cases the substrate's [`RestartStrategy`]
1550/// discriminator's own docstring already carries as the default arm; it
1551/// composes with the `{5, 60}` restart-intensity ratio to name the same
1552/// substrate-canonical "canonical worker-supervisor" shape the paired
1553/// halves close on their respective axes.
1554///
1555/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1556/// exactly one source of truth on each of its three halves — the sibling
1557/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
1558/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
1559/// this `one_for_one` strategy half now share the same substrate-
1560/// primitive lift discipline. Same shape every other typed default in
1561/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
1562/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
1563/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
1564/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
1565/// upper caps on the paired sibling axes, and the peer
1566/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1567/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
1568pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
1569
1570/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
1571/// default for the `:children :restart` axis — the OTP `permanent`
1572/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
1573/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
1574/// `pub const` so every substrate-side consumer that resolves "what
1575/// [`ChildSpec::restart`] variant does an author-omitted `:children
1576/// :restart` slot degrade onto?" reaches for exactly one substrate-
1577/// primitive [`RestartPolicy`].
1578///
1579/// Completes the OTP-shape supervisor-tree default set at the substrate
1580/// primitive. The per-`:supervisor` axis already carries all three of its
1581/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1582/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
1583/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1584/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
1585/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
1586/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
1587/// the M2 `:supervisor` slot family. The split mattered because the two
1588/// axes resolve *together* on every author-omitted supervisor: a
1589/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
1590/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
1591/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
1592/// `permanent` through an open-coded enum arm, so a future coherent
1593/// rebrand of the OTP-shape default set (an Elixir-shaped
1594/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
1595/// per-cluster overlay the operator pins through the MESH-COMPOSITION
1596/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
1597/// once the substrate discovers clean-completion-aware children as the
1598/// more common child shape) would have had to migrate three halves
1599/// through typed constants and the fourth through a raw enum arm in
1600/// lockstep or the supervisor-level and child-level defaults would
1601/// silently drift apart.
1602///
1603/// The `:children :restart` default axis has two production consumers on
1604/// the substrate side today: the [`Default for RestartPolicy`] impl's
1605/// return arm, and the serde-side `#[serde(default)]` on
1606/// [`ChildSpec::restart`] that resolves an author-omitted `:children
1607/// :restart` slot through that same impl. Both now key off this one
1608/// substrate primitive, so the future wasm-operator's per-child post-exit
1609/// restart-decision branch, the future M4
1610/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1611/// admission webhook, and the `caixa-operator`'s hierarchical
1612/// reconciliation scheduler's per-child fan-out all reach for one typed
1613/// identifier when they resolve an omitted per-child restart posture.
1614///
1615/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
1616/// worker-child restart type — always restart the child regardless of how
1617/// it died, the canonical posture for long-running services that must
1618/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1619/// `one_for_one` tree-of-independent-workers strategy this constant pairs
1620/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
1621/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
1622/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
1623/// [`RestartPolicy::Temporary`] — never restart) express deliberate
1624/// one-shot / clean-completion-aware postures an author declares
1625/// explicitly, never a posture an omitted slot should silently assume.
1626pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
1627
1628/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
1629/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
1630/// `pub const fn` constructor rather than a struct-literal cascade over
1631/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
1632/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1633/// lifted consts — one source of truth for the Erlang/OTP-canonical
1634/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
1635/// paths every downstream consumer already reaches through (the
1636/// hand-authored-until-now [`Default::default`] the
1637/// `..SupervisorSpec::default()` struct-update-syntax on every
1638/// one-axis-under-test fixture in this crate's test module rests on,
1639/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
1640/// every `const`-context consumer reaches through).
1641///
1642/// Extends the [`Default`]-through-const-ctor fold discipline the
1643/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
1644/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
1645/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
1646/// and [`crate::BehaviorSpec`]
1647/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
1648/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
1649/// typed-slot spec family — extended here onto the M2 supervisor-slot
1650/// [`SupervisorSpec`] whose canonical baseline is not "everything
1651/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
1652/// supervisor triple. The `empty()` peer's naming did not fit
1653/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
1654/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
1655/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
1656/// the sibling `Option`-only slots fold to), so this peer is named
1657/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
1658/// existing per-arm pin tests
1659/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
1660/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
1661/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
1662/// already reach for. Pinned load-bearing by
1663/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
1664/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
1665/// [`PartialEq`], sharpening the sibling
1666/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
1667/// pins from a per-field lift into a whole-struct one-source-of-truth
1668/// pin — the derived-until-now [`Default::default`] and the
1669/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
1670/// construction, not by coincidence).
1671impl Default for SupervisorSpec {
1672    #[inline]
1673    fn default() -> Self {
1674        Self::otp_canonical()
1675    }
1676}
1677
1678impl SupervisorSpec {
1679    /// `const`-context peer of the [`Default for SupervisorSpec`]
1680    /// impl (which routes through this constructor) — returns the
1681    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
1682    /// baseline this crate reaches for in every fixture-builder
1683    /// `..SupervisorSpec::default()` struct-update expression and
1684    /// every downstream `SupervisorSpec::default()` seed.
1685    ///
1686    /// Each field routes through the same substrate-canonical
1687    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
1688    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
1689    /// per-arm pin tests
1690    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
1691    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
1692    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
1693    /// already assert, so a future coherent rebrand of the OTP-canonical
1694    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
1695    /// cluster overlay via a future `:restart-window-overrides` slot, a
1696    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
1697    /// absorption roadmap acknowledges) migrates through three typed
1698    /// constants in lockstep, and the paired [`Default`] impl inherits
1699    /// every future extension by construction.
1700    ///
1701    /// `pub const fn` rather than the derived-style `Default::default`
1702    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
1703    /// [`Default::default`] is not `const` on stable Rust, and
1704    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
1705    /// every consumer through a [`Clone::clone`]. The `pub const fn`
1706    /// discipline lets `const`-context callers construct the OTP-
1707    /// canonical baseline at compile time without runtime dispatch on
1708    /// the derived [`Default::default`], the same posture the sibling
1709    /// [`crate::LimitsSpec::empty`] (9739971) /
1710    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
1711    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
1712    /// spec `pub const fn` constructors carry on the sibling
1713    /// "everything `None`" baseline axis.
1714    ///
1715    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
1716    /// of the derived-style [`Default`]" family — sibling of the
1717    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
1718    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
1719    /// baseline" trio, extended here onto the M2 supervisor-slot
1720    /// [`SupervisorSpec`] whose canonical baseline is not "everything
1721    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
1722    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
1723    /// than `empty()` to name the actual invariant the return value
1724    /// pins — the same phrasing already used in the per-arm pin tests
1725    /// on this file. Pinned load-bearing by
1726    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
1727    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
1728    #[must_use]
1729    pub const fn otp_canonical() -> Self {
1730        Self {
1731            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
1732            max_restarts: default_max_restarts(),
1733            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
1734            children: Vec::new(),
1735        }
1736    }
1737
1738    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
1739    /// sibling-restart-strategy scalar accessor every consumer that
1740    /// dispatches on the supervisor's per-sibling restart-decision shape
1741    /// keys off — returns the author-declared `:supervisor :estrategia`
1742    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
1743    /// the typed slot's own [`RestartStrategy`] storage.
1744    ///
1745    /// The `:supervisor :estrategia` slot carries the closed-set
1746    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
1747    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
1748    /// [`RestartStrategy::OneForAll`] — restart every child on any child
1749    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
1750    /// [`RestartStrategy::RestForOne`] — restart the failed child and
1751    /// every child started after it, the Erlang/OTP `rest_for_one`
1752    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
1753    /// dynamic children of the same shape, the Erlang/OTP
1754    /// `simple_one_for_one` per-session default) that every downstream
1755    /// consumer of the Supervisor's per-sibling restart-decision fan-out
1756    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
1757    /// paired coherently with the sibling `:children` axis
1758    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
1759    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
1760    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
1761    /// downstream consumer that reads the strategy keys off this scalar
1762    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
1763    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
1764    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
1765    /// `estrategia:` field, the future `feira app graph` per-Supervisor
1766    /// strategy print line, the future wasm-operator's per-supervisor
1767    /// sibling-restart-strategy branch, the future M4
1768    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
1769    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
1770    /// reconciliation scheduler's per-strategy fan-out).
1771    ///
1772    /// Prior to this lift the `.estrategia` field was accessed inline at
1773    /// two production sites in `caixa-core/src/supervisor.rs` — the
1774    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
1775    /// `match self.estrategia { … }` partition dispatch, and the
1776    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
1777    /// carrier at `estrategia: self.estrategia` — two open-coded
1778    /// field-accesses that expressed no compile-time link back to the
1779    /// typed slot. A future extension of the `:supervisor :estrategia`
1780    /// axis to a richer author surface (a per-cluster strategy override
1781    /// the operator pins through a future `:supervisor :estrategia-overrides`
1782    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
1783    /// acknowledges, a per-tenant strategy-alias table the M4 CR
1784    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
1785    /// derivation the future adaptive-supervision engine computes from
1786    /// child-failure-history topology, a per-child-cohort strategy split
1787    /// the future `RestForCohort` extension acknowledged by the
1788    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
1789    /// would have had to be threaded through every open-coded copy in
1790    /// lockstep — one consumer reading the raw variant while a peer read
1791    /// the operator-resolved variant would silently split the
1792    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
1793    /// the actual partition-dispatch input the empty-children refusal
1794    /// arm reached under, a two-consumer split at the validator far from
1795    /// the source `caixa.lisp` with no field naming the strategy-drift
1796    /// root cause. Lifting the resolution rule to a typed method on the
1797    /// substrate primitive means every downstream consumer of the
1798    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
1799    /// reaches for exactly one typed dispatch — the resolver's accept-set
1800    /// migrates as a unit on any future axis addition.
1801    ///
1802    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
1803    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
1804    /// per-`:placement` distribution-strategy axis — same "one typed
1805    /// dispatch on the substrate primitive, thin projections at each
1806    /// consumer" discipline extended onto the M2 supervisor-slot
1807    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
1808    /// scalar axis. The two typed axes (`Placement::estrategia` on the
1809    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
1810    /// Supervisor side) now share one accessor discipline for the shared
1811    /// substrate concept "a `Copy`-projected closed-set enum-arm
1812    /// discriminator that partitions the downstream renderer's per-arm
1813    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
1814    /// `SupervisorSpec` type — companion to the sibling per-`:children`
1815    /// [`crate::ChildSpec::nome`] (57c61d0) /
1816    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
1817    /// scalar accessors on the sibling per-`:children` `String`-carry
1818    /// axes. Named `estrategia()` to match the storage field's name and
1819    /// the peer [`crate::Placement::estrategia`] method-name discipline
1820    /// verbatim; the accessor's identity name maps onto the canonical
1821    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
1822    /// docstring already carries.
1823    ///
1824    /// Declared `pub const fn` to close the M2 supervisor-slot
1825    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
1826    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
1827    /// (converted in this commit) `Copy`-composite-enum accessor, peer
1828    /// of the sibling M2 per-`:supervisor`
1829    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1830    /// already lifted, and mirror of the peer M3 mesh-slot
1831    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
1832    /// `Copy`-return `pub const fn` scalar accessor whose method-name
1833    /// discipline this accessor was authored to match. Every downstream
1834    /// substrate-side `const`-context consumer of the per-`:supervisor`
1835    /// sibling-restart-strategy scalar (a future module-scope `const
1836    /// _:() = assert!(matches!(sup.estrategia(),
1837    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
1838    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1839    /// admission-webhook `const fn` per-supervisor strategy-arm floor
1840    /// over a typed [`SupervisorSpec`], any future `const fn`
1841    /// supervisor-tree composer over the substrate primitive that fans
1842    /// on the sibling-restart-strategy at compile time) now reaches
1843    /// through the same typed dispatch on the substrate primitive at
1844    /// const-eval time as at runtime. A future non-`Copy`-return
1845    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
1846    /// migration once the substrate grows per-cluster strategy overlays
1847    /// the [`SupervisorSpec`] docstring already anticipates, a
1848    /// per-tenant strategy-alias table the M4 CR materializer resolves
1849    /// per-CR) that would drop the `const` qualifier fails the
1850    /// fail-before-pass-after pin
1851    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
1852    /// caixa-core build time rather than surfacing as a downstream
1853    /// consumer regression.
1854    #[must_use]
1855    pub const fn estrategia(&self) -> RestartStrategy {
1856        self.estrategia
1857    }
1858
1859    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
1860    /// `MaxIntensity` restart-budget scalar accessor every consumer that
1861    /// reads the supervisor's per-`:restart-window` restart-budget count
1862    /// keys off — returns the author-declared `:supervisor :max-restarts`
1863    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
1864    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
1865    /// borrow of `&self` past the call). Non-optional (the `u32` field
1866    /// carries the restart-budget count as a required axis with a
1867    /// [`default_max_restarts`]-supplied default; the zero-floor arm
1868    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
1869    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
1870    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
1871    ///
1872    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
1873    /// `MaxIntensity` restart-budget count that pairs with the sibling
1874    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
1875    /// restart-intensity ratio the supervisor trips its own escalation on
1876    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
1877    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
1878    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
1879    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
1880    /// upper-cap bracket at
1881    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
1882    /// wasm-operator's per-supervisor restart-intensity counter's
1883    /// budget-vs-count comparator, the future M4
1884    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1885    /// webhook, the `caixa-operator`'s hierarchical reconciliation
1886    /// scheduler's per-supervisor escalation-decision branch, every
1887    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
1888    /// offending count verbatim for `feira lint` rendering).
1889    ///
1890    /// Prior to this lift the `.max_restarts` field was accessed inline at
1891    /// one production site in `caixa-core/src/supervisor.rs` — the
1892    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
1893    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
1894    /// that expressed no compile-time link back to the typed slot. A
1895    /// future extension of the `:max-restarts` axis to a richer author
1896    /// surface (a per-cluster restart-budget override the operator pins
1897    /// through a future `:supervisor :max-restarts-overrides` slot the
1898    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
1899    /// a per-tenant restart-budget-alias table the M4 CR materializer
1900    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
1901    /// the future adaptive-supervision engine computes from child-failure-
1902    /// history topology, a promotion of the plain `u32` count to a richer
1903    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
1904    /// budget-partition slot comes into scope) would have had to be
1905    /// threaded through every open-coded copy in lockstep or the validate
1906    /// gate and the future M4 emit path would silently disagree on which
1907    /// restart-budget count a given supervisor resolves to — an author's
1908    /// `:max-restarts 5` would satisfy validate while the emit path
1909    /// silently read a drifted other value (a `:max-restarts 10000`
1910    /// no-op supervisor at the emit boundary would carry the author's
1911    /// declared `5` verbatim in `feira lint` output while the future
1912    /// wasm-operator's restart-intensity counter operated under the
1913    /// drifted count), a two-consumer split at the validator far from the
1914    /// source `caixa.lisp` with no field naming the restart-budget-drift
1915    /// root cause. Lifting the resolution rule to a typed method on the
1916    /// substrate primitive means every downstream consumer of the
1917    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
1918    /// for exactly one typed dispatch — the resolver's accept-set migrates
1919    /// as a unit on any future axis addition.
1920    ///
1921    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
1922    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
1923    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
1924    /// outlier-detection trip-threshold axis — same "one typed dispatch on
1925    /// the substrate primitive, thin projections at each consumer"
1926    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
1927    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
1928    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
1929    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
1930    /// one accessor discipline for the shared substrate concept "a
1931    /// `Copy`-projected required `u32` count that trips the next-higher
1932    /// protection layer after N events in a rolling window" — both are
1933    /// counters with identical degenerate-at-the-high-end shape and share
1934    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
1935    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
1936    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
1937    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
1938    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
1939    /// the storage field's name verbatim and the peer
1940    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
1941    /// accessor's identity maps onto the canonical OTP-shape supervision
1942    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
1943    /// already carries.
1944    #[must_use]
1945    pub const fn max_restarts(&self) -> u32 {
1946        self.max_restarts
1947    }
1948
1949    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
1950    /// `Period` sliding-window scalar accessor every consumer of the
1951    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
1952    /// keys off — returns the author-declared `:supervisor :restart-window`
1953    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
1954    /// the typed slot's own `Option<Duration>` storage (`Duration` is
1955    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
1956    /// value; no borrow of `&self` past the call). `None` when the slot is
1957    /// absent (the canonical "never reset — every restart across the
1958    /// supervisor's lifetime counts against the sibling `:max-restarts`
1959    /// budget" sentinel the field's own docstring names and the peer
1960    /// `validate_accepts_none_restart_window` pin locks in on the
1961    /// [`SupervisorSpec::validate`] entry-side).
1962    ///
1963    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
1964    /// `Period` sliding-observation-interval that pairs with the sibling
1965    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
1966    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
1967    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
1968    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
1969    /// default). The typed slot's `Option<Duration>` accept-set —
1970    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
1971    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
1972    /// `Period > 0`; a zero period either trips on the first failure or
1973    /// never trips depending on operator interpretation, neither of which
1974    /// is the author's intent — omit the slot to express "no reset";
1975    /// carry a positive duration to express the sliding window),
1976    /// integer-millisecond canonical form enforced through
1977    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
1978    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
1979    /// future wasm-operator's per-supervisor restart-intensity counter
1980    /// quantizes at milliseconds), upper-bounded by
1981    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
1982    /// supervisor rolling window any operationally-reachable supervisor
1983    /// can honor without spanning multiple scheduler epochs the
1984    /// hierarchical-reconciliation scheduler treats as independent) —
1985    /// maps onto the future wasm-operator (M3) per-supervisor
1986    /// restart-intensity counter's rolling-observation-interval, the
1987    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1988    /// per-`spec.restartWindow` admission webhook, and the sibling
1989    /// `duration_codec`-serialized wire scalar every downstream consumer
1990    /// of the supervisor's per-`:supervisor` restart-intensity denominator
1991    /// keys off.
1992    ///
1993    /// Prior to this lift the `.restart_window` field was accessed inline
1994    /// at one production site in `caixa-core/src/supervisor.rs` — the
1995    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
1996    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
1997    /// open-coded field-access that expressed no compile-time link back to
1998    /// the typed slot. A future extension of the `:restart-window` axis to
1999    /// a richer author surface (a per-cluster restart-window override the
2000    /// operator pins through a future `:supervisor :restart-window-overrides`
2001    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2002    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
2003    /// materializer resolves per-CR, a per-supervisor dynamic
2004    /// restart-window derivation the future adaptive-supervision engine
2005    /// computes from child-failure-history topology, a promotion of the
2006    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
2007    /// pair once Erlang/OTP's per-child-cohort observation-interval-
2008    /// partition slot comes into scope) would have had to be threaded
2009    /// through every open-coded copy in lockstep or the validate gate and
2010    /// the future M4 emit path would silently disagree on which
2011    /// restart-window a given supervisor resolves to — an author's
2012    /// `:restart-window "60s"` would satisfy validate while the emit path
2013    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
2014    /// authored slot at the emit boundary would carry the author's
2015    /// declared window verbatim in `feira lint` output while the future
2016    /// wasm-operator's restart-intensity counter operated under a
2017    /// drifted window, or vice versa: an author's `:restart-window ()`
2018    /// would carry the "never reset" sentinel through validate while the
2019    /// emit path silently substituted a default sliding window), a
2020    /// two-consumer split at the validator far from the source
2021    /// `caixa.lisp` with no field naming the restart-window-drift root
2022    /// cause. Lifting the resolution rule to a typed method on the
2023    /// substrate primitive means every downstream consumer of the
2024    /// Supervisor's per-`:supervisor` restart-intensity-denominator
2025    /// surface reaches for exactly one typed dispatch — the resolver's
2026    /// accept-set migrates as a unit on any future axis addition.
2027    ///
2028    /// Third `Copy`-return accessor on the M2 supervisor-slot
2029    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
2030    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
2031    /// payload rather than a `Copy`-scalar, and the per-`:children`
2032    /// [`crate::ChildSpec::nome`] (57c61d0) /
2033    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2034    /// scalar accessors already close the per-element `String`-carry
2035    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
2036    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
2037    /// per-outermost-call wall-clock-deadline axis and the peer M3
2038    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
2039    /// accessor on the `:politicas` slot's per-call-deadline axis — all
2040    /// three share the shared substrate concept "a `Copy`-projected
2041    /// optional `Duration` that carries a positive integer-millisecond
2042    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
2043    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
2044    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
2045    /// bracket-helper the three axes each route through. Named
2046    /// `restart_window()` to match the storage field's name verbatim and
2047    /// the peer [`crate::LimitsSpec::wall_clock`] /
2048    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
2049    /// accessor's identity maps onto the canonical OTP-shape supervision
2050    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
2051    /// already carries.
2052    #[must_use]
2053    pub const fn restart_window(&self) -> Option<Duration> {
2054        self.restart_window
2055    }
2056
2057    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
2058    /// static-child-list slice accessor every consumer that walks the
2059    /// supervisor's declared child set keys off — returns the author-
2060    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
2061    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
2062    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
2063    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
2064    /// through). Non-optional: an empty slice is the load-bearing
2065    /// "author declared `:children ()`" sentinel every consumer of the
2066    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
2067    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
2068    /// three strategies require a non-empty slice — the paired
2069    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
2070    /// [`SupervisorError::NoChildren`] refusal cascade pins the
2071    /// partition on both arms).
2072    ///
2073    /// The `:supervisor :children` slot carries the OTP-shaped static
2074    /// child list the supervisor materializes one ComputeUnit per
2075    /// entry from — the Erlang/OTP `supervisor:init/1`'s
2076    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
2077    /// through the tatara-lisp `:children` author surface onto a typed
2078    /// `Vec<ChildSpec>` whose per-element `(nome(),
2079    /// versao_requirement(), restart)` triple the per-child
2080    /// [`SupervisorSpec::validate`] loop already gates through the
2081    /// lifted [`ChildSpec::nome`] (57c61d0) /
2082    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
2083    /// Every downstream consumer that fans on the static child list
2084    /// keys off this slice (the [`SupervisorSpec::validate`]
2085    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
2086    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
2087    /// per-child DNS-1123 / semver-requirement / duplicate-detection
2088    /// fan-out loop, every future wasm-operator (M3) per-supervisor
2089    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
2090    /// materialization loop, the future M4
2091    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2092    /// admission-webhook fan-out, the future `feira app graph`
2093    /// per-supervisor tree-print traversal).
2094    ///
2095    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
2096    /// inline at three production sites in `caixa-core/src/supervisor.rs`
2097    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
2098    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
2099    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
2100    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
2101    /// validate loop's `for child in &self.children` traversal head —
2102    /// three open-coded field-accesses that expressed no compile-time
2103    /// link back to the typed slot. A future extension of the
2104    /// `:supervisor :children` axis to a richer author surface (a
2105    /// per-cluster child-set overlay the operator pins through a future
2106    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
2107    /// supervision-canary roadmap acknowledges, a per-tenant
2108    /// child-set-alias table the M4 CR materializer resolves per-CR,
2109    /// a per-supervisor dynamic-child derivation the future adaptive-
2110    /// supervision engine computes from child-failure-history topology,
2111    /// a promotion of the plain `Vec<ChildSpec>` to a richer
2112    /// `{static, dynamic}` partition once Erlang/OTP's
2113    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
2114    /// would have had to be threaded through all three open-coded copies
2115    /// in lockstep or one consumer would silently disagree with the
2116    /// peers on which child-set a given supervisor resolves to — the
2117    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
2118    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
2119    /// would silently split the partition-dispatch's two-arm coherence
2120    /// (a supervisor that satisfies neither arm's precondition, or that
2121    /// satisfies both, at the cost of the paired
2122    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
2123    /// silently drifting from the per-child validate loop's actual
2124    /// traversal input), a three-consumer split at the validator far
2125    /// from the source `caixa.lisp` with no field naming the
2126    /// child-set-drift root cause. Lifting the resolution rule to a
2127    /// typed method on the substrate primitive means every downstream
2128    /// consumer of the Supervisor's per-`:supervisor` static-child-list
2129    /// surface reaches for exactly one typed dispatch — the resolver's
2130    /// accept-set migrates as a unit on any future axis addition.
2131    ///
2132    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
2133    /// — the seed for the same "one typed dispatch on the substrate
2134    /// primitive, thin projections at each consumer" discipline the
2135    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
2136    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
2137    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
2138    /// onto the first `Vec`-carry axis on the substrate. The four peer
2139    /// `Vec`-carry axes still unlifted at the time of this seed —
2140    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
2141    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
2142    /// (`Vec<Membro>` per-Aplicacao member list),
2143    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
2144    /// per-Aplicacao WIT-typed edge list),
2145    /// [`crate::UpgradeFromEntry::instructions`]
2146    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
2147    /// — inherit this accessor's discipline as future compounding runs
2148    /// migrate their consumers onto the shared slice-return shape.
2149    /// Fourth (and final) accessor on the M2 supervisor-slot
2150    /// `SupervisorSpec` type, sibling to the three `Copy`-return
2151    /// [`SupervisorSpec::estrategia`] (eafb619) /
2152    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
2153    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
2154    /// the last unlifted per-`:supervisor` field axis (the
2155    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
2156    /// per-`:supervisor` reader now routes through a typed dispatch on
2157    /// the substrate primitive. Named `children()` to match the storage
2158    /// field's name verbatim and the tatara-lisp author-surface term
2159    /// (`:children`) the field's own docstring already carries; the
2160    /// accessor's identity maps onto the canonical OTP-shape
2161    /// supervision vocabulary the [`SupervisorSpec::children`] field's
2162    /// docstring already reaches for ("Static children ..."). Returns
2163    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
2164    /// consumer of the child list treats it as a read-only sequence —
2165    /// the slice-view is the narrowest borrow that supports every
2166    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
2167    /// index, `.len()`) without leaking the backing `Vec`'s
2168    /// grow/push/reserve surface that no consumer of the typed view
2169    /// reaches for (the storage-side `Vec` remains reachable through
2170    /// the `pub children` field for the mutation-carrying
2171    /// `Caixa::supervisor_view` fold-in path in
2172    /// `manifest.rs:supervisor_view`).
2173    #[must_use]
2174    pub const fn children(&self) -> &[ChildSpec] {
2175        self.children.as_slice()
2176    }
2177
2178    /// Validate the supervisor's typed shape — strategy ↔ children
2179    /// invariants, max_restarts > 0, restart_window > 0 when set,
2180    /// per-child non-empty + duplicate-free names.
2181    ///
2182    /// Mirrors the value-shape discipline applied to every other
2183    /// typed slot:
2184    ///
2185    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
2186    ///     same "0 means the opposite of what you think" footgun
2187    ///     closed for `:politicas :timeout` (Envoy interprets a zero
2188    ///     timeout as `infinite`), `:politicas :circuit-breaker
2189    ///     :window`, and `:limits :wall-clock`. The
2190    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
2191    ///     `supervisor` requires `Period > 0`; a zero period either
2192    ///     trips on the first failure or never trips depending on
2193    ///     operator interpretation, neither of which is the
2194    ///     author's intent. Omit `:restart-window` to express "no
2195    ///     reset"; carry a positive duration to express the window.
2196    ///   - duplicate `:children` `:caixa` names are the same
2197    ///     graph-node-set / multiset distinction closed for
2198    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
2199    ///     and `:entrada :paths` (eb3456d). Two children with the
2200    ///     same `:caixa` materialize as two ComputeUnits with the
2201    ///     same name in the cluster's HelmRelease values, one
2202    ///     silently overwriting the other. Erlang/OTP's
2203    ///     `child_spec.id` is required-unique per supervisor;
2204    ///     pleme-io enforces the same set-not-multiset shape on
2205    ///     `:caixa` (the load-bearing identity in our renderer).
2206    pub fn validate(&self) -> Result<(), SupervisorError> {
2207        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
2208        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2209        // error carrier's `estrategia:` field through the lifted
2210        // [`SupervisorSpec::estrategia`] accessor rather than the raw
2211        // `self.estrategia` field access — the two production consumers
2212        // of the per-`:supervisor` sibling-restart-strategy scalar now
2213        // key off exactly one typed dispatch on the substrate primitive,
2214        // so any future rebrand on the axis (a per-cluster strategy
2215        // override the operator pins through a future `:supervisor
2216        // :estrategia-overrides` slot, a per-tenant strategy-alias table
2217        // the M4 CR materializer resolves per-CR) migrates as a single
2218        // caixa-core edit rather than a coordinated rewrite of the two
2219        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
2220        // (921fe1b) four-consumer migration on the per-`:placement`
2221        // distribution-strategy axis.
2222        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
2223        // dispatch's paired `.is_empty()` cross-slot refusal probes
2224        // (the `SimpleOneForOne`-arm
2225        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
2226        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2227        // refusal) through the lifted [`SupervisorSpec::children`]
2228        // slice-return accessor rather than the raw `self.children`
2229        // field access — the two paired production consumers of the
2230        // per-`:supervisor` static-child-list scalar-shape now key off
2231        // exactly one typed dispatch on the substrate primitive, so any
2232        // future rebrand on the axis (a per-cluster child-set overlay
2233        // the operator pins through a future `:supervisor
2234        // :children-overrides` slot, a per-tenant child-set-alias table
2235        // the M4 CR materializer resolves per-CR) migrates as a single
2236        // caixa-core edit rather than a coordinated rewrite of the
2237        // paired arms — first slice-return migration on any typed slot,
2238        // seed for the peer per-`:placement :clusters`,
2239        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
2240        // :instructions` `Vec`-carry axes.
2241        match self.estrategia() {
2242            RestartStrategy::SimpleOneForOne => {
2243                // SimpleOneForOne: children added at runtime. Static
2244                // list must be empty (one shape declared elsewhere).
2245                if !self.children().is_empty() {
2246                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
2247                }
2248            }
2249            _ => {
2250                if self.children().is_empty() {
2251                    return Err(SupervisorError::no_children(self.estrategia()));
2252                }
2253            }
2254        }
2255        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
2256        // axis. See [`crate::render::require_positive_bounded_u32`] for
2257        // the ordering discipline (zero-floor arm strictly precedes cap
2258        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
2259        // diagnostic with its counter-axis remediation directly named,
2260        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
2261        // cap-arm miss). Until this bracket landed the top edge ran all
2262        // the way to `u32::MAX` and a struct-literal
2263        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
2264        // equivalent author-surface `:max-restarts 100000` /
2265        // `:max-restarts 4294967295` typo landing in the slot) silently
2266        // passed validate. The runtime substrate consuming the value
2267        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
2268        // wasm-operator's per-supervisor restart-intensity counter, the
2269        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2270        // admission webhook) then turned a typed `:max-restarts`
2271        // policy into a no-op supervisor: the escalation threshold is
2272        // structurally so high that no realistic
2273        // restarts-per-`:restart-window` traffic shape can reach it,
2274        // the supervisor never escalates to its parent, and a bad
2275        // child can loop inside the window indefinitely with the
2276        // parent supervisor structurally never receiving the "this
2277        // subtree has exceeded its restart budget" signal the typed
2278        // slot is meant to express. The bracket set is
2279        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
2280        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
2281        // the sibling `:politicas :circuit-breaker :max-failures` axis:
2282        // both are "trip the next-higher protection layer after N
2283        // events in a rolling window" counters with identical
2284        // degenerate-at-the-high-end shape and now share one canonical
2285        // bracket helper. The bracket precedes the sibling
2286        // `:restart-window` zero-floor / canonical-millisecond arms so
2287        // an over-cap `max_restarts` paired with a structurally invalid
2288        // window surfaces the bracket diagnostic first, mirroring the
2289        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
2290        // ordering on the peer `:politicas :circuit-breaker` slot.
2291        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
2292        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
2293        // accessor rather than the raw `self.max_restarts` field access —
2294        // the one production consumer of the per-`:supervisor`
2295        // restart-budget-count scalar now keys off exactly one typed
2296        // dispatch on the substrate primitive, so any future rebrand on
2297        // the axis (a per-cluster restart-budget override the operator
2298        // pins through a future `:supervisor :max-restarts-overrides`
2299        // slot, a per-tenant restart-budget-alias table the M4 CR
2300        // materializer resolves per-CR) migrates as a single caixa-core
2301        // edit rather than a coordinated rewrite — sibling of the peer M3
2302        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
2303        // the per-`:politicas :circuit-breaker :max-failures` axis.
2304        crate::render::require_positive_bounded_u32(
2305            self.max_restarts(),
2306            SUPERVISOR_MAX_RESTARTS_MAX,
2307            || SupervisorError::ZeroMaxRestarts,
2308            SupervisorError::max_restarts_exceeds_cap,
2309        )?;
2310        // Route the [`SupervisorSpec::validate`] `:restart-window`
2311        // zero-floor + integer-millisecond canonical-form + upper-cap
2312        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
2313        // accessor rather than the raw `self.restart_window` field access —
2314        // the one production consumer of the per-`:supervisor`
2315        // restart-intensity-denominator scalar now keys off exactly one
2316        // typed dispatch on the substrate primitive, so any future rebrand
2317        // on the axis (a per-cluster restart-window override the operator
2318        // pins through a future `:supervisor :restart-window-overrides`
2319        // slot, a per-tenant restart-window-alias table the M4 CR
2320        // materializer resolves per-CR) migrates as a single caixa-core
2321        // edit rather than a coordinated rewrite — sibling of the peer M2
2322        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
2323        // on the per-`:limits :wall-clock` axis and the peer M3
2324        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
2325        // per-`:politicas :timeout` axis.
2326        if let Some(w) = self.restart_window() {
2327            // Zero-floor + integer-millisecond canonical-form +
2328            // upper-cap bracket on the typed `:restart-window` axis.
2329            // See
2330            // [`crate::render::require_positive_canonical_bounded_duration`]
2331            // for the full three-arm ordering discipline (zero-floor
2332            // strictly precedes canonical-form so `Duration::ZERO`
2333            // surfaces the self-locating `RestartWindowZero`
2334            // diagnostic; canonical-form strictly precedes the cap arm
2335            // so a sub-millisecond above-cap value surfaces the more
2336            // fundamental round-trip-shape diagnostic first) and the
2337            // three peer typed-`Duration` sites that share this
2338            // canonical bracket ([`crate::MeshPolicy::timeout`],
2339            // [`crate::CircuitBreaker::window`],
2340            // [`crate::LimitsSpec::wall_clock`]). Every validated
2341            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2342            // (1ms..=1h), integer-millisecond granularity.
2343            crate::render::require_positive_canonical_bounded_duration(
2344                w,
2345                SUPERVISOR_RESTART_WINDOW_MAX,
2346                || SupervisorError::RestartWindowZero,
2347                SupervisorError::restart_window_not_canonical,
2348                SupervisorError::restart_window_exceeds_cap,
2349            )?;
2350        }
2351        // Route the per-child DNS-1123 / semver-requirement / duplicate-
2352        // detection fan-out loop through the lifted named per-slot gate
2353        // [`SupervisorSpec::validate_children`] rather than an inline
2354        // three-per-child cascade — every future consumer that wants to
2355        // re-check only the `:children` slot's per-entry axes (the M4
2356        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2357        // admission webhook re-validating one added/renamed child, the
2358        // future wasm-operator's per-child dynamic-add re-validator on
2359        // the `SimpleOneForOne` runtime-add path once dynamic-children
2360        // graduate to a typed slot, a future partial re-validator on a
2361        // per-`:children`-entry patch) reaches every per-entry axis
2362        // through one dispatch rather than re-inlining the three-arm
2363        // cascade in lockstep with `validate` or paying the peer
2364        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
2365        // reach one entry check. Sibling of the peer M3 mesh-slot
2366        // per-slot gate family (`validate_membros` — the exact peer on
2367        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
2368        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
2369        // `validate_placement`; `validate_politicas` routing through
2370        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
2371        // per-slot gate discipline now spans both the M3 mesh-slot
2372        // family and the M2 `:children` per-child-cascade axis on one
2373        // shape: one named per-slot gate per typed per-entry loop.
2374        self.validate_children()?;
2375        Ok(())
2376    }
2377
2378    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
2379    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
2380    /// gate, and duplicate-`:caixa` dedup arm into one call every
2381    /// consumer that wants to re-validate one `:children` entry (or the
2382    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
2383    /// admits reaches through.
2384    ///
2385    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
2386    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
2387    /// three-per-entry shape (DNS-1123 name + semver-requirement +
2388    /// duplicate-`:caixa` dedup), lifted to one named substrate
2389    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2390    /// materializer's admission webhook re-checking one added or renamed
2391    /// child, the future wasm-operator's per-child dynamic-add
2392    /// re-validator on the `SimpleOneForOne` runtime-add path once
2393    /// dynamic-children graduate to a typed slot, a future partial
2394    /// re-validator on a per-`:children`-entry patch — each reaches the
2395    /// three per-entry axes through this one dispatch rather than
2396    /// re-inlining the three-arm cascade in lockstep with `validate`
2397    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
2398    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
2399    /// reach one entry check.
2400    ///
2401    /// Self-contained on `&self` — resolves its own dedup `HashSet`
2402    /// through [`SupervisorSpec::children`] rather than borrowing one
2403    /// threaded down from `validate`, the same posture the peer M3
2404    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
2405    /// [`crate::AplicacaoSpec::validate_contratos`],
2406    /// [`crate::AplicacaoSpec::validate_entrada`],
2407    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
2408    /// consumer that reaches this gate directly (without first calling
2409    /// `validate`) still runs the full per-child cascade — pinned by
2410    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2411    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2412    /// + `validate_children_is_self_contained_on_children_slot`.
2413    ///
2414    /// The three per-entry arms run in the same canonical order the
2415    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
2416    /// the diagnostic every author-declared per-`:children` entry surfaces
2417    /// through `validate` is byte-equal to the diagnostic this gate
2418    /// surfaces when called directly — the equivalence-pin pair
2419    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2420    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2421    /// asserts the two altitudes discriminate the same set on every
2422    /// per-entry-covered input.
2423    pub fn validate_children(&self) -> Result<(), SupervisorError> {
2424        let mut seen = std::collections::HashSet::new();
2425        for child in self.children() {
2426            // Every emitted cluster artifact's `metadata.name` for a
2427            // supervised child derives from this `:children :caixa` value
2428            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
2429            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
2430            // label value on every child's pod identity, and the per-
2431            // child K8s [`Service`][svc] `metadata.name` the future
2432            // wasm-operator (M3) provisions for inter-child supervision
2433            // tree wiring. Each apiserver-side schema on each landing
2434            // site enforces the DNS-1123 label rule on admission; a
2435            // structurally invalid child name (`"Worker"`, `"my_worker"`,
2436            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
2437            // UUID-shaped mistaken-identity slug) silently passes the
2438            // prior empty-/duplicate-only gate and the failure surfaces
2439            // at `kubectl apply` time as a `metadata.name: Invalid value`
2440            // rejection, far from the source caixa.lisp, with no field
2441            // naming the offending `:children` entry. Lifting the gate
2442            // to caixa-build time mirrors the `:membros :caixa` value-
2443            // shape trajectory (3f9d7a0) and the `:placement :clusters`
2444            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
2445            // identifier axis — the supervisor tree's child names —
2446            // through the lifted
2447            // [`crate::render::require_valid_dns_1123_label`] gate the
2448            // seven peer name axes (`:membros :caixa`, `:placement
2449            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
2450            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
2451            // route through, so drift between the eight axes' accepted
2452            // DNS-1123-label sets is structurally impossible.
2453            //
2454            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
2455            crate::render::require_valid_dns_1123_label(
2456                child.nome(),
2457                || SupervisorError::EmptyChildName,
2458                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
2459            )?;
2460            // The author surface for `:children :versao` is the same
2461            // Cargo-shaped semver requirement string `:deps :versao` and
2462            // `:membros :versao` carry — and the lacre pipeline resolves
2463            // all three axes through the same
2464            // [`crate::version::parse_requirement`] entry-point. The
2465            // shared [`crate::render::require_valid_versao_requirement`]
2466            // helper brackets the empty-first + parse cascade both peer
2467            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
2468            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
2469            // :versao`) route through, so drift between the three axes'
2470            // accepted requirement sets is structurally impossible and
2471            // the parse-side no-op the empty-first arm closes (semver's
2472            // empty parse yields an implicit `*`) lives in exactly one
2473            // predicate. Every `ChildSpec::versao` past validate is
2474            // round-trippable through [`crate::parse_requirement`]
2475            // without re-checking at the resolver layer, and the three
2476            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
2477            // are now structurally equivalent by construction.
2478            crate::render::require_valid_versao_requirement(
2479                child.versao_requirement(),
2480                || SupervisorError::empty_child_version(child.nome()),
2481                |reason| {
2482                    SupervisorError::child_versao_invalid(
2483                        child.nome(),
2484                        child.versao_requirement(),
2485                        reason,
2486                    )
2487                },
2488            )?;
2489            crate::render::insert_first_seen(&mut seen, child.nome(), || {
2490                SupervisorError::duplicate_child_caixa(child.nome())
2491            })?;
2492        }
2493        Ok(())
2494    }
2495}
2496
2497/// Cross-slot coherence gate on the supervision tree: no
2498/// `:children :caixa` entry may name the supervisor's own `:nome`.
2499///
2500/// A supervisor that lists itself as a child is a degenerate self-parent
2501/// — the supervision tree is a DAG rooted at the supervisor (OTP child
2502/// specs reference *distinct* child processes; a supervisor is never its
2503/// own child), and the wasm-operator's hierarchical reconciliation would
2504/// otherwise be handed a node that is its own parent: a one-node cycle it
2505/// either rejects far from the source `caixa.lisp` or recurses on. Because
2506/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
2507/// lacre closure root), a child whose `:caixa` equals the supervisor's
2508/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
2509///
2510/// Lives outside [`SupervisorSpec::validate`] because the typed view
2511/// carries the children but not the parent `:nome`; mirrors the
2512/// cross-slot precedence gate `validate_upgrade_from_against_versao`
2513/// (which likewise reads one slot against another at the
2514/// [`crate::layout`] wire-up site) and the mesh self-edge gate
2515/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
2516/// node to itself is structurally not a tree/mesh edge" discipline, here
2517/// on the supervision-tree axis.
2518pub fn validate_no_self_supervision(
2519    children: &[ChildSpec],
2520    parent_nome: &str,
2521) -> Result<(), SupervisorError> {
2522    for child in children {
2523        if child.nome() == parent_nome {
2524            return Err(SupervisorError::child_supervises_self(parent_nome));
2525        }
2526    }
2527    Ok(())
2528}
2529
2530#[derive(Debug, Error, PartialEq, Eq)]
2531pub enum SupervisorError {
2532    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
2533    NoChildren { estrategia: RestartStrategy },
2534    #[error(
2535        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
2536    )]
2537    SimpleOneForOneWithStaticChildren,
2538    #[error(":max-restarts must be > 0")]
2539    ZeroMaxRestarts,
2540    #[error(
2541        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
2542         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
2543         restart-intensity policy into a no-op supervisor: the escalation threshold is \
2544         structurally so high that no realistic restarts-per-:restart-window traffic shape \
2545         can reach it, so the supervisor never escalates to its parent and a bad child can \
2546         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
2547         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
2548         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2549         materializer's admission webhook) emits a `:max-restarts` declaration that is \
2550         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
2551         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
2552         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
2553         band) or restructure the supervision tree (split the flaky child into its own \
2554         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
2555    )]
2556    MaxRestartsExceedsCap { max_restarts: u32 },
2557    #[error(
2558        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
2559         requires Period > 0; a zero window either trips on the first failure or \
2560         never trips depending on operator interpretation. Omit :restart-window to \
2561         express `never reset`; carry a positive duration to express the window."
2562    )]
2563    RestartWindowZero,
2564    #[error(
2565        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
2566         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
2567         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
2568         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
2569         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
2570    )]
2571    RestartWindowNotCanonical { window: Duration },
2572    #[error(
2573        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
2574         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
2575         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
2576         failure-counting window is structurally so long that transient restarts are never \
2577         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
2578         when the child has exceeded its restart budget within the recent window` to `trip the \
2579         parent when the child has exceeded its restart budget over its lifetime`, and the \
2580         supervisor's reset semantic never reaches the child — every typed-slot consumer \
2581         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
2582         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2583         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
2584         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
2585         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
2586         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
2587         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
2588         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
2589         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
2590         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
2591         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
2592         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
2593         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
2594         hiding it behind a rolling-window declaration the cap arm rejects)"
2595    )]
2596    RestartWindowExceedsCap { window: Duration },
2597    #[error("child entry has empty :caixa name")]
2598    EmptyChildName,
2599    #[error(
2600        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
2601         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
2602         name / label value the child name lands in — the per-child \
2603         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
2604         label value, and the future wasm-operator per-child Service `metadata.name` \
2605         — each apiserver-side schema rejects names that don't match; use a \
2606         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
2607    )]
2608    ChildCaixaInvalid { caixa: String, reason: String },
2609    #[error("child {caixa:?} has empty :versao constraint")]
2610    EmptyChildVersion { caixa: String },
2611    #[error(
2612        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
2613         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
2614         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
2615         `:membros :versao` carry; the lacre pipeline resolves all three \
2616         through the same parser)"
2617    )]
2618    ChildVersaoInvalid {
2619        caixa: String,
2620        versao: String,
2621        reason: String,
2622    },
2623    #[error(
2624        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
2625         child_spec.id per supervisor; duplicate children materialize as duplicate \
2626         ComputeUnits in the rendered chart, one silently overwriting the other)"
2627    )]
2628    DuplicateChildCaixa { caixa: String },
2629    #[error(
2630        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
2631         never its own child (the supervision tree is a DAG rooted at the supervisor; \
2632         OTP child specs reference distinct child processes). Since every :nome is a \
2633         globally-unique substrate identity, a child naming the supervisor's own :nome \
2634         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
2635         self-referential :children entry or rename it to the actual child caixa."
2636    )]
2637    ChildSupervisesSelf { caixa: String },
2638}
2639
2640// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
2641// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
2642// and [`validate_no_self_supervision`] onto one substrate primitive per
2643// typed variant — the sibling on `SupervisorError` of the four uniform-shape
2644// `LayoutError`-envelope constructor families the peer
2645// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
2646// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
2647// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
2648// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
2649// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
2650// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
2651// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
2652// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
2653// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
2654// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
2655// variants on `{ de, para }`) already at that discipline on the peer
2656// `AplicacaoError` envelopes.
2657//
2658// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
2659// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
2660// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
2661// self-supervision arm) opened the identical
2662// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
2663// the exact "same block re-inlined at every consumer" shape the PRIME
2664// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
2665// `AplicacaoError` families each closed on their sibling envelopes. The
2666// three variants share one `{ caixa: String }` shape, so the fold routes
2667// each wire-up site through one dispatch per typed variant.
2668//
2669// The macro below generates one static constructor per variant of shape
2670// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
2671// collapses onto one dispatch:
2672// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
2673// struct-literal on the same `&str` fixture. The uniform one-field
2674// construction (`caixa: caixa.to_string()`) is spelled once — inside the
2675// macro — rather than at every wire-up site. Every constructor is
2676// `#[must_use]` so a caller who mistakenly discards the constructed error
2677// trips a compile warning at the wire-up site.
2678//
2679// Every future consumer that wants to construct one of these three
2680// variants outside `SupervisorSpec::validate_children` /
2681// `validate_no_self_supervision` — a deferred
2682// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2683// webhook re-checking one added/renamed child, a future
2684// `feira validate --supervisor` per-caixa admission verb, a per-child
2685// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
2686// once dynamic-children graduate to a typed slot, a per-Supervisor
2687// overlay resolver rejecting a duplicate/self-supervising child against
2688// a cluster-local snapshot — now reaches each variant through one call
2689// rather than re-inlining the three-line struct-literal in lockstep
2690// with the three in-crate wire-up sites.
2691macro_rules! supervisor_caixa_only_ctors {
2692    ($($ctor:ident => $variant:ident),* $(,)?) => {
2693        impl SupervisorError {
2694            $(
2695                #[doc = concat!(
2696                    "Construct a [`SupervisorError::",
2697                    stringify!($variant),
2698                    "`] naming the offending `:children :caixa` (or ",
2699                    "supervisor `:nome`, on the self-supervision arm). ",
2700                    "Folds the uniform `Self::",
2701                    stringify!($variant),
2702                    " { caixa: caixa.to_string() }` one-field ",
2703                    "struct-literal onto one substrate primitive so ",
2704                    "every [`SupervisorSpec::validate_children`] / ",
2705                    "[`validate_no_self_supervision`] wire-up on this ",
2706                    "variant reads through one dispatch rather than the ",
2707                    "pre-lift open-coded struct-literal block."
2708                )]
2709                #[must_use]
2710                pub fn $ctor(caixa: &str) -> Self {
2711                    Self::$variant { caixa: caixa.to_string() }
2712                }
2713            )*
2714        }
2715    };
2716}
2717
2718supervisor_caixa_only_ctors! {
2719    empty_child_version => EmptyChildVersion,
2720    duplicate_child_caixa => DuplicateChildCaixa,
2721    child_supervises_self => ChildSupervisesSelf,
2722}
2723
2724// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
2725// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
2726// one substrate primitive per typed variant — the M2 supervisor-side siblings
2727// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
2728// already lifted through the sibling
2729// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
2730// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
2731// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
2732// String }` two-slot shape the peer seven-variant
2733// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
2734// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
2735// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
2736// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
2737// variant carries the `{ caixa: String, versao: String, reason: String }`
2738// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
2739// carries on the same `:versao` value-shape.
2740//
2741// Each of the two wire-up sites opened the same closure-shaped
2742// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
2743// [versao: child.versao_requirement().to_string(),] reason }` block inside
2744// the paired [`crate::render::require_valid_dns_1123_label`] and
2745// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
2746// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
2747// as a bug, on the same altitude the peer `AplicacaoError` /
2748// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
2749// families already closed on their sibling envelopes.
2750//
2751// The two `#[must_use]` inherent constructors below fold each wire-up onto
2752// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
2753// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
2754// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
2755// The uniform per-field `.to_string()` / `.into()` construction is spelled
2756// once — inside each ctor body — rather than at every wire-up site. The
2757// `reason: impl Into<String>` bound accepts both `&str` literals and
2758// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
2759// diagnostic shape at the lift, matching the peer
2760// [`aplicacao_field_reason_ctors!`] and
2761// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
2762// sibling envelopes.
2763//
2764// Every future consumer that wants to construct one of these two variants
2765// outside `SupervisorSpec::validate_children` — a deferred
2766// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
2767// re-checking one added/renamed child's `:caixa` or `:versao`, a future
2768// `feira validate --supervisor` per-caixa admission verb, a per-child
2769// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
2770// dynamic-children graduate to a typed slot, a per-Supervisor overlay
2771// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
2772// cluster-local snapshot — now reaches each variant through one call rather
2773// than re-inlining the per-shape struct-literal block in lockstep with the
2774// two in-crate wire-up sites.
2775impl SupervisorError {
2776    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
2777    /// offending `:children :caixa` value under the given `reason`. Folds
2778    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
2779    /// reason: reason.into() }` two-slot struct-literal onto one substrate
2780    /// primitive so every wire-up on this variant reads through one
2781    /// dispatch, matching the peer
2782    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
2783    /// sibling `AplicacaoError { caixa: String, reason: String }`
2784    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
2785    /// outputs through the `impl Into<String>` bound.
2786    #[must_use]
2787    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
2788        Self::ChildCaixaInvalid {
2789            caixa: caixa.to_string(),
2790            reason: reason.into(),
2791        }
2792    }
2793
2794    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
2795    /// offending `:children :caixa` and its `:versao` requirement under
2796    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
2797    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
2798    /// reason.into() }` three-slot struct-literal onto one substrate
2799    /// primitive so every wire-up on this variant reads through one
2800    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
2801    /// { caixa, versao, reason }` three-slot axis on the peer
2802    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
2803    /// and `format!(…)` outputs through the `impl Into<String>` bound.
2804    #[must_use]
2805    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
2806        Self::ChildVersaoInvalid {
2807            caixa: caixa.to_string(),
2808            versao: versao.to_string(),
2809            reason: reason.into(),
2810        }
2811    }
2812}
2813
2814// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
2815// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
2816// three bracket-arms — one struct-literal at the `:children`-empty
2817// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
2818// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
2819// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
2820// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
2821// [`crate::render::require_positive_canonical_bounded_duration`]
2822// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
2823// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
2824// primitive per typed variant, matching the sibling
2825// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
2826// variants on the same `{ <field>: Duration | u32 }` shape) at that
2827// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
2828// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
2829// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
2830// wire-up site through one dispatch per typed variant without a runtime-
2831// work delta.
2832//
2833// Each of the four wire-up sites opened the identical
2834// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
2835// exact "same block re-inlined at every consumer" shape the PRIME
2836// DIRECTIVE names as a bug, on the same altitude the peer
2837// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
2838// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
2839// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
2840// the fold routes each wire-up site through one dispatch per typed
2841// variant.
2842//
2843// The macro below generates one static constructor per variant of shape
2844// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
2845// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
2846// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
2847// fixture — as a direct call at the [`SupervisorSpec::validate`]
2848// `:children`-empty refusal, or as a bare function pointer in the
2849// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
2850// [`crate::render::require_positive_bounded_u32`] /
2851// [`crate::render::require_positive_canonical_bounded_duration`] gate
2852// carries — rather than the pre-lift open-coded one-line closure over
2853// the same one-field struct-literal. `const fn` preserves the `Copy`-
2854// pass-through's zero-runtime-work property verbatim. Every constructor
2855// is `#[must_use]` so a caller who mistakenly discards the constructed
2856// error trips a compile warning at the wire-up site.
2857//
2858// Every future consumer that wants to construct one of these four
2859// variants outside `SupervisorSpec::validate` — a deferred
2860// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2861// webhook re-checking one edited `:estrategia` / `:max-restarts` /
2862// `:restart-window` slot against the cap + canonical-form cascade, a
2863// future `feira validate --supervisor` per-caixa admission verb re-
2864// running the shape gates on demand, a per-Supervisor overlay resolver
2865// rejecting an author-supplied slot against a cluster-local snapshot —
2866// now reaches each variant through one call rather than re-inlining the
2867// per-shape struct-literal block in lockstep with the four in-crate
2868// wire-up sites.
2869macro_rules! supervisor_scalar_ctors {
2870    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
2871        impl SupervisorError {
2872            $(
2873                #[doc = concat!(
2874                    "Construct a [`SupervisorError::",
2875                    stringify!($variant),
2876                    "`] naming the offending per-`:supervisor` `",
2877                    stringify!($field),
2878                    "` scalar. Folds the uniform `Self::",
2879                    stringify!($variant),
2880                    " { ",
2881                    stringify!($field),
2882                    " }` one-field `Copy`-pass-through struct-literal onto ",
2883                    "one substrate primitive so every per-axis wire-up on ",
2884                    "this variant reads through one dispatch — as a direct ",
2885                    "call (`SupervisorError::",
2886                    stringify!($ctor),
2887                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
2888                    "the same `Copy`-`",
2889                    stringify!($ty),
2890                    "` fixture) or as a bare function pointer in the ",
2891                    "`impl FnOnce(",
2892                    stringify!($ty),
2893                    ") -> SupervisorError` bracket-closure slot every ",
2894                    "`crate::render::require_positive_bounded_*` / ",
2895                    "`crate::render::require_positive_canonical_bounded_*` ",
2896                    "gate carries — rather than the pre-lift open-coded ",
2897                    "one-line closure over the same one-field struct-",
2898                    "literal. `const fn` preserves the `Copy`-pass-through's ",
2899                    "zero-runtime-work property verbatim."
2900                )]
2901                #[must_use]
2902                pub const fn $ctor($field: $ty) -> Self {
2903                    Self::$variant { $field }
2904                }
2905            )*
2906        }
2907    };
2908}
2909
2910supervisor_scalar_ctors! {
2911    no_children => NoChildren { estrategia: RestartStrategy },
2912    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
2913    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
2914    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
2915}
2916
2917/// Shared duration string codec for the typed slots that take a
2918/// duration (`restart_window`, `MeshPolicy::timeout`,
2919/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
2920/// reuse it without duplicating the parser.
2921pub mod duration_codec {
2922    use super::Duration;
2923    use serde::{Deserializer, Serializer};
2924
2925    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
2926        // Route through the canonical [`crate::render::serialize_option_via_str`]
2927        // — the substrate-side single-owner primitive for the forward
2928        // arm of the typed-magnitude codec family. See its docstring
2929        // for the full sibling roster.
2930        crate::render::serialize_option_via_str(v, s, render)
2931    }
2932
2933    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
2934        // Route through the canonical [`crate::render::deserialize_option_via_str`]
2935        // — the substrate-side single-owner primitive for the reverse
2936        // arm of the typed-magnitude codec family. See its docstring
2937        // for the full sibling roster.
2938        crate::render::deserialize_option_via_str(d, parse)
2939    }
2940
2941    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
2942        // Paired whitespace-rejection arm — same canonical-form
2943        // render-determinism discipline as the peer
2944        // `limits::parse_byte_size` / `limits::parse_duration` /
2945        // `limits::parse_millicores` /
2946        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
2947        // byte-scan closes the WhatWG-conformant whitespace bytes
2948        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
2949        // `char::is_whitespace` scan closes the strictly-complementary
2950        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
2951        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
2952        // codepoints) that `str::trim` at parse entry silently strips.
2953        // Either drift class would round-trip through `render` to a
2954        // *different* canonical form on next emit — breaking the
2955        // THEORY.md Part V render-determinism contract on three typed-
2956        // duration slots at once (`:supervisor :restart-window`,
2957        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
2958        // via the shared codec.
2959        //
2960        // Routed through the lifted [`crate::render::reject_whitespace`]
2961        // primitive — the substrate-side single-owner paired-arm gate
2962        // every typed-magnitude codec in caixa-core shares.
2963        crate::render::reject_whitespace::<String, _, _>(
2964            s,
2965            |b| {
2966                format!(
2967                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
2968                 authoring form for the typed duration slots routed through this shared codec \
2969                 (`:supervisor :restart-window`, `:politicas :timeout`, \
2970                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
2971                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
2972                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
2973                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
2974                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
2975                 Part V render-determinism contract every typed slot carries. Strip every \
2976                 whitespace byte (write `\"30s\"` verbatim)"
2977                )
2978            },
2979            |ch| {
2980                format!(
2981                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
2982                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
2983                 duration slots routed through this shared codec (`:supervisor \
2984                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
2985                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
2986                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
2987                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
2988                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
2989                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
2990                 `White_Space` property, strictly wider than the ASCII byte set) silently \
2991                 strips it at parse entry, and the value round-trips through `render` to \
2992                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
2993                 the THEORY.md Part V render-determinism contract every typed slot \
2994                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
2995                 verbatim with only ASCII bytes)",
2996                    cp = ch as u32
2997                )
2998            },
2999        )?;
3000        let s = s.trim();
3001        // Routed through the lifted
3002        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
3003        // the single-owner split every ASCII-alphabetic-unit typed-
3004        // magnitude codec in caixa-core (`limits::parse_byte_size` /
3005        // `limits::parse_duration` / this shared duration codec) shares.
3006        // See its docstring for the full sibling roster on the same
3007        // primitive altitude.
3008        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
3009        let num_trim = num_part.trim();
3010        // The canonical authoring form for every typed slot routed
3011        // through this shared codec — `:supervisor :restart-window`,
3012        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
3013        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
3014        // non-negative integer with no decimal point and no leading
3015        // sign, so the parser's accepted set must match for
3016        // serialize/deserialize to round-trip without canonical-form
3017        // drift. Until this gate landed the parser accepted any
3018        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
3019        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
3020        // tripped the value to a *different* canonical string on the
3021        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
3022        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
3023        // — breaking the THEORY.md Part V render-determinism contract
3024        // on three typed slots at once. Same canonical-form discipline
3025        // `crate::limits::parse_duration` (818dd38, the immediate
3026        // predecessor on the peer `:limits :wall-clock` codec) applies;
3027        // this gate lifts the discipline onto the shared codec that
3028        // backs the remaining three typed-duration slots in caixa-core.
3029        //
3030        // Strict canonical form: every byte of the magnitude is an
3031        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
3032        // inputs the gate distinguishes "non-canonical-but-numeric"
3033        // (parses as f64 or i64 — surfaced with a self-locating
3034        // diagnostic naming the canonical authoring form, the
3035        // round-trip drift each rejected shape would produce on first
3036        // serialize, and the canonical-form remediation) from
3037        // "garbage" (parses as neither — surfaced with the existing
3038        // narrower "bad duration magnitude" wording so its diagnostic
3039        // shape remains stable for the parser-shape footgun case).
3040        // The pre-existing `num < 0.0` arm is now unreachable — the
3041        // digit-only gate strictly precedes magnitude parsing, and a
3042        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
3043        // non-canonical-but-numeric branch with the `-30` named
3044        // verbatim in the diagnostic rather than the prior
3045        // value-laundered "negative duration in \"-30s\"" wording.
3046        //
3047        // Routed through the lifted
3048        // [`crate::render::is_digit_only_magnitude`] predicate — the
3049        // same source of truth the four peer typed-magnitude codec
3050        // sites share.
3051        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
3052        if !digit_only {
3053            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
3054            if numeric {
3055                return Err(format!(
3056                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
3057                     canonical authoring form for the typed duration slots routed through \
3058                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3059                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3060                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
3061                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
3062                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
3063                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
3064                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
3065                     THEORY.md Part V render-determinism contract every typed slot carries. \
3066                     Pick an integer magnitude in the unit that divides cleanly (write \
3067                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
3068                ));
3069            }
3070            return Err(format!("bad duration magnitude in {s:?}"));
3071        }
3072        // Leading-zero arm — peer with the `rate_limit_codec` leading-
3073        // zero arm (4f46830) on the same canonical-form render-
3074        // determinism axis. The digit-only gate accepts `"030s"`,
3075        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
3076        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
3077        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
3078        // *different* canonical string on the next emit, breaking the
3079        // THEORY.md Part V render-determinism contract the same way
3080        // `"+30s"` did before the leading-`+` arm landed. The single-
3081        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
3082        // losslessly through `render` (`render(Duration::ZERO)` emits
3083        // `"0s"`) — the downstream semantic-zero gates (e.g.
3084        // `SupervisorError::ZeroRestartWindow` on
3085        // `:supervisor :restart-window`,
3086        // `AplicacaoError::PolicyTimeoutZero` /
3087        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
3088        // duration slots) refuse zero-magnitude authoring at the typed-
3089        // validate layer above, so the single-byte `"0"` stays in the
3090        // accepted set at this codec layer and the diagnostic
3091        // partitioning between canonical-form drift (this arm) and
3092        // semantic-zero (the downstream gates) remains stable.
3093        // Peer with the future leading-zero arms on the two remaining
3094        // typed-magnitude codecs the trajectory acknowledges:
3095        // `limits::parse_duration` backing `:limits :wall-clock`,
3096        // `limits::parse_byte_size` backing `:limits :memory` — each
3097        // carries the same canonical-form-drift class today; this
3098        // gate lands the discipline on the shared duration codec
3099        // first because the `rate_limit_codec` predecessor on the
3100        // same canonical-form-drift axis is the closest peer on the
3101        // trajectory.
3102        //
3103        // Routed through the lifted
3104        // [`crate::render::is_leading_zero_padded_magnitude`]
3105        // predicate — the same source of truth the four peer
3106        // typed-magnitude codec sites share.
3107        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
3108            return Err(format!(
3109                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
3110                 canonical authoring form for the typed duration slots routed through \
3111                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3112                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3113                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
3114                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
3115                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
3116                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
3117                 serialize — breaking the THEORY.md Part V render-determinism contract \
3118                 every typed slot carries. Strip the leading zeros (write \
3119                 `\"30s\"` instead of `\"030s\"`)"
3120            ));
3121        }
3122        // The digit-only gate guarantees every byte is `[0-9]`, and
3123        // the leading-zero arm above guarantees the magnitude is
3124        // either the single byte `"0"` or starts with `[1-9]`, so
3125        // the only way `u64::from_str` can fail here is overflow (the
3126        // magnitude exceeds `u64::MAX`). Surface that with an
3127        // overflow-shaped wording so the diagnostic names the offending
3128        // magnitude verbatim rather than collapsing onto the
3129        // non-canonical arm. The codec now operates on `u64` end-to-end
3130        // — every accepted magnitude is integer-exact; no f64 mantissa
3131        // drift between author-supplied magnitude and the consumer's
3132        // `Duration` value. Same shape `crate::limits::parse_duration`
3133        // (818dd38) carries on the peer `:limits :wall-clock` axis.
3134        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
3135            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
3136        })?;
3137        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
3138        // unit-arm dispatch through the canonical
3139        // [`crate::render::duration_from_integer_magnitude_and_unit`]
3140        // primitive — the substrate-side single-owner unit-dispatch
3141        // table every typed-duration codec in caixa-core routes
3142        // through (peer: `crate::limits::parse_duration` backing
3143        // `:limits :wall-clock`). Every unit conversion is integer-
3144        // exact for an integer magnitude; overflow surfaces via the
3145        // typed `DurationUnitError::Overflow { multiplier }`
3146        // discriminant so this arm reconstructs the pre-lift
3147        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
3148        // wording verbatim from `num` / `unit_trim` / the returned
3149        // `multiplier`, and the unknown-unit arm reconstructs the
3150        // pre-lift `"unknown duration unit \"<other>\""` wording from
3151        // the caller-scoped `unit_trim`. Load-bearing pinned by
3152        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
3153        let unit_trim = unit.trim();
3154        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
3155            |e| match e {
3156                crate::render::DurationUnitError::Overflow { multiplier } => format!(
3157                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
3158                ),
3159                crate::render::DurationUnitError::UnknownUnit => {
3160                    format!("unknown duration unit {unit_trim:?}")
3161                }
3162            },
3163        )?;
3164        Ok(dur)
3165    }
3166
3167    /// Render a [`Duration`] in the canonical pleme-io duration string
3168    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
3169    /// caixa typed-duration slot serializes to and the same form K8s
3170    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
3171    /// EnvoyConfig per-route timeouts both expect (an integer
3172    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
3173    /// `+`). Lifted to `pub` so caixa-side renderers
3174    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
3175    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
3176    /// emitter, the future caixa-otel collector pipeline emitter) can
3177    /// consume the same canonical formatter without re-inlining the
3178    /// magnitude/unit decision tree (and inheriting the same drift
3179    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
3180    /// downstream apply-time parsing in non-obvious ways).
3181    pub fn render(d: Duration) -> String {
3182        let total_ms = d.as_millis();
3183        if total_ms == 0 {
3184            return "0s".into();
3185        }
3186        if total_ms.is_multiple_of(3600 * 1000) {
3187            return format!("{}h", total_ms / (3600 * 1000));
3188        }
3189        if total_ms.is_multiple_of(60 * 1000) {
3190            return format!("{}m", total_ms / (60 * 1000));
3191        }
3192        if total_ms.is_multiple_of(1000) {
3193            return format!("{}s", total_ms / 1000);
3194        }
3195        format!("{total_ms}ms")
3196    }
3197
3198    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
3199    ///
3200    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
3201    /// largest divisor unit, so any sub-millisecond residue
3202    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
3203    /// §V.2.7 render-determinism contract:
3204    ///
3205    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
3206    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
3207    ///     `1_000_000` ns ≠ original `1_500_000` ns;
3208    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
3209    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
3210    ///     on every typed-`Duration` slot then rejects on re-validate.
3211    ///
3212    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
3213    /// the codec's round-trippable accepted set lives in exactly one place —
3214    /// every typed-`Duration` slot that routes through this shared codec
3215    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
3216    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
3217    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
3218    /// every typed-`Duration` slot whose own codec shares the same
3219    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
3220    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
3221    /// pair) calls this predicate from its `validate()` to bracket the
3222    /// accepted set against the codec's accepted set, structurally. Drift
3223    /// between the codec's granularity and any typed slot's accepted set is
3224    /// then a single-source-of-truth edit at this predicate rather than a
3225    /// silent round-trip break the next consumer discovers at apply time.
3226    ///
3227    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
3228    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
3229    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
3230    /// family — same "typed-slot's valid set matches its codec's accepted
3231    /// set, structurally" discipline carried at the codec layer.
3232    #[must_use]
3233    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
3234        d.subsec_nanos().is_multiple_of(1_000_000)
3235    }
3236}
3237
3238/// Required-Duration variant for fields that aren't Option<Duration>.
3239pub mod duration_codec_required {
3240    use super::Duration;
3241    use serde::{Deserialize, Deserializer, Serializer};
3242
3243    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
3244        s.serialize_str(&super::duration_codec::render(*v))
3245    }
3246
3247    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
3248        let s = String::deserialize(d)?;
3249        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
3250    }
3251}
3252
3253#[cfg(test)]
3254mod tests {
3255    use super::*;
3256
3257    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
3258        ChildSpec {
3259            caixa: name.into(),
3260            versao: ver.into(),
3261            restart,
3262        }
3263    }
3264
3265    #[test]
3266    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
3267        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
3268        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
3269        // posture. Each accessor projects the per-`:children :caixa`
3270        // / per-`:children :versao` [`String`] storage through the
3271        // `pub const fn` [`String::as_str`] (const-stable since Rust
3272        // 1.87, well within the workspace MSRV) — any future
3273        // accidental downgrade to non-`const` fails the corresponding
3274        // `<name>_via_const_fn` wrapper at caixa-core build time with
3275        // E0015 (`cannot call non-const method`), strictly stronger
3276        // than a runtime `assert!`. Sibling of the peer
3277        // per-M2/M3/universal-axis `String → &str` scalar-accessor
3278        // family pins on the sibling `const`-eval-surface passes
3279        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
3280        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
3281        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
3282        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
3283        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
3284        // [`crate::aplicacao::Entrada::destination`] at the M3
3285        // ingress axis,
3286        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
3287        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
3288        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
3289        // axis, and the per-`:contratos`
3290        // [`crate::aplicacao::WitContract::source`] /
3291        // [`crate::aplicacao::WitContract::destination`] /
3292        // [`crate::aplicacao::WitContract::world_ref`] trio the
3293        // sibling pin at 279823b already anchors).
3294        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
3295            c.nome()
3296        }
3297        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
3298            c.versao_requirement()
3299        }
3300        for (caixa, versao) in [
3301            ("worker-a", "^0.1"),
3302            ("worker-b", "~0.2.3"),
3303            ("collector", "*"),
3304        ] {
3305            let c = child(caixa, versao, RestartPolicy::Permanent);
3306            assert_eq!(nome_via_const_fn(&c), c.nome());
3307            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
3308            assert_eq!(c.nome(), caixa);
3309            assert_eq!(c.versao_requirement(), versao);
3310        }
3311    }
3312
3313    #[test]
3314    fn supervisor_children_slice_return_accessor_is_const_fn() {
3315        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
3316        // `const`-eval-surface posture. The accessor destructures the
3317        // per-`:children` `Vec<ChildSpec>` storage through the
3318        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
3319        // 1.66, well within the workspace MSRV) — any future
3320        // accidental downgrade to non-`const` fails
3321        // `children_via_const_fn` at caixa-core build time with E0015
3322        // (`cannot call non-const method`), strictly stronger than a
3323        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
3324        // `Vec → &[T]` slice-return accessor family pin
3325        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
3326        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
3327        // per-`:membros` / per-`:contratos` slice-return axes, and of
3328        // the peer M2 upgrade-appup axis pin
3329        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
3330        // on the per-`:upgrade-from :instructions` slice-return axis.
3331        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
3332            s.children()
3333        }
3334        // Sweep both the empty-children (leaf-supervisor with no
3335        // static children — the `SimpleOneForOne` dynamic-child
3336        // arm's canonical shape) and the populated-children
3337        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
3338        // arm's canonical shape) axes so the accessor carries a
3339        // const-dispatch pin on both arms.
3340        let s_empty = SupervisorSpec {
3341            estrategia: RestartStrategy::SimpleOneForOne,
3342            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3343            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3344            children: vec![],
3345        };
3346        assert!(children_via_const_fn(&s_empty).is_empty());
3347        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
3348        let s_full = SupervisorSpec {
3349            estrategia: RestartStrategy::OneForOne,
3350            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3351            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3352            children: vec![
3353                child("worker-a", "^0.1", RestartPolicy::Permanent),
3354                child("worker-b", "~0.2.3", RestartPolicy::Transient),
3355                child("collector", "*", RestartPolicy::Temporary),
3356            ],
3357        };
3358        assert_eq!(children_via_const_fn(&s_full).len(), 3);
3359        assert_eq!(children_via_const_fn(&s_full), s_full.children());
3360    }
3361
3362    #[test]
3363    fn default_has_one_for_one_and_5_restarts_in_60s() {
3364        let s = SupervisorSpec::default();
3365        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
3366        assert_eq!(s.max_restarts, 5);
3367        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
3368        assert!(s.children.is_empty());
3369    }
3370
3371    #[test]
3372    fn validate_one_for_one_requires_children() {
3373        let mut s = SupervisorSpec::default();
3374        s.children = vec![];
3375        assert!(matches!(
3376            s.validate().unwrap_err(),
3377            SupervisorError::NoChildren { .. }
3378        ));
3379        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
3380        s.validate().unwrap();
3381    }
3382
3383    #[test]
3384    fn validate_simple_one_for_one_forbids_static_children() {
3385        let mut s = SupervisorSpec {
3386            estrategia: RestartStrategy::SimpleOneForOne,
3387            ..SupervisorSpec::default()
3388        };
3389        s.children
3390            .push(child("w", "^0.1", RestartPolicy::Permanent));
3391        assert_eq!(
3392            s.validate().unwrap_err(),
3393            SupervisorError::SimpleOneForOneWithStaticChildren
3394        );
3395        s.children.clear();
3396        s.validate().unwrap();
3397    }
3398
3399    #[test]
3400    fn validate_rejects_zero_max_restarts() {
3401        let s = SupervisorSpec {
3402            max_restarts: 0,
3403            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3404            ..SupervisorSpec::default()
3405        };
3406        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
3407    }
3408
3409    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
3410    //
3411    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
3412    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
3413    // `:supervisor :max-restarts` axis — both fields are "trip the
3414    // next-higher protection layer after N events in a rolling window"
3415    // counters with identical degenerate-at-the-high-end shape, so the
3416    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
3417    // exactly as it lies in `1..=1000` on the breaker side.
3418
3419    #[test]
3420    fn validate_rejects_max_restarts_above_cap() {
3421        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
3422        // 1` is structurally one past the cap and silently passed
3423        // validate on every pre-gate codebase because the typed slot's
3424        // only check was the zero-floor arm. The no-op-supervisor vector
3425        // only surfaced at the runtime substrate (Erlang/OTP
3426        // MaxIntensity/Period ratio, the future wasm-operator's
3427        // per-supervisor restart-intensity counter) far from the source
3428        // caixa.lisp with no field naming the offending supervisor.
3429        let s = SupervisorSpec {
3430            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3431            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3432            ..SupervisorSpec::default()
3433        };
3434        assert_eq!(
3435            s.validate().unwrap_err(),
3436            SupervisorError::MaxRestartsExceedsCap {
3437                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3438            }
3439        );
3440    }
3441
3442    #[test]
3443    fn validate_rejects_max_restarts_far_above_cap() {
3444        // The `u32::MAX` worst case — the four-billion-restart
3445        // threshold a typo (`:max-restarts 4294967295`) or a
3446        // struct-literal copy-paste lands in the slot. Pin the cap
3447        // arm's coverage explicitly across the full `u32` overflow so
3448        // a future relaxation that drops the upper bound surfaces
3449        // here. Same shape every other typed-cap arm on this surface
3450        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
3451        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
3452        let s = SupervisorSpec {
3453            max_restarts: u32::MAX,
3454            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3455            ..SupervisorSpec::default()
3456        };
3457        assert_eq!(
3458            s.validate().unwrap_err(),
3459            SupervisorError::MaxRestartsExceedsCap {
3460                max_restarts: u32::MAX,
3461            }
3462        );
3463    }
3464
3465    #[test]
3466    fn validate_accepts_max_restarts_at_cap() {
3467        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
3468        // must validate. The cap is inclusive on the top edge,
3469        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
3470        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
3471        // discipline on the sibling capped axes. Pin the boundary
3472        // explicitly so a future off-by-one tightening
3473        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
3474        // here as a test failure rather than a silent contract
3475        // narrowing.
3476        let s = SupervisorSpec {
3477            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
3478            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3479            ..SupervisorSpec::default()
3480        };
3481        s.validate()
3482            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
3483    }
3484
3485    #[test]
3486    fn validate_accepts_max_restarts_typical_values() {
3487        // The documented production-playbook band positive-control
3488        // sweep — every value Erlang/OTP / Elixir / Riak Core /
3489        // RabbitMQ recommend (1..=100) must pass, plus a sweep
3490        // through the hyperscale band (200, 500, 1000) the cap
3491        // accepts. Pin the inclusive validated set explicitly so a
3492        // future tightening of the ceiling surfaces here.
3493        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
3494            let s = SupervisorSpec {
3495                max_restarts: n,
3496                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3497                ..SupervisorSpec::default()
3498            };
3499            s.validate()
3500                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
3501        }
3502    }
3503
3504    #[test]
3505    fn zero_max_restarts_takes_precedence_over_cap() {
3506        // The cross-arm ordering pin: `0` is structurally outside
3507        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
3508        // (cap), but the zero-floor diagnostic is the more
3509        // self-locating one (it directly names the counter-axis
3510        // remediation), so the validate gate must fire on zero first.
3511        // Same shape every other zero-then-shape ordering on this
3512        // surface uses (PolicyRetriesZero then
3513        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
3514        // PolicyBreakerMaxFailuresExceedsCap).
3515        let s = SupervisorSpec {
3516            max_restarts: 0,
3517            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3518            ..SupervisorSpec::default()
3519        };
3520        assert_eq!(
3521            s.validate().unwrap_err(),
3522            SupervisorError::ZeroMaxRestarts,
3523            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
3524        );
3525    }
3526
3527    #[test]
3528    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
3529        // The cross-arm ordering pin between the cap and the sibling
3530        // `:restart-window` gates (zero-window, canonical-window). A
3531        // supervisor carrying both an over-cap `max_restarts` AND a
3532        // structurally invalid window (zero, sub-ms) must surface the
3533        // cap diagnostic first — the cap arm is wired immediately
3534        // after the zero-restart arm and strictly before the window
3535        // arms, so the offending value the diagnostic names matches
3536        // the order the author would discover the gates by reading
3537        // top-to-bottom through `SupervisorSpec::validate`. Pin the
3538        // order so a future refactor that reorders the arms surfaces
3539        // here as a test failure rather than a silent diagnostic
3540        // regression. Peer of
3541        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
3542        // on the sibling `:politicas :circuit-breaker` slot.
3543        let s = SupervisorSpec {
3544            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3545            restart_window: Some(Duration::ZERO),
3546            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3547            ..SupervisorSpec::default()
3548        };
3549        assert_eq!(
3550            s.validate().unwrap_err(),
3551            SupervisorError::MaxRestartsExceedsCap {
3552                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3553            },
3554            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
3555        );
3556    }
3557
3558    #[test]
3559    fn max_restarts_cap_diagnostic_carries_offending_value() {
3560        // The diagnostic-shape pin: the offending `u32` is carried
3561        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
3562        // variant so the surfaced error message names the value the
3563        // author wrote (`":supervisor :max-restarts (50000) exceeds the
3564        // supervisor-policy ceiling …"`), not just the cap. Same
3565        // self-locating diagnostic shape every other typed-cap arm on
3566        // this surface carries
3567        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
3568        // the offending failure count verbatim,
3569        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
3570        // retries count verbatim).
3571        let s = SupervisorSpec {
3572            max_restarts: 50_000,
3573            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3574            ..SupervisorSpec::default()
3575        };
3576        let err = s.validate().unwrap_err();
3577        assert!(
3578            matches!(
3579                err,
3580                SupervisorError::MaxRestartsExceedsCap {
3581                    max_restarts: 50_000
3582                }
3583            ),
3584            "got {err:?}"
3585        );
3586        let msg = err.to_string();
3587        assert!(
3588            msg.contains("50000"),
3589            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
3590        );
3591    }
3592
3593    #[test]
3594    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
3595        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
3596        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
3597        // half of Learn You Some Erlang's worker-supervisor default,
3598        // sibling of the `60s` `Period` half that the paired
3599        // [`Default for SupervisorSpec`] impl already pins on the
3600        // sibling `restart_window` axis. Pinning the literal here
3601        // surfaces a future rebrand (a tightening to Elixir's `3`,
3602        // a widening to a per-cluster overlay the operator pins
3603        // through a future `:max-restarts-overrides` slot) as a
3604        // deliberate test edit, not a silent contract migration.
3605        // Peer of the sibling
3606        // [`supervisor_max_restarts_cap_pins_canonical_value`]
3607        // upper-bracket pin on the same axis.
3608        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
3609    }
3610
3611    #[test]
3612    fn default_max_restarts_helper_routes_through_lifted_default() {
3613        // Composition pin: the private `default_max_restarts()`
3614        // serde-`#[serde(default = "…")]` helper on
3615        // [`SupervisorSpec::max_restarts`] must route through the
3616        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3617        // typed `pub const` rather than a raw `5` literal. Prior to
3618        // the lift the helper carried an inline `5` with no compile-
3619        // time link back to the shared default, so the wire-format
3620        // author-omitted arm and the caixa-core
3621        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
3622        // arm could silently split on any future default rebrand.
3623        // Byte-parity against the lifted constant closes the split.
3624        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
3625    }
3626
3627    #[test]
3628    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
3629        // Composition pin: the [`Default for SupervisorSpec`] impl's
3630        // struct-literal `max_restarts` field must route through the
3631        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3632        // typed `pub const` (via the private helper this test's
3633        // sibling `default_max_restarts_helper_routes_through_lifted_default`
3634        // already pins onto the constant). Structurally: every
3635        // `SupervisorSpec::default()` call must yield a
3636        // `max_restarts` field byte-equal to the lifted constant
3637        // (the two paired defaults — the serde-side wire-format arm
3638        // and the struct-literal default arm — cannot silently split
3639        // on any future default rebrand). Peer of the sibling
3640        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
3641        // — this pin closes the byte-parity arm on the two paired
3642        // altitude entry points onto the shared substrate constant.
3643        assert_eq!(
3644            SupervisorSpec::default().max_restarts(),
3645            SUPERVISOR_MAX_RESTARTS_DEFAULT,
3646        );
3647    }
3648
3649    #[test]
3650    fn supervisor_restart_window_default_pins_otp_canonical_value() {
3651        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
3652        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
3653        // Learn You Some Erlang's worker-supervisor default, paired
3654        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
3655        // `MaxIntensity` half this constant is the sliding-window
3656        // denominator of on the same `MaxIntensity / Period`
3657        // restart-intensity ratio. Pinning the literal here surfaces a
3658        // future coherent rebrand of the paired default (Elixir's
3659        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
3660        // the operator pins through a future
3661        // `:restart-window-overrides` slot) as a deliberate test edit,
3662        // not a silent contract migration. Peer of the sibling
3663        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
3664        // paired-half pin on the same OTP-canonical default and the
3665        // [`supervisor_restart_window_cap_pins_canonical_value`]
3666        // upper-bracket pin on the same axis.
3667        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
3668    }
3669
3670    #[test]
3671    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
3672        // Composition pin: the [`Default for SupervisorSpec`] impl's
3673        // struct-literal `restart_window` field must route through the
3674        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3675        // typed `pub const` rather than a raw
3676        // `Duration::from_secs(60)` literal. Prior to this lift the
3677        // paired `{intensity, 5, 60}` OTP-canonical default was split
3678        // across two altitudes with no compile-time link between the
3679        // halves — the `MaxIntensity` half rode through the lifted
3680        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
3681        // `Period` half rode as an open-coded literal at the
3682        // composition site, so a future coherent rebrand of the paired
3683        // canonical would have had to migrate one half through the
3684        // constant and the other through a raw literal in lockstep.
3685        // Byte-parity against the lifted constant on the `Period` half
3686        // closes the split — the paired OTP-canonical default now
3687        // migrates as one unit on any future axis change. Peer of the
3688        // sibling
3689        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3690        // byte-parity pin on the paired `MaxIntensity` half.
3691        assert_eq!(
3692            SupervisorSpec::default().restart_window(),
3693            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3694        );
3695    }
3696
3697    #[test]
3698    fn supervisor_estrategia_default_pins_otp_canonical_value() {
3699        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
3700        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
3701        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
3702        // canonical default, paired with the sibling
3703        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
3704        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
3705        // this constant is the strategy discriminator of on the same
3706        // OTP-canonical worker-supervisor default. Pinning the arm here
3707        // surfaces a future coherent rebrand of the paired triple (Elixir's
3708        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
3709        // intensity/period axes leaving this strategy arm untouched, an OTP
3710        // `rest_for_one` widening once the substrate discovers startup-
3711        // order-coupled child cohorts as the more common worker-supervisor
3712        // shape, a per-cluster overlay the operator pins through a future
3713        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
3714        // supervision-canary roadmap acknowledges) as a deliberate test
3715        // edit, not a silent contract migration. Peer of the sibling
3716        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
3717        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3718        // paired-half pins on the same OTP-canonical default.
3719        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
3720    }
3721
3722    #[test]
3723    fn restart_strategy_default_routes_through_lifted_default() {
3724        // Composition pin: the [`Default for RestartStrategy`] impl's
3725        // return arm must route through the substrate-canonical
3726        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
3727        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
3728        // an inline `Self::OneForOne` with no compile-time link back to
3729        // the shared OTP-canonical `one_for_one` strategy the paired
3730        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
3731        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
3732        // `.unwrap_or_default()` (now
3733        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
3734        // so a future rebrand of the OTP-canonical strategy default (an
3735        // OTP `rest_for_one` widening once the substrate discovers
3736        // startup-order-coupled child cohorts as the more common worker-
3737        // supervisor shape, a per-cluster overlay the operator pins
3738        // through a future `:estrategia-overrides` slot) would have had to
3739        // be threaded through the `Default` impl and the two peer routes
3740        // in lockstep or the three consumers would silently split. Byte-
3741        // parity against the lifted constant closes the split. Peer of
3742        // the sibling
3743        // [`default_max_restarts_helper_routes_through_lifted_default`] +
3744        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3745        // composition pins on the paired `MaxIntensity` + `Period` halves.
3746        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
3747    }
3748
3749    #[test]
3750    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
3751        // Composition pin: the [`Default for SupervisorSpec`] impl's
3752        // struct-literal `estrategia` field must route through the
3753        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
3754        // `pub const` (either directly, or via the
3755        // [`RestartStrategy::default`] impl that the sibling
3756        // `restart_strategy_default_routes_through_lifted_default` pin
3757        // already routes onto the constant). Structurally: every
3758        // `SupervisorSpec::default()` call must yield an `estrategia`
3759        // field byte-equal to the lifted constant (the three paired
3760        // defaults — the [`Default for RestartStrategy`] impl arm, the
3761        // struct-literal default arm here, and the
3762        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
3763        // silently split on any future default rebrand). Peer of the
3764        // sibling
3765        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3766        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3767        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
3768        // of the same `SupervisorSpec::default()` composed altitude.
3769        assert_eq!(
3770            SupervisorSpec::default().estrategia(),
3771            SUPERVISOR_ESTRATEGIA_DEFAULT,
3772        );
3773    }
3774
3775    #[test]
3776    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
3777        // Composition pin: the [`Default for SupervisorSpec`] impl must
3778        // route through the substrate-canonical
3779        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
3780        // rather than a re-hand-authored struct-literal cascade. Sharpens
3781        // the sibling per-arm
3782        // `supervisor_spec_default_*_routes_through_lifted_default` pins
3783        // from a per-field lift into a whole-struct one-source-of-truth
3784        // pin — the derived-until-now [`Default::default`] and the
3785        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
3786        // construction, not by coincidence.
3787        //
3788        // A future extension of the OTP-canonical baseline (a fifth
3789        // `restart_intensity` field the Erlang/OTP `#supervisor` record
3790        // grows, a per-child-cohort split of the `restart_window` /
3791        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
3792        // CR materializer's admission-time overlay pass) reaches both
3793        // paths through exactly one edit on
3794        // [`SupervisorSpec::otp_canonical`] — the derived path could
3795        // silently disagree with the constructor's shape on any new
3796        // field whose [`Default::default`] resolves to a different arm
3797        // than the OTP-canonical baseline the constructor names, while
3798        // this delegated impl reaches the constructor directly and
3799        // picks up every future extension by construction.
3800        //
3801        // Fourth peer on the M2 / M3 typed-slot-spec
3802        // [`Default`]-through-const-ctor fold family — sibling of the
3803        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
3804        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
3805        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
3806        // (91641a4), and [`crate::BehaviorSpec`]
3807        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
3808        // per-`Option`-only-typed-slot folds — extended here onto the
3809        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
3810        // is not "everything `None`" but the Erlang/OTP-canonical
3811        // `{one_for_one, 5, 60}` worker-supervisor triple.
3812        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
3813    }
3814
3815    #[test]
3816    fn supervisor_spec_otp_canonical_byte_equals_default() {
3817        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
3818        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
3819        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
3820        // pin already asserts against the [`Default::default`] path.
3821        // Sharpens the pair-invariant into a per-constructor pin so a
3822        // future extension of [`SupervisorSpec`] with a fifth field
3823        // whose OTP-canonical shape is non-`Default::default`-equivalent
3824        // trips at caixa-core test time rather than at a downstream
3825        // consumer that composed [`SupervisorSpec::otp_canonical`] with
3826        // [`SupervisorSpec::validate`] as its "canonical baseline
3827        // seed".
3828        let canonical = SupervisorSpec::otp_canonical();
3829        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
3830        assert_eq!(canonical.max_restarts, 5);
3831        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
3832        assert!(canonical.children.is_empty());
3833    }
3834
3835    #[test]
3836    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
3837        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
3838        // remain callable from a `const`-bound position so downstream
3839        // `const`-context callers wanting a canonical OTP-baseline seed
3840        // can construct one at compile time without runtime dispatch on
3841        // the derived [`Default::default`]. Peer of the sibling
3842        // `pub const fn` [`crate::LimitsSpec::empty`] /
3843        // [`crate::aplicacao::MeshPolicy::empty`] /
3844        // [`crate::BehaviorSpec::empty`] constructors on the sibling
3845        // typed-slot-spec `pub const fn` axis. If a future edit breaks
3846        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
3847        // (a non-`const` field-default helper, a non-`const`-stable
3848        // container type promotion), this evaluation fails at
3849        // build time on this file rather than at a downstream
3850        // `const`-context call site.
3851        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
3852        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
3853        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
3854        assert_eq!(
3855            CANONICAL.restart_window,
3856            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3857        );
3858        assert!(CANONICAL.children.is_empty());
3859    }
3860
3861    #[test]
3862    fn supervisor_child_restart_default_pins_otp_canonical_value() {
3863        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
3864        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
3865        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
3866        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
3867        // half of the same OTP-shape supervisor-tree default set whose
3868        // per-`:supervisor` halves the sibling
3869        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3870        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
3871        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
3872        // arm here surfaces a future rebrand of the per-child default (an
3873        // OTP-`transient` widening once the substrate discovers clean-
3874        // completion-aware children as the more common child shape, a
3875        // per-cluster overlay the operator pins through a future
3876        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
3877        // supervision-canary roadmap acknowledges) as a deliberate test
3878        // edit, not a silent contract migration. Peer of the sibling
3879        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
3880        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
3881        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3882        // value pins on the per-`:supervisor` halves.
3883        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
3884    }
3885
3886    #[test]
3887    fn restart_policy_default_routes_through_lifted_default() {
3888        // Composition pin: the [`Default for RestartPolicy`] impl's return
3889        // arm must route through the substrate-canonical
3890        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
3891        // than a raw `Self::Permanent` arm. Prior to the lift the impl
3892        // carried an inline `Self::Permanent` with no compile-time link
3893        // back to the OTP-shape supervisor-tree default set whose three
3894        // per-`:supervisor` halves already rode through lifted constants
3895        // — so a future coherent rebrand of the set would have had to
3896        // migrate three halves through typed constants and this fourth
3897        // through a raw enum arm in lockstep or the supervisor-level and
3898        // child-level defaults would silently drift apart. Byte-parity
3899        // against the lifted constant closes the split. Peer of the
3900        // sibling
3901        // [`restart_strategy_default_routes_through_lifted_default`]
3902        // composition pin on the per-`:supervisor` `:estrategia` axis.
3903        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
3904    }
3905
3906    #[test]
3907    fn child_spec_serde_default_restart_routes_through_lifted_default() {
3908        // Composition pin: the serde-side `#[serde(default)]` on
3909        // [`ChildSpec::restart`] — the wire-format author-omitted
3910        // `:children :restart` arm — must resolve onto the substrate-
3911        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
3912        // (via the [`Default for RestartPolicy`] impl the sibling
3913        // `restart_policy_default_routes_through_lifted_default` pin
3914        // already routes onto the constant). Structurally: a `ChildSpec`
3915        // deserialized from a payload that omits the `restart` key must
3916        // yield a `restart` field byte-equal to the lifted constant, so
3917        // the wire-format author-omitted arm and the
3918        // [`RestartPolicy::default`] impl arm cannot silently split on any
3919        // future default rebrand. Peer of the sibling
3920        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
3921        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3922        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3923        // byte-parity pins on the per-`:supervisor` halves of the same
3924        // author-omitted-slot resolution surface.
3925        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
3926            .expect("ChildSpec must deserialize with the restart key omitted");
3927        assert_eq!(
3928            omitted.restart(),
3929            SUPERVISOR_CHILD_RESTART_DEFAULT,
3930            "an author-omitted :children :restart slot must degrade onto \
3931             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
3932             {:?}, expected {:?})",
3933            omitted.restart(),
3934            SUPERVISOR_CHILD_RESTART_DEFAULT,
3935        );
3936    }
3937
3938    #[test]
3939    fn supervisor_max_restarts_cap_pins_canonical_value() {
3940        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
3941        // 1000 — the same ceiling the peer
3942        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
3943        // `:politicas :circuit-breaker :max-failures` axis (both are
3944        // "trip the next-higher protection layer after N events in a
3945        // rolling window" counters with identical
3946        // degenerate-at-the-high-end shape; uniform top edge so the
3947        // M4 CR materializers and the wasm-operator reconciler reach
3948        // for either field knowing the value is in `1..=1000`). Two
3949        // orders of magnitude above every documented Erlang/OTP /
3950        // Elixir / Riak Core / RabbitMQ production-playbook
3951        // recommendation band and below the clearly-pathological
3952        // "effectively no escalation" floor (10_000, 100_000,
3953        // u32::MAX). Pinning the literal value here surfaces a future
3954        // drift (a relaxation to 10_000, a tightening to 100) as a
3955        // deliberate test edit, not a silent contract narrowing.
3956        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
3957    }
3958
3959    #[test]
3960    fn validate_rejects_empty_child_name() {
3961        let s = SupervisorSpec {
3962            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
3963            ..SupervisorSpec::default()
3964        };
3965        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
3966    }
3967
3968    #[test]
3969    fn validate_rejects_empty_child_version() {
3970        let s = SupervisorSpec {
3971            children: vec![child("w", "", RestartPolicy::Permanent)],
3972            ..SupervisorSpec::default()
3973        };
3974        assert!(matches!(
3975            s.validate().unwrap_err(),
3976            SupervisorError::EmptyChildVersion { .. }
3977        ));
3978    }
3979
3980    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
3981
3982    #[test]
3983    fn validate_rejects_invalid_child_versao_requirement() {
3984        // The fail-before-pass-after pin: a non-empty but malformed
3985        // semver requirement (`"^bad-version"`) silently passed
3986        // `validate()` on every pre-gate codebase because the prior
3987        // shape only refused the empty string. The parse failure
3988        // surfaced far downstream at lacre-resolve time with a
3989        // `semver::Error` that didn't name which `:children` entry
3990        // carried the typo. The new gate moves the check to caixa-build
3991        // time at the source caixa.lisp — the third `:versao` typed
3992        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
3993        // structural parity.
3994        let s = SupervisorSpec {
3995            children: vec![
3996                child("worker", "^0.1", RestartPolicy::Permanent),
3997                child("cache", "^bad-version", RestartPolicy::Transient),
3998            ],
3999            ..SupervisorSpec::default()
4000        };
4001        let err = s.validate().unwrap_err();
4002        assert!(
4003            matches!(
4004                err,
4005                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4006                    if caixa == "cache" && versao == "^bad-version"
4007            ),
4008            "got {err:?}"
4009        );
4010    }
4011
4012    #[test]
4013    fn validate_rejects_child_versao_with_double_caret_typo() {
4014        // `"^^0.1"` is the canonical doubled-caret typo — looks
4015        // Cargo-shaped on first glance but fails the parser because
4016        // semver doesn't accept stacked operators. Pin this
4017        // adjacent-shape footgun explicitly so a future relaxation that
4018        // accepts "looks-canonical-but-isn't" forms surfaces here.
4019        let s = SupervisorSpec {
4020            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
4021            ..SupervisorSpec::default()
4022        };
4023        let err = s.validate().unwrap_err();
4024        assert!(
4025            matches!(
4026                err,
4027                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4028                    if caixa == "worker" && versao == "^^0.1"
4029            ),
4030            "got {err:?}"
4031        );
4032    }
4033
4034    #[test]
4035    fn validate_rejects_child_versao_with_v_prefixed_tag() {
4036        // `"v0.1"` is the canonical "git-tag-shape leaking into the
4037        // semver requirement slot" typo — an author copies the
4038        // publish-side git-tag string verbatim into `:versao`, but
4039        // Cargo's semver parser rejects the leading `v`. Same
4040        // adjacent-shape footgun pinned for `:membros :versao`
4041        // (9888b13).
4042        let s = SupervisorSpec {
4043            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
4044            ..SupervisorSpec::default()
4045        };
4046        let err = s.validate().unwrap_err();
4047        assert!(
4048            matches!(
4049                err,
4050                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4051                    if caixa == "worker" && versao == "v0.1"
4052            ),
4053            "got {err:?}"
4054        );
4055    }
4056
4057    #[test]
4058    fn validate_accepts_canonical_child_versao_forms() {
4059        // The Cargo-shaped requirement forms `:deps :versao` and
4060        // `:membros :versao` already accept via
4061        // `crate::parse_requirement` must pass the children gate
4062        // without re-validating at the resolver layer. Pin every leg so
4063        // a future tightening of the canonical set surfaces here as a
4064        // test failure.
4065        for form in [
4066            "^0.1",      // caret — minor-range pin (the most common shape)
4067            "~0.1.2",    // tilde — patch-range pin
4068            "0.1.0",     // exact — single-version pin
4069            "*",         // wildcard — any version (semver::VersionReq::STAR)
4070            ">=0.1, <2", // multi-range — comma-separated comparators
4071        ] {
4072            let s = SupervisorSpec {
4073                children: vec![child("worker", form, RestartPolicy::Permanent)],
4074                ..SupervisorSpec::default()
4075            };
4076            s.validate()
4077                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4078        }
4079    }
4080
4081    #[test]
4082    fn child_versao_empty_takes_precedence_over_invalid() {
4083        // Order pin: the existing `EmptyChildVersion` diagnostic (which
4084        // doesn't try to parse) fires before the new
4085        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
4086        // `:versao` keeps its narrower error message —
4087        // `parse_requirement` would also reject `""`, but the
4088        // empty-string arm is the more self-locating diagnostic for the
4089        // author. Same ordering discipline as
4090        // `membro_versao_empty_takes_precedence_over_invalid` in
4091        // aplicacao.rs.
4092        let s = SupervisorSpec {
4093            children: vec![child("worker", "", RestartPolicy::Permanent)],
4094            ..SupervisorSpec::default()
4095        };
4096        let err = s.validate().unwrap_err();
4097        assert!(
4098            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
4099            "got {err:?}"
4100        );
4101    }
4102
4103    #[test]
4104    fn child_versao_invalid_fires_before_duplicate_check() {
4105        // Order pin: a malformed requirement on a non-duplicate entry
4106        // surfaces *its own* diagnostic (which names the offending
4107        // `:versao` string), even when a later entry would otherwise
4108        // collapse onto an earlier name. The per-entry shape gate runs
4109        // inline before the duplicate-key insert — parallel to
4110        // `membro_versao_invalid_fires_before_duplicate_check` in
4111        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
4112        let s = SupervisorSpec {
4113            children: vec![
4114                child("worker", "^bad", RestartPolicy::Permanent),
4115                child("cache", "^0.1", RestartPolicy::Transient),
4116                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4117            ],
4118            ..SupervisorSpec::default()
4119        };
4120        let err = s.validate().unwrap_err();
4121        assert!(
4122            matches!(
4123                err,
4124                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
4125            ),
4126            "got {err:?}"
4127        );
4128    }
4129
4130    #[test]
4131    fn child_versao_invalid_diagnostic_carries_offending_versao() {
4132        // The diagnostic-shape pin: the error names the offending
4133        // `:versao` value verbatim so the author can grep their
4134        // caixa.lisp without re-running the build, and carries a
4135        // non-empty `reason` from `semver::VersionReq::parse` so the
4136        // parser's own wording flows through to the diagnostic.
4137        let s = SupervisorSpec {
4138            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
4139            ..SupervisorSpec::default()
4140        };
4141        let err = s.validate().unwrap_err();
4142        let SupervisorError::ChildVersaoInvalid {
4143            caixa,
4144            versao,
4145            reason,
4146        } = err
4147        else {
4148            panic!("expected ChildVersaoInvalid, got other variant");
4149        };
4150        assert_eq!(caixa, "worker");
4151        assert_eq!(versao, "not-a-req");
4152        assert!(
4153            !reason.is_empty(),
4154            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
4155        );
4156    }
4157
4158    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
4159
4160    #[test]
4161    fn validate_rejects_child_caixa_with_uppercase() {
4162        // The canonical "I copied the Servico's display name verbatim"
4163        // typo — child caixa names are lowercase per K8s DNS-1123 label
4164        // rule. The diagnostic names the offending name and suggests the
4165        // lower-cased fix in one edit, mirroring the
4166        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
4167        let s = SupervisorSpec {
4168            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
4169            ..SupervisorSpec::default()
4170        };
4171        let err = s.validate().unwrap_err();
4172        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4173            panic!("expected ChildCaixaInvalid, got other variant");
4174        };
4175        assert_eq!(caixa, "Worker");
4176        assert!(
4177            reason.contains("uppercase"),
4178            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
4179        );
4180        assert!(
4181            reason.contains("\"worker\""),
4182            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
4183        );
4184    }
4185
4186    #[test]
4187    fn validate_rejects_child_caixa_with_underscore() {
4188        // The canonical "I'm thinking of a Python module / Postgres
4189        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
4190        // label schema. K8s rejects `metadata.name: my_worker` at
4191        // admission time with an opaque `field is invalid` (no source-
4192        // citing diagnostic). The gate moves it to caixa-build time.
4193        let s = SupervisorSpec {
4194            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
4195            ..SupervisorSpec::default()
4196        };
4197        let err = s.validate().unwrap_err();
4198        assert!(
4199            matches!(
4200                err,
4201                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4202                    if caixa == "my_worker" && reason.contains('_')
4203            ),
4204            "got {err:?}"
4205        );
4206    }
4207
4208    #[test]
4209    fn validate_rejects_child_caixa_with_dot() {
4210        // A `:children :caixa` entry is a single DNS-1123 label, not a
4211        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
4212        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
4213        // (3f9d7a0) on the peer name axis.
4214        let s = SupervisorSpec {
4215            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
4216            ..SupervisorSpec::default()
4217        };
4218        let err = s.validate().unwrap_err();
4219        assert!(
4220            matches!(
4221                err,
4222                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4223                    if caixa == "team.worker" && reason.contains('.')
4224            ),
4225            "got {err:?}"
4226        );
4227    }
4228
4229    #[test]
4230    fn validate_rejects_child_caixa_with_leading_hyphen() {
4231        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
4232        // with an alphanumeric. The K8s apiserver rejects `-worker`
4233        // outright; the renderer would emit a `metadata.name: "-worker"`
4234        // that fails admission far from the source caixa.lisp.
4235        let s = SupervisorSpec {
4236            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
4237            ..SupervisorSpec::default()
4238        };
4239        let err = s.validate().unwrap_err();
4240        assert!(
4241            matches!(
4242                err,
4243                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4244                    if caixa == "-worker" && reason.contains("start and end")
4245            ),
4246            "got {err:?}"
4247        );
4248    }
4249
4250    #[test]
4251    fn validate_rejects_child_caixa_with_trailing_hyphen() {
4252        // The symmetric arm of the boundary rule. Pin separately so
4253        // both ends of the label are covered against a future relaxation
4254        // that only checks one boundary.
4255        let s = SupervisorSpec {
4256            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
4257            ..SupervisorSpec::default()
4258        };
4259        let err = s.validate().unwrap_err();
4260        assert!(
4261            matches!(
4262                err,
4263                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4264                    if caixa == "worker-"
4265            ),
4266            "got {err:?}"
4267        );
4268    }
4269
4270    #[test]
4271    fn validate_rejects_child_caixa_with_unicode() {
4272        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
4273        // (`xn--…`) by the author before it reaches K8s. The byte-by-
4274        // byte ASCII validity check rejects multi-byte UTF-8 sequences
4275        // by the first byte that fails the `[a-z0-9-]` predicate.
4276        let s = SupervisorSpec {
4277            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
4278            ..SupervisorSpec::default()
4279        };
4280        let err = s.validate().unwrap_err();
4281        assert!(
4282            matches!(
4283                err,
4284                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4285                    if caixa == "café"
4286            ),
4287            "got {err:?}"
4288        );
4289    }
4290
4291    #[test]
4292    fn validate_rejects_child_caixa_with_whitespace() {
4293        // Whitespace is the canonical "I pasted from a sketch / doc"
4294        // footgun. The apiserver rejects every `metadata.name` value
4295        // carrying whitespace; pin the gate fires at the right boundary.
4296        let s = SupervisorSpec {
4297            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
4298            ..SupervisorSpec::default()
4299        };
4300        let err = s.validate().unwrap_err();
4301        assert!(
4302            matches!(
4303                err,
4304                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4305                    if caixa == "my worker"
4306            ),
4307            "got {err:?}"
4308        );
4309    }
4310
4311    #[test]
4312    fn validate_rejects_child_caixa_too_long() {
4313        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
4314        // 63 bytes; the K8s apiserver rejects every `metadata.name`
4315        // axis over the limit at admission time. The diagnostic names
4316        // both the cap and the actual length so the author can shorten
4317        // in one edit, mirroring `rejects_membro_caixa_too_long`
4318        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
4319        let too_long = "a".repeat(64);
4320        let s = SupervisorSpec {
4321            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
4322            ..SupervisorSpec::default()
4323        };
4324        let err = s.validate().unwrap_err();
4325        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4326            panic!("expected ChildCaixaInvalid, got other variant");
4327        };
4328        assert_eq!(caixa, too_long);
4329        assert!(
4330            reason.contains("63"),
4331            "diagnostic must name the 63-byte cap (got: {reason:?})"
4332        );
4333        assert!(
4334            reason.contains("64"),
4335            "diagnostic must name the actual length (got: {reason:?})"
4336        );
4337    }
4338
4339    #[test]
4340    fn child_caixa_max_length_validates() {
4341        // The 63-byte boundary control pin — exactly-at-the-cap is
4342        // accepted, mirroring `membro_caixa_max_length_validates`
4343        // (3f9d7a0) and `placement_cluster_max_length_validates`
4344        // (6cbb900). Pinned separately so a future off-by-one tightening
4345        // surfaces here.
4346        let max_label = "a".repeat(63);
4347        let s = SupervisorSpec {
4348            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
4349            ..SupervisorSpec::default()
4350        };
4351        s.validate().unwrap();
4352    }
4353
4354    #[test]
4355    fn validate_accepts_canonical_child_caixa_forms() {
4356        // The realistic shapes a supervised child's `:caixa` carries —
4357        // single-word `worker`, version-suffixed `cache-v2`, single-char
4358        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
4359        // `payment-retry`, all-digit `0`. Pin every leg so a future
4360        // tightening (e.g. requiring a leading lowercase letter) surfaces
4361        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
4362        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
4363        // (6cbb900).
4364        for form in [
4365            "worker",
4366            "cache-v2",
4367            "a",
4368            "db",
4369            "2-pool",
4370            "payment-retry",
4371            "0",
4372        ] {
4373            let s = SupervisorSpec {
4374                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
4375                ..SupervisorSpec::default()
4376            };
4377            s.validate()
4378                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4379        }
4380    }
4381
4382    #[test]
4383    fn child_caixa_empty_takes_precedence_over_invalid() {
4384        // Order pin: the existing `EmptyChildName` diagnostic (which
4385        // doesn't try to parse the DNS-1123 shape) fires before the new
4386        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
4387        // its narrower error message — `is_dns_1123_label` would reject
4388        // the empty string too (boundary check on the first byte), but
4389        // the empty-string arm is the more self-locating diagnostic for
4390        // the author. Same ordering discipline as
4391        // `membro_caixa_empty_takes_precedence_over_invalid` in
4392        // aplicacao.rs.
4393        let s = SupervisorSpec {
4394            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4395            ..SupervisorSpec::default()
4396        };
4397        let err = s.validate().unwrap_err();
4398        assert_eq!(err, SupervisorError::EmptyChildName);
4399    }
4400
4401    #[test]
4402    fn child_caixa_invalid_fires_before_versao_check() {
4403        // Order pin: the per-axis shape gate runs inline before the
4404        // per-entry versao check, so a malformed `:caixa` on an entry
4405        // whose `:versao` would also fail surfaces the more self-
4406        // locating name-axis diagnostic first. Parallel to
4407        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
4408        // and `placement_cluster_invalid_fires_before_duplicate_check`
4409        // (6cbb900).
4410        let s = SupervisorSpec {
4411            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
4412            ..SupervisorSpec::default()
4413        };
4414        let err = s.validate().unwrap_err();
4415        assert!(
4416            matches!(
4417                err,
4418                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
4419            ),
4420            "got {err:?}"
4421        );
4422    }
4423
4424    #[test]
4425    fn child_caixa_invalid_fires_before_duplicate_check() {
4426        // Order pin: a malformed name on a non-duplicate entry surfaces
4427        // its own diagnostic, even when a later entry would otherwise
4428        // collapse onto an earlier name. The per-entry shape gate runs
4429        // inline before the duplicate-key HashSet insert, mirroring
4430        // `placement_cluster_invalid_fires_before_duplicate_check`
4431        // (6cbb900).
4432        let s = SupervisorSpec {
4433            children: vec![
4434                child("Worker", "^0.1", RestartPolicy::Permanent),
4435                child("cache", "^0.1", RestartPolicy::Transient),
4436                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4437            ],
4438            ..SupervisorSpec::default()
4439        };
4440        let err = s.validate().unwrap_err();
4441        assert!(
4442            matches!(
4443                err,
4444                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
4445            ),
4446            "got {err:?}"
4447        );
4448    }
4449
4450    #[test]
4451    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
4452        // The diagnostic-shape pin: the error names the offending
4453        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
4454        // the author can grep their caixa.lisp without re-running the
4455        // build. Mirrors the diagnostic-shape sweep on every prior
4456        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
4457        let s = SupervisorSpec {
4458            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
4459            ..SupervisorSpec::default()
4460        };
4461        let err = s.validate().unwrap_err();
4462        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4463            panic!("expected ChildCaixaInvalid, got other variant");
4464        };
4465        assert_eq!(caixa, "My_Worker");
4466        assert!(
4467            !reason.is_empty(),
4468            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
4469        );
4470    }
4471
4472    // ── value-shape: zero restart_window + duplicate child names ──────────
4473
4474    #[test]
4475    fn validate_accepts_none_restart_window() {
4476        // Omitted `:restart-window` is the "never reset" sentinel —
4477        // valid by design. Mirrors :limits axes where None = unbounded.
4478        let s = SupervisorSpec {
4479            restart_window: None,
4480            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4481            ..SupervisorSpec::default()
4482        };
4483        s.validate().unwrap();
4484    }
4485
4486    #[test]
4487    fn validate_rejects_zero_restart_window() {
4488        // Same "0 means the opposite of what you think" footgun closed
4489        // for :politicas :timeout (Envoy treats 0s as infinite) and
4490        // :limits :wall-clock (wasmtime traps before the call starts).
4491        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
4492        let s = SupervisorSpec {
4493            restart_window: Some(Duration::ZERO),
4494            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4495            ..SupervisorSpec::default()
4496        };
4497        assert_eq!(
4498            s.validate().unwrap_err(),
4499            SupervisorError::RestartWindowZero
4500        );
4501    }
4502
4503    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
4504    //
4505    // The fourth (and last) typed-`Duration` axis in caixa-core to get
4506    // the integer-millisecond canonical-form gate — peer with
4507    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
4508    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
4509    // path is already gated at the shared codec layer (see
4510    // `restart_window_serde_rejects_fractional_seconds`); this arm
4511    // closes the programmatic-struct-literal path the codec gate can't
4512    // see.
4513
4514    #[test]
4515    fn validate_rejects_sub_millisecond_restart_window() {
4516        // The fail-before-pass-after pin: a programmatic
4517        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
4518        // `validate` on every pre-gate codebase, then truncated to
4519        // `as_millis() == 1` on first serialize — the shared codec
4520        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
4521        // 1_000_000 ns, the typed `restart_window` no longer matches
4522        // its rendered form.
4523        let s = SupervisorSpec {
4524            restart_window: Some(Duration::from_micros(1500)),
4525            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4526            ..SupervisorSpec::default()
4527        };
4528        match s.validate().unwrap_err() {
4529            SupervisorError::RestartWindowNotCanonical { window } => {
4530                assert_eq!(window, Duration::from_micros(1500));
4531            }
4532            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4533        }
4534    }
4535
4536    #[test]
4537    fn validate_rejects_one_nanosecond_restart_window() {
4538        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
4539        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
4540        // so the shared codec emits the literal `"0s"` — the next
4541        // serde round-trip would parse back to `Duration::ZERO`, which
4542        // the `RestartWindowZero` arm then rejects on re-validate. The
4543        // canonical-form gate at this layer surfaces a self-locating
4544        // diagnostic naming the offending Duration verbatim rather
4545        // than a downstream `RestartWindowZero` whose remediation
4546        // points at omitting the slot.
4547        let s = SupervisorSpec {
4548            restart_window: Some(Duration::from_nanos(1)),
4549            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4550            ..SupervisorSpec::default()
4551        };
4552        match s.validate().unwrap_err() {
4553            SupervisorError::RestartWindowNotCanonical { window } => {
4554                assert_eq!(window, Duration::from_nanos(1));
4555            }
4556            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4557        }
4558    }
4559
4560    #[test]
4561    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
4562        // The 1-ns-past-1ms boundary case: a `Duration` carrying
4563        // 1_000_001 ns is structurally past the integer-ms granularity
4564        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
4565        // trip would truncate to `1ms` and the consumer would observe
4566        // a 1-ns drift on every emit. Same boundary the peer
4567        // `validate_rejects_nanosecond_past_canonical_boundary` test
4568        // in limits.rs pins for the `:limits :wall-clock` axis.
4569        let w = Duration::from_nanos(1_000_001);
4570        let s = SupervisorSpec {
4571            restart_window: Some(w),
4572            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4573            ..SupervisorSpec::default()
4574        };
4575        assert_eq!(
4576            s.validate().unwrap_err(),
4577            SupervisorError::RestartWindowNotCanonical { window: w }
4578        );
4579    }
4580
4581    #[test]
4582    fn validate_accepts_integer_millisecond_restart_window_values() {
4583        // The positive-control sweep: every `Duration` the shared
4584        // codec can round-trip losslessly — the canonical
4585        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
4586        // pair emits and accepts — passes `validate` without
4587        // surfacing the new canonical-form arm. Mirrors
4588        // `validate_accepts_integer_millisecond_wall_clock_values` on
4589        // the sibling `:limits :wall-clock` axis.
4590        for w in [
4591            Duration::from_millis(1),
4592            Duration::from_millis(500),
4593            Duration::from_millis(1500),
4594            Duration::from_secs(1),
4595            Duration::from_secs(30),
4596            Duration::from_secs(60),
4597            Duration::from_secs(120),
4598            Duration::from_secs(3600),
4599        ] {
4600            let s = SupervisorSpec {
4601                restart_window: Some(w),
4602                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4603                ..SupervisorSpec::default()
4604            };
4605            s.validate()
4606                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
4607        }
4608    }
4609
4610    #[test]
4611    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
4612        // Cross-arm ordering pin: `Duration::ZERO` has
4613        // `subsec_nanos() == 0` and would otherwise pass the
4614        // canonical-form arm — the zero-floor arm must fire first so
4615        // the more self-locating `RestartWindowZero` diagnostic (with
4616        // its omit-axis remediation directly named) leads. Same
4617        // posture every peer zero-then-shape gate uses
4618        // (`WallClockZero` → `WallClockNotCanonical`,
4619        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
4620        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
4621        let s = SupervisorSpec {
4622            restart_window: Some(Duration::ZERO),
4623            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4624            ..SupervisorSpec::default()
4625        };
4626        assert_eq!(
4627            s.validate().unwrap_err(),
4628            SupervisorError::RestartWindowZero
4629        );
4630    }
4631
4632    #[test]
4633    fn restart_window_canonical_diagnostic_carries_offending_duration() {
4634        // Diagnostic-shape pin: the canonical-form arm names the
4635        // offending `Duration` verbatim so the author's grep lands on
4636        // the field's value, not a generic "duration not canonical"
4637        // message. Same shape every other typed-canonical-form arm
4638        // on this surface carries (`WallClockNotCanonical` carries
4639        // the offending `Duration` verbatim,
4640        // `PolicyTimeoutNotCanonical` carries the offending
4641        // `Duration` verbatim).
4642        let w = Duration::from_micros(500);
4643        let s = SupervisorSpec {
4644            restart_window: Some(w),
4645            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4646            ..SupervisorSpec::default()
4647        };
4648        let err = s.validate().unwrap_err();
4649        let msg = err.to_string();
4650        assert!(
4651            msg.contains("500"),
4652            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
4653        );
4654        assert!(
4655            msg.contains("sub-millisecond"),
4656            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
4657        );
4658    }
4659
4660    #[test]
4661    fn restart_window_validated_value_round_trips_through_codec() {
4662        // The structural property the canonical-ms gate enforces:
4663        // every `SupervisorSpec::restart_window` past
4664        // `SupervisorSpec::validate` round-trips losslessly through
4665        // the shared duration codec (serialize → string →
4666        // deserialize → equal value). Pin this end-to-end so a future
4667        // change to either side (the validate gate's accepted
4668        // granularity, the codec's parse/render unit set) that breaks
4669        // the alignment surfaces here. Peer of
4670        // `wall_clock_validated_value_round_trips_through_codec` on
4671        // the sibling `:limits :wall-clock` axis.
4672        for w in [
4673            Duration::from_millis(1),
4674            Duration::from_millis(1500),
4675            Duration::from_secs(30),
4676            Duration::from_secs(3600),
4677        ] {
4678            let s = SupervisorSpec {
4679                restart_window: Some(w),
4680                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4681                ..SupervisorSpec::default()
4682            };
4683            s.validate().unwrap();
4684            let json = serde_json::to_string(&s).unwrap();
4685            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4686            assert_eq!(back.restart_window, Some(w));
4687        }
4688    }
4689
4690    // ── value-shape: upper cap on :restart-window ─────────────────────────
4691    //
4692    // The fourth (and last) typed-`Duration` axis in caixa-core to get
4693    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
4694    // `:politicas :timeout` (2e8ee7e), and `:politicas
4695    // :circuit-breaker :window` (379a814). Brackets the typed
4696    // `:restart-window` axis structurally: every validated value lies
4697    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
4698    // granularity, closing the
4699    // rolling-window-degenerates-to-lifetime-counter footgun the prior
4700    // zero-floor-and-canonical-form-only checks left open.
4701
4702    #[test]
4703    fn validate_rejects_restart_window_above_cap() {
4704        // The fail-before-pass-after pin: 3601s = 1h + 1s is
4705        // structurally one canonical-tick past the
4706        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
4707        // integer-millisecond magnitude the canonical-form arm above
4708        // accepts cleanly, that the shared duration codec round-trips
4709        // losslessly as `"3601s"`, and that silently passed validate on
4710        // every pre-gate codebase because the typed slot's only checks
4711        // were the zero-floor and canonical-form arms. The runtime
4712        // substrate consuming the value (Erlang/OTP's MaxIntensity/
4713        // Period reconciler, the future wasm-operator's per-supervisor
4714        // restart-intensity counter) reaches for a `Duration` so long
4715        // no realistic restart-recovery pattern resets the counter,
4716        // far from the source caixa.lisp.
4717        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
4718        let s = SupervisorSpec {
4719            restart_window: Some(w),
4720            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4721            ..SupervisorSpec::default()
4722        };
4723        assert_eq!(
4724            s.validate().unwrap_err(),
4725            SupervisorError::RestartWindowExceedsCap { window: w }
4726        );
4727    }
4728
4729    #[test]
4730    fn validate_rejects_restart_window_one_millisecond_above_cap() {
4731        // Boundary case: exactly 1ms past the cap (the granularity the
4732        // canonical-form gate enforces). Catches a future "strictly
4733        // less than" half-measure and pins the diagnostic to name the
4734        // offending `Duration` verbatim. Peer of
4735        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
4736        // `rejects_policy_timeout_one_millisecond_above_cap` /
4737        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
4738        // on the sibling typed-`Duration` axes' top edges.
4739        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
4740        let s = SupervisorSpec {
4741            restart_window: Some(w),
4742            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4743            ..SupervisorSpec::default()
4744        };
4745        assert_eq!(
4746            s.validate().unwrap_err(),
4747            SupervisorError::RestartWindowExceedsCap { window: w }
4748        );
4749    }
4750
4751    #[test]
4752    fn validate_rejects_restart_window_far_above_cap() {
4753        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
4754        // `(:restart-window "7d")`, or any "I want a lifetime counter
4755        // but wrote a `<integer>h` magnitude anyway" typo — values the
4756        // canonical-form arm accepts as integer-millisecond magnitudes,
4757        // the codec round-trips losslessly through serde, but the
4758        // operator's `MaxIntensity / Period` reconciler cannot honor
4759        // as a meaningful rolling window. Until this gate landed
4760        // validate accepted them. Pin the common above-cap values (24h,
4761        // 7d, ~11.5d) so a future relaxation that drops the upper bound
4762        // surfaces here.
4763        for w in [
4764            Duration::from_secs(86_400),    // 24h
4765            Duration::from_secs(604_800),   // 7d
4766            Duration::from_secs(1_000_000), // ~11.5 days
4767        ] {
4768            let s = SupervisorSpec {
4769                restart_window: Some(w),
4770                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4771                ..SupervisorSpec::default()
4772            };
4773            assert_eq!(
4774                s.validate().unwrap_err(),
4775                SupervisorError::RestartWindowExceedsCap { window: w }
4776            );
4777        }
4778    }
4779
4780    #[test]
4781    fn validate_accepts_restart_window_at_cap() {
4782        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
4783        // (1h) — must validate. The cap is inclusive on the top edge,
4784        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
4785        // [`crate::POLICY_TIMEOUT_MAX`] /
4786        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
4787        // capped axes. Pin the boundary explicitly so a future
4788        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
4789        // instead of `>`) surfaces here as a test failure rather than a
4790        // silent contract narrowing.
4791        let s = SupervisorSpec {
4792            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
4793            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4794            ..SupervisorSpec::default()
4795        };
4796        s.validate()
4797            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
4798    }
4799
4800    #[test]
4801    fn validate_accepts_restart_window_typical_values() {
4802        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
4803        // per-supervisor production-playbook band positive-control
4804        // sweep — every value Learn You Some Erlang's `{intensity, 5,
4805        // 60}` worker-supervisor `Period = 60s` default, Elixir's
4806        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
4807        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
4808        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
4809        // default recommend (5s..=300s) must pass, plus a sweep
4810        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
4811        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
4812        // on the sibling `:limits :wall-clock` axis.
4813        for w in [
4814            Duration::from_millis(1),
4815            Duration::from_millis(500),
4816            Duration::from_secs(1),
4817            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
4818            Duration::from_secs(10), // Riak Core lower
4819            Duration::from_secs(30),
4820            Duration::from_secs(60),  // Learn You Some Erlang default
4821            Duration::from_secs(120), // OTP supervisor MaxT typical
4822            Duration::from_secs(300), // Riak Core upper
4823            Duration::from_secs(900), // 15m
4824            Duration::from_secs(1800),
4825            Duration::from_secs(3600), // exactly 1h, the cap
4826        ] {
4827            let s = SupervisorSpec {
4828                restart_window: Some(w),
4829                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4830                ..SupervisorSpec::default()
4831            };
4832            s.validate()
4833                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
4834        }
4835    }
4836
4837    #[test]
4838    fn restart_window_zero_takes_precedence_over_cap() {
4839        // The cross-arm ordering pin: `Duration::ZERO` is structurally
4840        // outside both `>= 1ms` (zero-floor) and `<=
4841        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
4842        // diagnostic is the more self-locating one (it directly names
4843        // the omit-axis remediation), so the validate gate must fire
4844        // on zero first. Same shape every other zero-then-cap ordering
4845        // on this surface uses (`WallClockZero` then
4846        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
4847        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
4848        // `PolicyBreakerWindowExceedsCap`).
4849        let s = SupervisorSpec {
4850            restart_window: Some(Duration::ZERO),
4851            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4852            ..SupervisorSpec::default()
4853        };
4854        assert_eq!(
4855            s.validate().unwrap_err(),
4856            SupervisorError::RestartWindowZero,
4857            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
4858        );
4859    }
4860
4861    #[test]
4862    fn restart_window_canonical_takes_precedence_over_cap() {
4863        // The cross-arm ordering pin: a `Duration` that is *both*
4864        // sub-millisecond (non-canonical-form) and structurally above
4865        // the cap surfaces the canonical-form diagnostic first,
4866        // because the round-trip-shape break is the more fundamental
4867        // issue (the value can't even round-trip through the codec,
4868        // so the cap diagnostic naming `1ms..=1h` would be misleading
4869        // — there's no integer-ms form of the offending value). Pin
4870        // the order so a future refactor that reorders the arms
4871        // surfaces here as a test failure rather than a silent
4872        // diagnostic regression. Peer of
4873        // `wall_clock_canonical_takes_precedence_over_cap` /
4874        // `policy_timeout_canonical_takes_precedence_over_cap`.
4875        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
4876        let s = SupervisorSpec {
4877            restart_window: Some(w),
4878            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4879            ..SupervisorSpec::default()
4880        };
4881        assert_eq!(
4882            s.validate().unwrap_err(),
4883            SupervisorError::RestartWindowNotCanonical { window: w },
4884            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
4885        );
4886    }
4887
4888    #[test]
4889    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
4890        // The cross-arm ordering pin between the `:max-restarts` cap
4891        // and the sibling `:restart-window` cap. A supervisor carrying
4892        // both an over-cap `max_restarts` AND an over-cap window must
4893        // surface the `MaxRestartsExceedsCap` diagnostic first — the
4894        // cap arm is wired immediately after the zero-restart arm and
4895        // strictly before every window-axis arm (zero / canonical /
4896        // cap), so the offending value the diagnostic names matches
4897        // the order the author would discover the gates by reading
4898        // top-to-bottom through `SupervisorSpec::validate`. Pin the
4899        // order so a future refactor that reorders the arms surfaces
4900        // here as a test failure rather than a silent diagnostic
4901        // regression. Peer of
4902        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
4903        // on the sibling zero / canonical window arms.
4904        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
4905        let s = SupervisorSpec {
4906            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4907            restart_window: Some(w),
4908            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4909            ..SupervisorSpec::default()
4910        };
4911        assert_eq!(
4912            s.validate().unwrap_err(),
4913            SupervisorError::MaxRestartsExceedsCap {
4914                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4915            },
4916            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4917        );
4918    }
4919
4920    #[test]
4921    fn restart_window_cap_diagnostic_carries_offending_value() {
4922        // The diagnostic-shape pin: the offending `Duration` is
4923        // carried verbatim into the
4924        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
4925        // surfaced error message names the value the author wrote,
4926        // not just the cap. Same self-locating diagnostic shape every
4927        // other typed-cap arm on this surface carries
4928        // (`WallClockExceedsCap` carries the offending `Duration`
4929        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
4930        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
4931        // the offending `Duration` verbatim).
4932        let w = Duration::from_secs(7200); // 2h
4933        let s = SupervisorSpec {
4934            restart_window: Some(w),
4935            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4936            ..SupervisorSpec::default()
4937        };
4938        let err = s.validate().unwrap_err();
4939        assert!(
4940            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
4941            "got {err:?}"
4942        );
4943        let msg = err.to_string();
4944        assert!(
4945            msg.contains("7200"),
4946            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
4947        );
4948    }
4949
4950    #[test]
4951    fn supervisor_restart_window_cap_pins_canonical_value() {
4952        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
4953        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
4954        // shared duration codec emits as a clean canonical string
4955        // (`"<n>h"`). Pinning the literal value here surfaces a future
4956        // drift (a relaxation to 24h, a tightening to 5m) as a
4957        // deliberate test edit, not a silent contract narrowing.
4958        //
4959        // The four typed-`Duration` caps on the validation surface
4960        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
4961        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
4962        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
4963        // single uniform top edge at the codec's largest emitted unit
4964        // — a structural-property invariant the equality assertions
4965        // here enshrine, so a future drift on any of the four
4966        // surfaces as a deliberate test edit. Same shape every other
4967        // typed-cap value pin uses
4968        // (`wall_clock_cap_pins_canonical_value`,
4969        // `policy_timeout_cap_pins_canonical_value`,
4970        // `circuit_breaker_window_cap_pins_canonical_value`).
4971        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
4972        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
4973        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
4974        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
4975        assert_eq!(
4976            SUPERVISOR_RESTART_WINDOW_MAX,
4977            crate::POLICY_BREAKER_WINDOW_MAX
4978        );
4979    }
4980
4981    #[test]
4982    fn restart_window_cap_value_round_trips_through_codec() {
4983        // The codec round-trip property the cap arm preserves: the
4984        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
4985        // through the shared duration codec — every value at the cap
4986        // serializes to the canonical `"1h"` form and parses back
4987        // identically. Pin the round-trip so a future change to the
4988        // codec's unit set or to the cap's magnitude that breaks the
4989        // round-trip property surfaces here. Peer of
4990        // `wall_clock_cap_value_round_trips_through_codec` on the
4991        // sibling `:limits :wall-clock` axis.
4992        let s = SupervisorSpec {
4993            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
4994            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4995            ..SupervisorSpec::default()
4996        };
4997        s.validate().unwrap();
4998        let json = serde_json::to_string(&s).unwrap();
4999        assert!(
5000            json.contains("\"1h\""),
5001            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
5002        );
5003        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5004        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
5005    }
5006
5007    #[test]
5008    fn validate_rejects_duplicate_child_caixa() {
5009        // Two children with the same :caixa render to two ComputeUnits
5010        // with the same name in the cluster's HelmRelease values —
5011        // one silently overwrites the other. Erlang/OTP's child_spec.id
5012        // is required-unique per supervisor; same set-not-multiset
5013        // discipline applied here as for :membros / :placement
5014        // :clusters / :entrada :paths.
5015        let s = SupervisorSpec {
5016            children: vec![
5017                child("worker", "^0.1", RestartPolicy::Permanent),
5018                child("cache", "^0.1", RestartPolicy::Transient),
5019                child("worker", "^0.2", RestartPolicy::Permanent),
5020            ],
5021            ..SupervisorSpec::default()
5022        };
5023        let err = s.validate().unwrap_err();
5024        assert!(
5025            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
5026            "got {err:?}"
5027        );
5028    }
5029
5030    #[test]
5031    fn validate_duplicate_child_diagnostic_names_first_collision() {
5032        // Iteration walks the :children list in declaration order —
5033        // the diagnostic names the first repeat, deterministically,
5034        // even when multiple names duplicate.
5035        let s = SupervisorSpec {
5036            children: vec![
5037                child("a", "^0.1", RestartPolicy::Permanent),
5038                child("b", "^0.1", RestartPolicy::Permanent),
5039                child("a", "^0.1", RestartPolicy::Permanent),
5040                child("b", "^0.1", RestartPolicy::Permanent),
5041            ],
5042            ..SupervisorSpec::default()
5043        };
5044        let err = s.validate().unwrap_err();
5045        assert!(
5046            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
5047            "got {err:?}"
5048        );
5049    }
5050
5051    // ── self-supervision cross-slot gate ──────────────────────────
5052
5053    #[test]
5054    fn validate_no_self_supervision_rejects_self_referential_child() {
5055        // A supervisor whose `:children` lists its own `:nome` is a
5056        // one-node reconciliation cycle — rejected, naming the parent.
5057        let children = vec![
5058            child("worker", "^0.1", RestartPolicy::Permanent),
5059            child("orquestra", "^0.1", RestartPolicy::Permanent),
5060        ];
5061        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
5062        assert!(
5063            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
5064            "got {err:?}"
5065        );
5066    }
5067
5068    #[test]
5069    fn validate_no_self_supervision_accepts_distinct_children() {
5070        // Positive control: distinct child names (including a child that
5071        // is itself a supervisor — nested trees are valid OTP) pass.
5072        let children = vec![
5073            child("worker", "^0.1", RestartPolicy::Permanent),
5074            child("sub-tree", "^0.1", RestartPolicy::Permanent),
5075        ];
5076        validate_no_self_supervision(&children, "orquestra").unwrap();
5077    }
5078
5079    #[test]
5080    fn validate_no_self_supervision_empty_children_is_ok() {
5081        // SimpleOneForOne / no-static-children supervisors have nothing
5082        // to self-reference — the gate is vacuously satisfied.
5083        validate_no_self_supervision(&[], "orquestra").unwrap();
5084    }
5085
5086    #[test]
5087    fn validate_simple_one_for_one_skips_uniqueness_check() {
5088        // SimpleOneForOne supervisors carry no static children — the
5089        // duplicate-child loop never runs. A zero-window declaration
5090        // on a SimpleOneForOne supervisor still trips the window check
5091        // (window applies to dynamic children too).
5092        let s = SupervisorSpec {
5093            estrategia: RestartStrategy::SimpleOneForOne,
5094            restart_window: None,
5095            children: vec![],
5096            ..SupervisorSpec::default()
5097        };
5098        s.validate().unwrap();
5099        let s_zero = SupervisorSpec {
5100            estrategia: RestartStrategy::SimpleOneForOne,
5101            restart_window: Some(Duration::ZERO),
5102            children: vec![],
5103            ..SupervisorSpec::default()
5104        };
5105        assert_eq!(
5106            s_zero.validate().unwrap_err(),
5107            SupervisorError::RestartWindowZero
5108        );
5109    }
5110
5111    #[test]
5112    fn validate_zero_window_runs_after_max_restarts_check() {
5113        // Pin the order: max_restarts == 0 fires before
5114        // restart_window == 0s, so an author with both wrong sees the
5115        // counter-axis diagnostic first (matches the order in the
5116        // struct and in the doc comment).
5117        let s = SupervisorSpec {
5118            max_restarts: 0,
5119            restart_window: Some(Duration::ZERO),
5120            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5121            ..SupervisorSpec::default()
5122        };
5123        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5124    }
5125
5126    #[test]
5127    fn round_trip_all_strategies() {
5128        for &strat in RestartStrategy::ALL {
5129            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
5130            // shape partition through the [`gen_platform::IsVariant`]
5131            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
5132            // predicate rather than the raw
5133            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
5134            // open-coded pattern-match — same closed-set-typed-enum
5135            // arm-discriminator dispatch discipline the sibling
5136            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
5137            // (915a934) extended onto its two paired positive / negated
5138            // `matches!` filter sites, and the sibling
5139            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
5140            // predicate convergence (766ec63) extended onto the M3 mesh-
5141            // slot per-`:placement` distribution-strategy `matches!`
5142            // discriminator axis. See the sibling
5143            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
5144            // fixture and the peer `manifest::tests::
5145            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
5146            // fixture — all three sites (the last unlifted
5147            // `matches!`-based arm-discriminator axis on the OTP-shape
5148            // supervisor sibling-restart-strategy closed-set typed enum,
5149            // acknowledged in 915a934's Prior-commits footnote as the
5150            // outstanding follow-up) now consult one typed dispatch on
5151            // the substrate primitive.
5152            let s = SupervisorSpec {
5153                estrategia: strat,
5154                children: if strat.is_simple_one_for_one() {
5155                    vec![]
5156                } else {
5157                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
5158                },
5159                ..SupervisorSpec::default()
5160            };
5161            let json = serde_json::to_string(&s).unwrap();
5162            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5163            assert_eq!(s, back);
5164        }
5165    }
5166
5167    #[test]
5168    fn round_trip_all_restart_policies() {
5169        for policy in [
5170            RestartPolicy::Permanent,
5171            RestartPolicy::Temporary,
5172            RestartPolicy::Transient,
5173        ] {
5174            let c = child("w", "^0.1", policy);
5175            let json = serde_json::to_string(&c).unwrap();
5176            let back: ChildSpec = serde_json::from_str(&json).unwrap();
5177            assert_eq!(c, back);
5178        }
5179    }
5180
5181    #[test]
5182    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
5183        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
5184        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
5185        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
5186        // is the only variant that satisfies `.is_simple_one_for_one()`;
5187        // every static-children-bearing arm (`OneForOne` / `OneForAll`
5188        // / `RestForOne`) returns `false`. This pin makes the partition
5189        // invariant load-bearing at caixa-core test time so a future
5190        // derive regression (a hole that returns `false` for
5191        // `SimpleOneForOne` too, or a byte-collision that flips a second
5192        // variant to `true`) trips here rather than laundering the arm
5193        // at the three test-fixture builder sites (a hole flips the
5194        // `SimpleOneForOne` fixture to carry a non-empty children list
5195        // and the subsequent `SupervisorSpec::validate` would refuse the
5196        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
5197        // a collision flips a peer strategy's fixture to carry an empty
5198        // children list and the subsequent `validate` would refuse with
5199        // [`SupervisorError::NoChildren`] — either way, the pin fires
5200        // here, at the derive site, rather than at the fixture-refusal
5201        // site far away). Peer of the sibling
5202        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
5203        // (915a934) pin on the M2 OTP-appup axis and the sibling
5204        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
5205        // pin on the M0 `:kind` axis.
5206        let cases: &[(RestartStrategy, bool)] = &[
5207            (RestartStrategy::OneForOne, false),
5208            (RestartStrategy::OneForAll, false),
5209            (RestartStrategy::RestForOne, false),
5210            (RestartStrategy::SimpleOneForOne, true),
5211        ];
5212        for (variant, expected) in cases {
5213            assert_eq!(
5214                variant.is_simple_one_for_one(),
5215                *expected,
5216                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
5217                 return {expected} (partition invariant on the \
5218                 IsVariant-derived arm-discriminator predicate — every \
5219                 test-fixture site that partitions the `:children` slot \
5220                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
5221                 off this typed dispatch, so a derive regression must \
5222                 surface here rather than at the fixture-refusal site)"
5223            );
5224        }
5225    }
5226
5227    #[test]
5228    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
5229        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
5230        // fixture-shape partition against the pre-lift
5231        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
5232        // pattern-match every test-fixture builder site previously
5233        // coupled to inline. Asserts the two projections agree byte-for-
5234        // byte on every arm of the enum, so a future derive regression
5235        // that flipped either predicate's arm-set would surface here at
5236        // caixa-core test time rather than at the three fixture-builder
5237        // sites (`supervisor::tests::round_trip_all_strategies`,
5238        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
5239        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
5240        // far from the derive site. Same peer-shape byte-identity pin
5241        // every sibling `IsVariant`-derive-routed convergence carries on
5242        // the substrate's closed-set typed-enum surface (peer of
5243        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
5244        // on the M2 OTP-appup axis).
5245        for &strat in RestartStrategy::ALL {
5246            let via_predicate = strat.is_simple_one_for_one();
5247            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
5248            assert_eq!(
5249                via_predicate, via_matches,
5250                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
5251                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
5252                 the pre-lift open-coded pattern and the \
5253                 IsVariant-derived predicate are the same axis, \
5254                 one typed dispatch"
5255            );
5256        }
5257    }
5258
5259    #[test]
5260    fn duration_codec_round_trip_canonical_units() {
5261        // Note the canonical-form rule: durations serialize to the
5262        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
5263        // "60s" — but the round-trip preserves the underlying Duration.
5264        let cases = [
5265            ("30s", Duration::from_secs(30)),
5266            ("5m", Duration::from_secs(300)),
5267            ("1h", Duration::from_secs(3600)),
5268            ("500ms", Duration::from_millis(500)),
5269        ];
5270        for (lit, dur) in cases {
5271            let s = SupervisorSpec {
5272                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5273                restart_window: Some(dur),
5274                ..SupervisorSpec::default()
5275            };
5276            let json = serde_json::to_string(&s).unwrap();
5277            assert!(
5278                json.contains(&format!("\"{lit}\"")),
5279                "expected \"{lit}\" in {json}"
5280            );
5281            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5282            assert_eq!(back.restart_window, Some(dur));
5283        }
5284    }
5285
5286    #[test]
5287    fn duration_canonicalizes_to_largest_unit() {
5288        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
5289        // typed Duration still equals 60s on the way back.
5290        let s = SupervisorSpec {
5291            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5292            restart_window: Some(Duration::from_secs(60)),
5293            ..SupervisorSpec::default()
5294        };
5295        let json = serde_json::to_string(&s).unwrap();
5296        assert!(json.contains("\"1m\""), "{json}");
5297        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5298        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
5299    }
5300
5301    #[test]
5302    fn three_child_one_for_one_validates() {
5303        let s = SupervisorSpec {
5304            estrategia: RestartStrategy::OneForOne,
5305            max_restarts: 5,
5306            restart_window: Some(Duration::from_secs(60)),
5307            children: vec![
5308                child("worker", "^0.1", RestartPolicy::Permanent),
5309                child("cache", "^0.1", RestartPolicy::Transient),
5310                child("scratch", "^0.1", RestartPolicy::Temporary),
5311            ],
5312        };
5313        s.validate().unwrap();
5314    }
5315
5316    #[test]
5317    fn json_uses_pascal_case_for_strategy_and_policy() {
5318        // Variant names are PascalCase by default in serde, matching
5319        // tatara-lisp's enum convention (`:estrategia OneForOne`).
5320        let c = child("w", "^0.1", RestartPolicy::Permanent);
5321        let json = serde_json::to_string(&c).unwrap();
5322        assert!(json.contains("\"Permanent\""));
5323        assert!(!json.contains("\"permanent\""));
5324
5325        let s = SupervisorSpec {
5326            estrategia: RestartStrategy::OneForOne,
5327            children: vec![c],
5328            ..SupervisorSpec::default()
5329        };
5330        let json = serde_json::to_string(&s).unwrap();
5331        assert!(json.contains("\"estrategia\":\"OneForOne\""));
5332    }
5333
5334    // ── shared duration codec: integer-magnitude canonical-form gate ──
5335    //
5336    // The gate lifts the discipline `crate::limits::parse_duration`
5337    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
5338    // the shared codec backing the remaining three typed-duration
5339    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
5340    // `:politicas :circuit-breaker :window`. Every magnitude `render`
5341    // emits is a non-negative integer with no decimal point and no
5342    // leading sign, so the codec's accepted set must match for
5343    // serialize/deserialize to round-trip without canonical-form
5344    // drift.
5345
5346    #[test]
5347    fn parse_accepts_integer_canonical_units() {
5348        // Pin the happy-path: every canonical author shape `render`
5349        // ever emits parses to the same `Duration` value, so the
5350        // codec's accepted set is at least a superset of its emitted
5351        // set on the canonical-unit axis.
5352        for (lit, dur) in [
5353            ("30s", Duration::from_secs(30)),
5354            ("500ms", Duration::from_millis(500)),
5355            ("2m", Duration::from_secs(120)),
5356            ("1h", Duration::from_secs(3600)),
5357            ("0s", Duration::ZERO),
5358        ] {
5359            assert_eq!(
5360                duration_codec::parse(lit).unwrap(),
5361                dur,
5362                "parse({lit:?}) should be {dur:?}"
5363            );
5364        }
5365    }
5366
5367    #[test]
5368    fn parse_accepts_bare_integer_as_seconds() {
5369        // The `"s" | ""` arm: a bare integer with no unit is read as
5370        // seconds. Pin this so the unit-empty form keeps parsing (it
5371        // renders to `"<n>s"` on serialize — that's a unit-choice
5372        // drift the integer-magnitude gate does NOT close, matching
5373        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
5374        // the peer `:limits :memory` codec).
5375        assert_eq!(
5376            duration_codec::parse("30").unwrap(),
5377            Duration::from_secs(30)
5378        );
5379    }
5380
5381    #[test]
5382    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
5383        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
5384        // on first serialize — DRIFT. The integer-magnitude gate names
5385        // the offending `"1.5"` verbatim and points at the canonical
5386        // remediation `"1500ms"`.
5387        let err = duration_codec::parse("1.5s").unwrap_err();
5388        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
5389        assert!(
5390            err.contains("not a non-negative integer"),
5391            "missing canonical-form reason in {err:?}"
5392        );
5393        assert!(
5394            err.contains("\"1500ms\""),
5395            "missing canonical-form remediation in {err:?}"
5396        );
5397    }
5398
5399    #[test]
5400    fn parse_rejects_decimal_shaped_integer_seconds() {
5401        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
5402        // `1s` exactly, so the round-trip looks correct — but the
5403        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
5404        // decimal-shape-with-integer-value form so author intent is
5405        // never silently rewritten.
5406        let err = duration_codec::parse("1.0s").unwrap_err();
5407        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
5408        assert!(
5409            err.contains("not a non-negative integer"),
5410            "missing canonical-form reason in {err:?}"
5411        );
5412    }
5413
5414    #[test]
5415    fn parse_rejects_half_unit_minute() {
5416        // `"0.5m"` is the unit-fraction footgun — author writes a
5417        // human-readable half-minute, serde silently rewrites to
5418        // `"30s"` on next emit. The gate names the offending
5419        // magnitude `"0.5"` and points at the integer-in-smaller-unit
5420        // form.
5421        let err = duration_codec::parse("0.5m").unwrap_err();
5422        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
5423        assert!(
5424            err.contains("\"30s\""),
5425            "missing canonical-form remediation in {err:?}"
5426        );
5427    }
5428
5429    #[test]
5430    fn parse_rejects_leading_plus_sign() {
5431        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
5432        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
5433        // cleanly to 30s and round-tripped to `"30s"` on next emit
5434        // (DRIFT). The digit-only gate closes the leading-sign class
5435        // first; the diagnostic names `"+30"` verbatim.
5436        let err = duration_codec::parse("+30s").unwrap_err();
5437        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
5438        assert!(
5439            err.contains("not a non-negative integer"),
5440            "missing canonical-form reason in {err:?}"
5441        );
5442    }
5443
5444    #[test]
5445    fn parse_rejects_leading_minus_sign() {
5446        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
5447        // rejected with `"negative duration in \"-30s\""`. Under the
5448        // integer-magnitude gate the diagnostic is unified — `-30` is
5449        // non-digit-only, f64-numeric, and surfaces with the canonical-
5450        // form reason (no leading `+` / `-` sign) naming the offending
5451        // `"-30"` verbatim. Same diagnostic shape as every other
5452        // rejected non-integer magnitude.
5453        let err = duration_codec::parse("-30s").unwrap_err();
5454        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
5455        assert!(
5456            err.contains("not a non-negative integer"),
5457            "missing canonical-form reason in {err:?}"
5458        );
5459    }
5460
5461    #[test]
5462    fn parse_garbage_still_falls_through_to_bad_magnitude() {
5463        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
5464        // through to the narrower "bad duration magnitude" arm — the
5465        // canonical-form diagnostic is reserved for the parser-shape
5466        // footgun case, not the "not a number at all" case. Same
5467        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
5468        // the peer `:limits :memory` codec.
5469        let err = duration_codec::parse("--1s").unwrap_err();
5470        assert!(
5471            err.contains("bad duration magnitude"),
5472            "expected bad-magnitude wording in {err:?}"
5473        );
5474    }
5475
5476    #[test]
5477    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
5478        // The accepted set is now closed under `u64`-exact integer
5479        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
5480        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
5481        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
5482        // possible. Pin the integer-exact arms across the four unit
5483        // suffixes so a future refactor that reaches back for f64
5484        // (`from_secs_f64`, `mul_f64`) surfaces here.
5485        assert_eq!(
5486            duration_codec::parse("3600s").unwrap(),
5487            Duration::from_secs(3600)
5488        );
5489        assert_eq!(
5490            duration_codec::parse("60m").unwrap(),
5491            Duration::from_secs(3600)
5492        );
5493        assert_eq!(
5494            duration_codec::parse("1h").unwrap(),
5495            Duration::from_secs(3600)
5496        );
5497        assert_eq!(
5498            duration_codec::parse("999ms").unwrap(),
5499            Duration::from_millis(999)
5500        );
5501    }
5502
5503    #[test]
5504    fn restart_window_serde_rejects_fractional_seconds() {
5505        // The shared codec backs `SupervisorSpec::restart_window`
5506        // (`with = "duration_codec"`) — so the gate applies on serde
5507        // deserialize for the typed Supervisor slot. A
5508        // `{"restartWindow":"1.5s"}` payload that previously round-
5509        // tripped to a different canonical string on next serialize
5510        // is now refused at deserialize with the integer-magnitude
5511        // diagnostic.
5512        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5513            "restartWindow":"1.5s",
5514            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5515        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5516        let msg = err.to_string();
5517        assert!(
5518            msg.contains("not a non-negative integer"),
5519            "expected integer-magnitude diagnostic in {msg:?}"
5520        );
5521        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
5522    }
5523
5524    #[test]
5525    fn restart_window_serde_rejects_leading_plus() {
5526        // The `u64::from_str` leading-`+` permissiveness gap that
5527        // motivated the digit-only gate (the `f64`-side accepted
5528        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
5529        // is now closed on the shared codec — surfaces as a structured
5530        // diagnostic at the serde layer for every typed-duration slot.
5531        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5532            "restartWindow":"+30s",
5533            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5534        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5535        let msg = err.to_string();
5536        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
5537        assert!(
5538            msg.contains("not a non-negative integer"),
5539            "missing canonical-form reason in {msg:?}"
5540        );
5541    }
5542
5543    #[test]
5544    fn parse_rejects_leading_zero_magnitude() {
5545        // `"030s"` is digit-only, so the existing non-digit-only / sign
5546        // / fractional arm doesn't catch it — `u64::from_str("030")`
5547        // returns `Ok(30)`, so before this gate `"030s"` parsed to
5548        // `Duration::from_secs(30)` and round-tripped through `render`
5549        // to `"30s"` — a *different* canonical string on the next emit,
5550        // breaking the THEORY.md Part V render-determinism contract
5551        // exactly the way `"+30s"` did before the leading-`+` arm
5552        // landed. Peer with the `rate_limit_codec` leading-zero arm
5553        // (4f46830) on the same canonical-form-drift axis.
5554        let err = duration_codec::parse("030s").unwrap_err();
5555        assert!(
5556            err.contains("non-canonical leading zero"),
5557            "expected leading-zero diagnostic in {err:?}"
5558        );
5559        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5560        assert!(
5561            err.contains("\"30s\""),
5562            "missing canonical-form remediation in {err:?}"
5563        );
5564        assert!(
5565            err.contains("THEORY.md"),
5566            "missing render-determinism citation in {err:?}"
5567        );
5568    }
5569
5570    #[test]
5571    fn parse_rejects_multi_digit_zero_magnitude() {
5572        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
5573        // digit-only, parse losslessly to `Duration::ZERO`, but render
5574        // back to `"0s"` (the single-byte canonical form) on the next
5575        // emit. The leading-zero arm refuses the drift class at the
5576        // codec layer; the semantic-zero gate downstream
5577        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
5578        // the single-byte canonical form `"0s"` separately on the
5579        // typed-validate layer.
5580        let err = duration_codec::parse("00s").unwrap_err();
5581        assert!(
5582            err.contains("non-canonical leading zero"),
5583            "expected leading-zero diagnostic in {err:?}"
5584        );
5585        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
5586    }
5587
5588    #[test]
5589    fn parse_rejects_leading_zero_per_hour_window() {
5590        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
5591        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
5592        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
5593        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
5594        // `h` / bare-integer-as-seconds) inherits the same gate.
5595        let err = duration_codec::parse("01h").unwrap_err();
5596        assert!(
5597            err.contains("non-canonical leading zero"),
5598            "expected leading-zero diagnostic in {err:?}"
5599        );
5600        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
5601    }
5602
5603    #[test]
5604    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
5605        // The `parse_accepts_bare_integer_as_seconds` happy-path
5606        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
5607        // multi-byte starts-with-`0`, parses losslessly to
5608        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
5609        // bare-integer surface accepts permissive unit-empty
5610        // shorthand but still must reject leading-zero padding.
5611        let err = duration_codec::parse("030").unwrap_err();
5612        assert!(
5613            err.contains("non-canonical leading zero"),
5614            "expected leading-zero diagnostic in {err:?}"
5615        );
5616        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5617    }
5618
5619    #[test]
5620    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
5621        // The codec-layer / typed-validate-layer boundary: `"0s"` /
5622        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
5623        // each round-trips losslessly through `render`
5624        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
5625        // accepts them. The downstream semantic-zero gates
5626        // (`SupervisorError::ZeroRestartWindow`,
5627        // `AplicacaoError::PolicyTimeoutZero`,
5628        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
5629        // zero-magnitude authoring at the typed-validate layer above,
5630        // peer with the `rate_limit_codec` codec-layer / typed-
5631        // validate-layer partition for `"0/s"`.
5632        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
5633        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
5634        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
5635    }
5636
5637    #[test]
5638    fn parse_accepts_canonical_magnitude_with_leading_one() {
5639        // The complementary boundary: a future tightening cannot
5640        // drift into rejecting valid canonical magnitudes that
5641        // happen to start with `1` (or any digit `[1-9]`). Pin
5642        // every canonical-unit suffix so the leading-zero arm
5643        // remains strictly narrower than the digit-only arm.
5644        assert_eq!(
5645            duration_codec::parse("100ms").unwrap(),
5646            Duration::from_millis(100)
5647        );
5648        assert_eq!(
5649            duration_codec::parse("100s").unwrap(),
5650            Duration::from_secs(100)
5651        );
5652        assert_eq!(
5653            duration_codec::parse("10m").unwrap(),
5654            Duration::from_secs(600)
5655        );
5656        assert_eq!(
5657            duration_codec::parse("10h").unwrap(),
5658            Duration::from_secs(36_000)
5659        );
5660    }
5661
5662    #[test]
5663    fn restart_window_serde_rejects_leading_zero() {
5664        // The shared codec backs `SupervisorSpec::restart_window`
5665        // (`with = "duration_codec"`) — so the leading-zero arm
5666        // applies on serde deserialize for the typed Supervisor slot.
5667        // A `{"restartWindow":"030s"}` payload that previously round-
5668        // tripped to a different canonical string on next serialize
5669        // is now refused at deserialize with the leading-zero
5670        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
5671        // / `restart_window_serde_rejects_fractional_seconds` on the
5672        // same canonical-form-drift axis.
5673        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5674            "restartWindow":"030s",
5675            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5676        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5677        let msg = err.to_string();
5678        assert!(
5679            msg.contains("non-canonical leading zero"),
5680            "expected leading-zero diagnostic in {msg:?}"
5681        );
5682        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
5683    }
5684
5685    #[test]
5686    fn parse_rejects_leading_whitespace() {
5687        // `" 30s"` — the canonical paste-from-aligned-doc /
5688        // paste-from-YAML-quoted-plain-scalar footgun. Before this
5689        // gate the top-level `s.trim()` at parse entry silently ate
5690        // the leading space and parsed the value to
5691        // `Duration::from_secs(30)`, which then round-tripped through
5692        // `render` to `"30s"` (a *different* canonical string on the
5693        // next emit) — the exact canonical-form-drift class the
5694        // leading-`+` / leading-zero arms already close, extended
5695        // to the whitespace-byte class. Peer with the sibling
5696        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
5697        // the M3 `:politicas` axis.
5698        let err = duration_codec::parse(" 30s").unwrap_err();
5699        assert!(
5700            err.contains("contains whitespace byte"),
5701            "expected whitespace diagnostic in {err:?}"
5702        );
5703        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5704        assert!(
5705            err.contains("THEORY.md"),
5706            "missing render-determinism contract citation in {err:?}"
5707        );
5708    }
5709
5710    #[test]
5711    fn parse_rejects_trailing_whitespace() {
5712        // `"30s "` — the canonical shell-history / trailing-space
5713        // paste footgun. Before this gate the top-level `s.trim()`
5714        // silently ate the trailing space and parsed to
5715        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
5716        // next emit — same canonical-form drift as the leading-space
5717        // sibling, closed on the same whitespace-byte arm.
5718        let err = duration_codec::parse("30s ").unwrap_err();
5719        assert!(
5720            err.contains("contains whitespace byte"),
5721            "expected whitespace diagnostic in {err:?}"
5722        );
5723        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5724    }
5725
5726    #[test]
5727    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
5728        // `"30 s"` — the canonical typographically-spaced author
5729        // shape (the same idiom every prose reference to a duration
5730        // renders as, mistakenly retained when the value is pasted
5731        // into a codec-shaped slot). Before this gate the per-part
5732        // `num_part.trim()` / `unit.trim()` calls silently ate the
5733        // whitespace between the magnitude and the unit and parsed
5734        // the value to `Duration::from_secs(30)`, round-tripping to
5735        // `"30s"` — the codec's *internal* whitespace-tolerance
5736        // vector, orthogonal to the leading / trailing surface but
5737        // the same canonical-form-drift class. Pins the arm as
5738        // strictly stronger than the pre-existing top-level
5739        // `s.trim()` behavior: it fires on whitespace anywhere in
5740        // the value, not just at the string boundary.
5741        let err = duration_codec::parse("30 s").unwrap_err();
5742        assert!(
5743            err.contains("contains whitespace byte"),
5744            "expected whitespace diagnostic in {err:?}"
5745        );
5746        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5747    }
5748
5749    #[test]
5750    fn parse_rejects_tab_byte() {
5751        // `"\t30s"` — the canonical paste-from-indented-doc /
5752        // paste-from-YAML-block-scalar footgun where a tab byte leads
5753        // the magnitude. Pins that the gate covers tab (`0x09`) as
5754        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
5755        // members and both would be silently swallowed by `s.trim()`
5756        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
5757        // space alone to the full ASCII-whitespace set (space `0x20`,
5758        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
5759        // the tab arm as a representative of the non-space members.
5760        let err = duration_codec::parse("\t30s").unwrap_err();
5761        assert!(
5762            err.contains("contains whitespace byte"),
5763            "expected whitespace diagnostic in {err:?}"
5764        );
5765        assert!(
5766            err.contains("0x09"),
5767            "missing offending tab byte in {err:?}"
5768        );
5769    }
5770
5771    #[test]
5772    fn restart_window_serde_rejects_whitespace() {
5773        // The shared codec backs `SupervisorSpec::restart_window`
5774        // (`with = "duration_codec"`) — so the whitespace arm
5775        // applies on serde deserialize for the typed Supervisor slot.
5776        // A `{"restartWindow":" 30s"}` payload that previously round-
5777        // tripped to a different canonical string on next serialize
5778        // is now refused at deserialize with the whitespace-byte
5779        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
5780        // / `restart_window_serde_rejects_leading_plus` /
5781        // `restart_window_serde_rejects_fractional_seconds` on the
5782        // same canonical-form-drift axis.
5783        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5784            "restartWindow":" 30s",
5785            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5786        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5787        let msg = err.to_string();
5788        assert!(
5789            msg.contains("contains whitespace byte"),
5790            "expected whitespace diagnostic in {msg:?}"
5791        );
5792        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
5793    }
5794
5795    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
5796    //
5797    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
5798    // duration codec — closes the strictly-complementary class the
5799    // byte-scan cannot see, through the lifted
5800    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
5801    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
5802    // and `:politicas :circuit-breaker :window` simultaneously via
5803    // this shared codec.
5804
5805    #[test]
5806    fn duration_codec_parse_rejects_leading_nbsp() {
5807        // NBSP prefix — the strictly-complementary drift class the
5808        // ASCII byte-scan cannot see. `str::trim` strips it silently
5809        // and the value drifts to `"30s"` on next serialize.
5810        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
5811        assert!(
5812            err.contains("non-ASCII Unicode whitespace character"),
5813            "expected non-ASCII whitespace diagnostic in {err:?}"
5814        );
5815        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
5816    }
5817
5818    #[test]
5819    fn duration_codec_parse_rejects_trailing_line_separator() {
5820        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
5821        // footgun.
5822        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
5823        assert!(
5824            err.contains("non-ASCII Unicode whitespace character"),
5825            "expected non-ASCII whitespace diagnostic in {err:?}"
5826        );
5827        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
5828    }
5829
5830    #[test]
5831    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
5832        // Positive-control pin: every ASCII-only canonical form the
5833        // renderer emits stays accepted through the new arm.
5834        assert_eq!(
5835            duration_codec::parse("30s").unwrap(),
5836            Duration::from_secs(30)
5837        );
5838        assert_eq!(
5839            duration_codec::parse("500ms").unwrap(),
5840            Duration::from_millis(500)
5841        );
5842        assert_eq!(
5843            duration_codec::parse("1h").unwrap(),
5844            Duration::from_secs(3600)
5845        );
5846    }
5847
5848    #[test]
5849    fn restart_window_serde_rejects_non_ascii_whitespace() {
5850        // The shared codec backs `SupervisorSpec::restart_window` — so
5851        // the new non-ASCII Unicode whitespace arm applies on serde
5852        // deserialize for the typed Supervisor slot. A
5853        // `{"restartWindow":" 30s"}` payload that previously
5854        // survived the ASCII byte-scan (only ASCII whitespace was
5855        // refused) is now refused at deserialize with the
5856        // non-ASCII-whitespace-and-codepoint diagnostic.
5857        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
5858            \"restartWindow\":\"\u{00A0}30s\",\
5859            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
5860        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5861        let msg = err.to_string();
5862        assert!(
5863            msg.contains("non-ASCII Unicode whitespace character"),
5864            "expected non-ASCII whitespace diagnostic in {msg:?}"
5865        );
5866        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
5867    }
5868
5869    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
5870
5871    #[test]
5872    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
5873        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
5874        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
5875        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
5876        // name the exact camelCase JSON keys the
5877        // `#[serde(rename_all = "camelCase")]` attribute on
5878        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
5879        // field carries `Some(_)` / non-empty) and pin that each canonical
5880        // byte-sequence appears verbatim in the JSON — a future accidental
5881        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
5882        // name flip at the derive attribute (any of which would silently
5883        // break every downstream JSON consumer that reaches for one of the
5884        // four consts via `Value::get(...)`) surfaces here as a build-time
5885        // test failure at `supervisor.rs`, not as an apply-time
5886        // `.get(<stale-canonical-const>)` returning `None` far from the
5887        // derive-attr drift's commit. Peer with the sibling
5888        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
5889        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
5890        // M2 typed-slot family established, extended here to close the
5891        // top-level Supervisor axis.
5892        let spec = SupervisorSpec {
5893            estrategia: RestartStrategy::OneForOne,
5894            max_restarts: 5,
5895            restart_window: Some(Duration::from_secs(60)),
5896            children: vec![ChildSpec {
5897                caixa: "w".into(),
5898                versao: "^0.1".into(),
5899                restart: RestartPolicy::Permanent,
5900            }],
5901        };
5902        let json = serde_json::to_string(&spec).unwrap();
5903        for key in [
5904            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5905            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5906            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5907            crate::render::SUPERVISOR_KEY_CHILDREN,
5908        ] {
5909            let quoted = format!("\"{key}\"");
5910            assert!(
5911                json.contains(&quoted),
5912                "serialized SupervisorSpec must carry the lifted \
5913                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
5914                 the JSON emission (got: {json})",
5915            );
5916        }
5917    }
5918
5919    #[test]
5920    fn supervisor_key_consts_are_pairwise_distinct() {
5921        // Cross-axis drift-detection pin: a future collapse of two
5922        // canonical top-level byte-strings onto the same value (e.g. an
5923        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
5924        // also read `"estrategia"`) would silently reroute every
5925        // downstream probe on one axis onto the sibling axis's overlay
5926        // entry and pass every propagation-probe test that expected only
5927        // the stale axis's value. Peer of the sibling four-way distinct
5928        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
5929        let all = [
5930            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5931            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5932            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5933            crate::render::SUPERVISOR_KEY_CHILDREN,
5934        ];
5935        for (i, a) in all.iter().enumerate() {
5936            for b in all.iter().skip(i + 1) {
5937                assert_ne!(
5938                    a, b,
5939                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
5940                     canonical byte-sequences — got `{a}` == `{b}`",
5941                );
5942            }
5943        }
5944    }
5945
5946    #[test]
5947    fn supervisor_key_consts_are_lower_camel_case_shape() {
5948        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
5949        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
5950        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
5951        // capital, no whitespace / dots) — the canonical shape the
5952        // `#[serde(rename_all = "camelCase")]` derive produces on
5953        // `SupervisorSpec`. A future flip to a non-camelCase attribute
5954        // at the derive surfaces both here (this test fails on the
5955        // stale-constant shape) and at
5956        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
5957        // (that test fails on the mismatch between const and derive).
5958        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
5959        // (d8b8b4f) on the sibling M2 `:limits` axis.
5960        for key in [
5961            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5962            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5963            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5964            crate::render::SUPERVISOR_KEY_CHILDREN,
5965        ] {
5966            assert!(
5967                !key.is_empty(),
5968                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
5969            );
5970            let first = key.chars().next().unwrap();
5971            assert!(
5972                first.is_ascii_lowercase(),
5973                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
5974                 (got {key:?}, leads with {first:?})",
5975            );
5976            assert!(
5977                key.chars().all(|c| c.is_ascii_alphanumeric()),
5978                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
5979                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
5980            );
5981        }
5982    }
5983
5984    #[test]
5985    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
5986        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
5987        // (camelCase JSON keys, no leading colon) must never collide
5988        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
5989        // consts (kebab-case author-facing labels with leading colon)
5990        // that sit next to them at `caixa_core::render`. Both families
5991        // cover the same four typed Supervisor slots on two distinct
5992        // axes (author-side kebab vs renderer-side camelCase);
5993        // collapsing either family onto the other's byte-shape would
5994        // silently reroute the render-side probe onto the author-facing
5995        // surface, or vice versa. Peer of the byte-distinctness
5996        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
5997        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
5998        let pairs = [
5999            (
6000                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6001                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
6002            ),
6003            (
6004                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6005                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
6006            ),
6007            (
6008                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6009                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
6010            ),
6011            (
6012                crate::render::SUPERVISOR_KEY_CHILDREN,
6013                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
6014            ),
6015        ];
6016        for (json_key, author_key) in pairs {
6017            assert_ne!(
6018                json_key, author_key,
6019                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
6020                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
6021                 got JSON `{json_key}` == author `{author_key}`",
6022            );
6023        }
6024    }
6025
6026    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
6027
6028    #[test]
6029    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
6030        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
6031        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
6032        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
6033        // keys the `#[serde(rename_all = "camelCase")]` attribute on
6034        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
6035        // pin that each canonical byte-sequence appears verbatim in the
6036        // JSON — a future accidental `rename_all = "snake_case"` /
6037        // `"kebab-case"` / verbatim-field-name flip at the derive
6038        // attribute (any of which would silently break every downstream
6039        // JSON consumer that reaches for one of the three consts via
6040        // `Value::get(...)`) surfaces here as a build-time test failure at
6041        // `supervisor.rs`, not as an apply-time
6042        // `.get(<stale-canonical-const>)` returning `None` far from the
6043        // derive-attr drift's commit. Peer with the enclosing
6044        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6045        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
6046        // discipline the SupervisorSpec top-level lift established,
6047        // extended here to the sibling per-`:children` entry `ChildSpec`
6048        // derive so the last M2 typed-struct sub-block
6049        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
6050        // surface without a lifted serde-key peer joins the substrate's
6051        // "one canonical byte-string per typed serialized-key axis"
6052        // discipline.
6053        let c = ChildSpec {
6054            caixa: "worker".into(),
6055            versao: "^0.1".into(),
6056            restart: RestartPolicy::Permanent,
6057        };
6058        let json = serde_json::to_string(&c).unwrap();
6059        for key in [
6060            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6061            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6062            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6063        ] {
6064            let quoted = format!("\"{key}\"");
6065            assert!(
6066                json.contains(&quoted),
6067                "serialized ChildSpec must carry the lifted \
6068                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
6069                 in the JSON emission (got: {json})",
6070            );
6071        }
6072    }
6073
6074    #[test]
6075    fn supervisor_child_key_consts_are_pairwise_distinct() {
6076        // Cross-axis drift-detection pin: a future collapse of two
6077        // canonical `ChildSpec` per-entry byte-strings onto the same
6078        // value (e.g. an accidental copy-paste flip of
6079        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
6080        // silently reroute every downstream probe on one axis onto the
6081        // sibling axis's overlay entry and pass every propagation-probe
6082        // test that expected only the stale axis's value. Peer of the
6083        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
6084        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
6085        // pair (ce80ca0).
6086        let all = [
6087            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6088            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6089            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6090        ];
6091        for (i, a) in all.iter().enumerate() {
6092            for b in all.iter().skip(i + 1) {
6093                assert_ne!(
6094                    a, b,
6095                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
6096                     distinct canonical byte-sequences — got `{a}` == `{b}`",
6097                );
6098            }
6099        }
6100    }
6101
6102    #[test]
6103    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
6104        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
6105        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6106        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6107        // capital, no whitespace / dots) — the canonical shape the
6108        // `#[serde(rename_all = "camelCase")]` derive produces on
6109        // `ChildSpec`. A future flip to a non-camelCase attribute at the
6110        // derive surfaces both here (this test fails on the
6111        // stale-constant shape) and at
6112        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
6113        // (that test fails on the mismatch between const and derive).
6114        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
6115        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
6116        for key in [
6117            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6118            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6119            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6120        ] {
6121            assert!(
6122                !key.is_empty(),
6123                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
6124            );
6125            let first = key.chars().next().unwrap();
6126            assert!(
6127                first.is_ascii_lowercase(),
6128                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
6129                 byte (got {key:?}, leads with {first:?})",
6130            );
6131            assert!(
6132                key.chars().all(|c| c.is_ascii_alphanumeric()),
6133                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
6134                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6135            );
6136        }
6137    }
6138
6139    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
6140
6141    #[test]
6142    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
6143        // The fail-before-pass-after pin: pre-lift there was no
6144        // single-source binding between the [`RestartStrategy`] variant
6145        // name the un-`rename`d `Serialize` derive emits under
6146        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
6147        // every downstream cluster-side dispatcher (the future
6148        // wasm-operator's per-supervisor sibling-restart branch, the
6149        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
6150        // admission-time enum-arm bind, the `caixa-operator`'s
6151        // hierarchical reconciliation scheduler's per-strategy fan-out)
6152        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
6153        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
6154        // override, or a variant rename in the source — would silently
6155        // rebrand the emitted scalar under one spelling while every
6156        // downstream dispatcher still probed the other, with the failure
6157        // surfacing at the operator's reconcile posture (subtrees coming
6158        // up under the `default()` `OneForOne` arm rather than the typed
6159        // slot's declared strategy — a bad child would then only take
6160        // itself down instead of the sibling set the author intended, so
6161        // shared-state children fall out of sync) far from the source
6162        // rebrand commit and with no field naming the drift. Pinning the
6163        // two paths (the `Serialize` derive's serialized string AND the
6164        // [`RestartStrategy::as_str`] helper) to the same four lifted
6165        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
6166        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
6167        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
6168        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
6169        // byte-strings makes any future drift on either endpoint fail
6170        // here at caixa-core build time. Peer of the M3
6171        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
6172        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
6173        // three-path-convergence discipline, extended to close the
6174        // OTP-shaped per-supervisor sibling-restart axis.
6175        for (variant, expected) in [
6176            (
6177                RestartStrategy::OneForOne,
6178                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6179            ),
6180            (
6181                RestartStrategy::OneForAll,
6182                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6183            ),
6184            (
6185                RestartStrategy::RestForOne,
6186                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6187            ),
6188            (
6189                RestartStrategy::SimpleOneForOne,
6190                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6191            ),
6192        ] {
6193            let json = serde_json::to_string(&variant).unwrap();
6194            assert_eq!(
6195                json,
6196                format!("\"{expected}\""),
6197                "RestartStrategy::{variant:?} must serialize to {expected:?}"
6198            );
6199            assert_eq!(
6200                variant.as_str(),
6201                expected,
6202                "RestartStrategy::{variant:?}.as_str() must return the lifted \
6203                 SUPERVISOR_ESTRATEGIA_* constant"
6204            );
6205        }
6206    }
6207
6208    #[test]
6209    fn supervisor_estrategia_consts_are_pairwise_distinct() {
6210        // Cross-arm drift-detection pin: a future collapse of two
6211        // canonical variant byte-strings onto the same value (e.g. an
6212        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
6213        // to also read `"OneForOne"`) would silently reroute every
6214        // downstream operator's per-strategy dispatch onto the sibling
6215        // arm's reconcile branch and pass every propagation-probe test
6216        // that expected only the stale arm's value — the mis-strategied
6217        // subtree would come up with the wrong sibling-restart posture
6218        // on every subsequent failure. Peer of the sibling four-way
6219        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
6220        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
6221        let all = [
6222            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6223            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6224            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6225            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6226        ];
6227        for (i, a) in all.iter().enumerate() {
6228            for (j, b) in all.iter().enumerate() {
6229                if i != j {
6230                    assert_ne!(
6231                        a, b,
6232                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
6233                         — got duplicate {a:?} at indices {i} and {j}",
6234                    );
6235                }
6236            }
6237        }
6238    }
6239
6240    #[test]
6241    fn restart_strategy_display_routes_through_as_str_helper() {
6242        // The fail-before-pass-after pin on the first half of the
6243        // three-path convergence: pre-convergence the sibling
6244        // OTP-shape typed enum [`RestartStrategy`] carried a
6245        // [`std::fmt::Display`] surface via its
6246        // `#[discriminant(also_display)]` gen-platform derive route,
6247        // which arrived kebab-case as `"one-for-one"` /
6248        // `"one-for-all"` / `"rest-for-one"` /
6249        // `"simple-one-for-one"` while the wire format ran as
6250        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
6251        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
6252        // Every consumer reaching for a strategy byte-string past the
6253        // wire format had to pick between three paths
6254        // ([`RestartStrategy::as_str`], the `Serialize` derive's
6255        // serialized string, or `format!("{v}")` on the
6256        // discriminant-Display route), any two of which a future
6257        // variant rename or `#[serde(rename_all = "kebab-case")]`
6258        // attribute would silently desynchronize. Wiring
6259        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
6260        // closes the third path: every `format!("{v}")` call reaches
6261        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6262        // const the wire format and the [`RestartStrategy::as_str`]
6263        // helper already route through, so a future variant rename
6264        // lands at exactly one place. Pin the routing here so a future
6265        // `impl std::fmt::Display for RestartStrategy`
6266        // reimplementation that hand-rolls the arms instead of
6267        // delegating to [`RestartStrategy::as_str`] fails at
6268        // caixa-core build time. Peer of the M3
6269        // `placement_strategy_display_routes_through_as_str_helper`
6270        // (cc8f749) which the M3 axis converged first.
6271        for &variant in RestartStrategy::ALL {
6272            assert_eq!(
6273                variant.to_string(),
6274                variant.as_str(),
6275                "RestartStrategy::{variant:?} Display must route through \
6276                 RestartStrategy::as_str (single source of truth: the lifted \
6277                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
6278            );
6279        }
6280    }
6281
6282    #[test]
6283    fn restart_strategy_display_matches_serialized_wire_byte_string() {
6284        // The fail-before-pass-after pin on the second half of the
6285        // three-path convergence: `Display` (user-facing text) agrees
6286        // byte-for-byte with the `Serialize` derive's wire format
6287        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
6288        // scalar) on every variant. Pre-convergence the two paths
6289        // were structurally independent — a future
6290        // `#[serde(rename_all = "kebab-case")]` attribute on the
6291        // enum would silently rebrand the emitted wire scalar
6292        // (`one-for-one`, `one-for-all`, `rest-for-one`,
6293        // `simple-one-for-one`) while every consumer that
6294        // pretty-prints the strategy (the future wasm-operator's
6295        // per-supervisor sibling-restart-strategy diagnostic line,
6296        // the future `feira app graph` per-supervisor strategy line,
6297        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
6298        // materializer's admission-webhook rejection body) would
6299        // still emit the PascalCase form the `as_str` / `Display`
6300        // route returns, with the mismatch surfacing at consumer
6301        // parse time / operator dispatch time far from the source
6302        // rebrand commit. Pin the two paths byte-for-byte here so any
6303        // future serde-attribute or variant-rename drift is a
6304        // caixa-core-build-time test failure at this call, not a
6305        // silent per-consumer dispatch miss. Peer of the M3
6306        // `placement_strategy_display_matches_serialized_wire_byte_string`
6307        // (cc8f749) which the M3 axis converged first.
6308        for &variant in RestartStrategy::ALL {
6309            let wire = serde_json::to_string(&variant).unwrap();
6310            let unquoted = wire
6311                .strip_prefix('"')
6312                .and_then(|s| s.strip_suffix('"'))
6313                .expect("serialized RestartStrategy is a JSON string");
6314            assert_eq!(
6315                variant.to_string(),
6316                unquoted,
6317                "RestartStrategy::{variant:?} Display byte-string must match the \
6318                 Serialize derive's wire byte-string (three-path convergence: \
6319                 Display + as_str + Serialize all resolve to the same \
6320                 SUPERVISOR_ESTRATEGIA_* const)"
6321            );
6322        }
6323    }
6324
6325    #[test]
6326    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
6327        // Fail-before-pass-after byte-parity pin on the lifted
6328        // `impl AsRef<str> for RestartStrategy` — asserts the
6329        // standard-library trait impl and the substrate-primitive
6330        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
6331        // to the same `&str` per instance across the four-arm
6332        // closed set, so any future silent detour that routes the
6333        // impl through a divergent projection (a per-arm inline
6334        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
6335        // re-inlining that opens a compile-time link to the un-lifted
6336        // arm-literal, a swap onto the kebab-case
6337        // [`gen_platform::Discriminant`] catalog identity that would
6338        // collide the wire axis with the dispatcher-catalog axis) trips
6339        // at caixa-core test time under `PartialEq` rather than at a
6340        // downstream `impl AsRef<str>`-bound consumer's silent split.
6341        // Sweeps every one of the four arms
6342        // [`RestartStrategy::ALL`] carries so no arm's projection is
6343        // covered only by the sibling wire-format `Serialize` derive
6344        // path. Peer of the sibling
6345        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
6346        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
6347        // top-level `:versao` typed newtype — the two pins together
6348        // cover the substrate primitive's `AsRef<str>` projection axis
6349        // on the paired newtype + closed-set-typed-enum surface.
6350        for &variant in RestartStrategy::ALL {
6351            assert_eq!(
6352                <RestartStrategy as AsRef<str>>::as_ref(&variant),
6353                variant.as_str(),
6354                "AsRef<str> impl on RestartStrategy::{variant:?} must \
6355                 byte-equal RestartStrategy::as_str on the same instance \
6356                 — divergence signals a silent detour off the substrate-\
6357                 primitive accessor"
6358            );
6359        }
6360    }
6361
6362    #[test]
6363    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
6364        // Fail-before-pass-after byte-parity pin on the three-path
6365        // convergence discipline the M2 sibling-restart primitive now
6366        // carries on the `&str`-projection axis:
6367        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
6368        // lifted impl), `format!("{s}")` (the pre-existing
6369        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
6370        // primitive `pub const fn` accessor both trait impls delegate
6371        // through) must resolve to the same byte-string on every
6372        // instance across the four-arm closed set. Refuses any future
6373        // divergence between the two trait impls (a stray
6374        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
6375        // rather than delegating through the shared accessor; a
6376        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
6377        // literal cascade) that would silently split the two
6378        // projection paths of the same closed-set typed enum. Mirrors
6379        // the sibling three-path-convergence discipline the peer
6380        // [`crate::CaixaVersion`] typed newtype carries on its
6381        // `AsRef<str>` / `Display` / `as_str` triple
6382        // (version.rs pin
6383        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
6384        // 16d5c7e).
6385        for &variant in RestartStrategy::ALL {
6386            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
6387            let via_display: String = format!("{variant}");
6388            let via_accessor: &str = variant.as_str();
6389            assert_eq!(via_as_ref, via_accessor);
6390            assert_eq!(via_display, via_accessor);
6391            assert_eq!(via_as_ref, via_display.as_str());
6392        }
6393    }
6394
6395    #[test]
6396    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
6397        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
6398        // exhaustive-iteration surface: every variant appears exactly
6399        // once, and the slice length matches the arm count of the
6400        // closed set. Every consumer that walks the accepted-strategy
6401        // set (a future `feira supervisor --estrategia …` CLI-side
6402        // arg-parse's "did you mean" hint, a future M4 admission-
6403        // webhook's rejection body naming the accepted-`:estrategia`
6404        // list, the [`RestartStrategy::from_wire`] reverse-projection
6405        // consumers that iterate the accept-set for diagnostic
6406        // rendering) reads through this slice, so a future arm addition
6407        // that grows the enum but forgets to grow [`Self::ALL`]
6408        // silently truncates every downstream consumer's accept-set at
6409        // the same pre-addition boundary — this pin fails at caixa-core
6410        // build time on the pairwise-distinct + arm-count invariants.
6411        //
6412        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
6413        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
6414        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
6415        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6416        // pins on the peer closed-set typed-enum axes.
6417        let all: &[RestartStrategy] = RestartStrategy::ALL;
6418        assert_eq!(
6419            all.len(),
6420            4,
6421            "RestartStrategy::ALL must enumerate every variant of the \
6422             four-arm closed set (OneForOne, OneForAll, RestForOne, \
6423             SimpleOneForOne); got {all:?}"
6424        );
6425        for (i, a) in all.iter().enumerate() {
6426            for (j, b) in all.iter().enumerate() {
6427                if i != j {
6428                    assert_ne!(
6429                        a, b,
6430                        "RestartStrategy::ALL must carry every variant exactly \
6431                         once — got duplicate {a:?} at indices {i} and {j}"
6432                    );
6433                }
6434            }
6435        }
6436        for variant in [
6437            RestartStrategy::OneForOne,
6438            RestartStrategy::OneForAll,
6439            RestartStrategy::RestForOne,
6440            RestartStrategy::SimpleOneForOne,
6441        ] {
6442            assert!(
6443                all.contains(&variant),
6444                "RestartStrategy::ALL must contain {variant:?} — a future arm \
6445                 addition that grows the enum but forgets to grow the ALL slice \
6446                 silently truncates every downstream consumer's accept-set at \
6447                 the pre-addition boundary"
6448            );
6449        }
6450    }
6451
6452    #[test]
6453    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
6454        // Fail-before-pass-after pin on the forward accept-set of the
6455        // [`RestartStrategy::from_wire`] reverse projection: every
6456        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6457        // constant the [`RestartStrategy::as_str`] emitter walks parses
6458        // back to its paired variant. Any future arm addition that
6459        // grows the emitter's `as_str` match but forgets to grow the
6460        // parser's `from_wire` match silently splits the two halves of
6461        // the round-trip — the wire byte-string one non-serde consumer
6462        // parses from the one the emitter wrote — with the failure
6463        // surfacing at parse time far from the rebrand commit. Pinning
6464        // the four-arm accept-set here catches the drift at caixa-core
6465        // build time.
6466        //
6467        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
6468        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
6469        // accept-set pins on the peer closed-set typed-enum `str → Self`
6470        // axes.
6471        for (wire, expected) in [
6472            (
6473                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6474                RestartStrategy::OneForOne,
6475            ),
6476            (
6477                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6478                RestartStrategy::OneForAll,
6479            ),
6480            (
6481                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6482                RestartStrategy::RestForOne,
6483            ),
6484            (
6485                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6486                RestartStrategy::SimpleOneForOne,
6487            ),
6488        ] {
6489            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6490                panic!(
6491                    "RestartStrategy::from_wire({wire:?}) must accept every \
6492                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
6493                     lifted canonical byte-string that RestartStrategy::{expected:?} \
6494                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
6495                )
6496            });
6497            assert_eq!(
6498                parsed, expected,
6499                "RestartStrategy::from_wire({wire:?}) must return \
6500                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
6501            );
6502        }
6503    }
6504
6505    #[test]
6506    fn restart_strategy_from_wire_round_trips_through_as_str() {
6507        // Fail-before-pass-after pin on the closed round-trip between
6508        // the forward [`RestartStrategy::as_str`] emitter and the
6509        // reverse [`RestartStrategy::from_wire`] parser: for every
6510        // variant in [`RestartStrategy::ALL`], parsing the emitter's
6511        // output must return exactly the same variant. Any per-arm
6512        // divergence — a future arm added to `as_str` but not
6513        // `from_wire`, an accidental copy-paste flip in one but not
6514        // the other — silently splits the emit and parse halves and
6515        // the failure surfaces at consumer parse time far from the
6516        // drift site. The `ALL`-iterating shape means a future arm
6517        // addition picks up the coverage by construction.
6518        //
6519        // Peer of the sibling
6520        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
6521        // (18c7342) round-trip pin on
6522        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
6523        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
6524        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
6525        for &variant in RestartStrategy::ALL {
6526            let wire = variant.as_str();
6527            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6528                panic!(
6529                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6530                     must be Some({variant:?}) — the two halves of the round-trip \
6531                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
6532                     got None on wire byte-string {wire:?}"
6533                )
6534            });
6535            assert_eq!(
6536                parsed, variant,
6537                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6538                 must round-trip to the same variant; got {parsed:?}"
6539            );
6540        }
6541    }
6542
6543    #[test]
6544    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
6545        // Fail-before-pass-after pin on the closed-set refusal
6546        // discipline of [`RestartStrategy::from_wire`]: every
6547        // byte-string outside the four-arm accept-set returns `None`
6548        // rather than silently collapsing onto the [`Default`]
6549        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
6550        // exercised here sweeps the load-bearing drift shapes: the
6551        // empty string (a stripped serde-attribute drift), all-
6552        // whitespace strings (the canonical text-editor accidental
6553        // padding shape), the kebab-case dispatcher-catalog identities
6554        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
6555        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
6556        // derived [`std::str::FromStr`] accept-set, which parses the
6557        // *other* axis of this enum's two-axis split and must not leak
6558        // into the `from_wire` PascalCase-wire accept-set), the
6559        // lowercased single-word forms (`"oneforone"`), the padded
6560        // canonical scalar (`" OneForOne "`), the trailing-newline
6561        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
6562        // (`"AllForOne"` — the canonical typo direction).
6563        //
6564        // Peer of the sibling
6565        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
6566        // (2aa6d23) +
6567        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
6568        // (18c7342) refusal pins on the peer closed-set typed-enum
6569        // axes.
6570        for bad in [
6571            "",
6572            " ",
6573            "\n",
6574            "\t",
6575            "one-for-one",
6576            "one-for-all",
6577            "rest-for-one",
6578            "simple-one-for-one",
6579            "oneforone",
6580            "OneForOnes",
6581            "one_for_one",
6582            "one for one",
6583            "ONEFORONE",
6584            "OneForOne ",
6585            " OneForOne",
6586            " SimpleOneForOne ",
6587            "OneForOne\n",
6588            "restforone",
6589            "REST_FOR_ONE",
6590            "AllForOne",
6591            "Simple",
6592            "?",
6593        ] {
6594            assert!(
6595                RestartStrategy::from_wire(bad).is_none(),
6596                "RestartStrategy::from_wire({bad:?}) must return None — the \
6597                 parser's accept-set is exactly the four RestartStrategy::as_str \
6598                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
6599                 and this byte-string is outside that closed set"
6600            );
6601        }
6602    }
6603
6604    #[test]
6605    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
6606        // Fail-before-pass-after pin on the fourth path of the four-path
6607        // convergence: `from_wire` (the reverse projection) inverts the
6608        // `Serialize` derive's wire byte-string on every variant.
6609        // Together with the pre-existing three-path convergence
6610        // (`Display` + `as_str` + `Serialize` all resolve to the same
6611        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
6612        // pinned by
6613        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
6614        // this closes the round-trip: the wire byte-string the
6615        // `Serialize` derive emits parses back to the same variant
6616        // through `from_wire`, so any future serde-attribute or variant-
6617        // rename drift on the emit half now surfaces as a matched drift
6618        // on the parse half at caixa-core build time — the two halves
6619        // migrate as a unit through the lifted consts on any future
6620        // rename, and the round-trip cannot silently split.
6621        //
6622        // Peer of the sibling
6623        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6624        // (18c7342) wire-format pin on
6625        // [`crate::aplicacao::PlacementStrategy::from_wire`].
6626        for &variant in RestartStrategy::ALL {
6627            let wire = serde_json::to_string(&variant).unwrap();
6628            let unquoted = wire
6629                .strip_prefix('"')
6630                .and_then(|s| s.strip_suffix('"'))
6631                .expect("serialized RestartStrategy is a JSON string");
6632            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
6633                panic!(
6634                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
6635                     Serialize derive's wire byte-string for \
6636                     RestartStrategy::{variant:?} — the four-path convergence \
6637                     (Display + as_str + Serialize + from_wire) resolves through \
6638                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
6639                )
6640            });
6641            assert_eq!(
6642                parsed, variant,
6643                "RestartStrategy::from_wire of the Serialize derive's wire \
6644                 byte-string for RestartStrategy::{variant:?} must round-trip \
6645                 to the same variant; got {parsed:?}"
6646            );
6647        }
6648    }
6649
6650    #[test]
6651    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
6652        // Fail-before-pass-after byte-parity pin on the newly lifted
6653        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
6654        // library trait impl and the substrate-primitive
6655        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
6656        // the same four-arm accept-set across every arm the exhaustive
6657        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
6658        // detour that routes the trait impl through a divergent projection
6659        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
6660        // … }` re-inlining that opens a compile-time link to the un-
6661        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
6662        // attribute drift that silently splits the wire byte-string from
6663        // every consumer that reaches for this typed dispatch, an
6664        // accidental swap onto the kebab-case dispatcher-catalog axis the
6665        // pre-existing [`std::str::FromStr`] impl parses through and which
6666        // would collide the two-axis wire/catalog split the sibling
6667        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
6668        // trips at caixa-core test time under `assert_eq!` rather than at
6669        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
6670        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
6671        // carries so no arm's projection is covered only by the sibling
6672        // method-named `from_wire` path. Peer of the sibling
6673        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
6674        // (3c83606),
6675        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
6676        // (bf33136), and the M3
6677        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
6678        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
6679        // onto the first M2-OTP-shape closed-set typed enum on the caixa
6680        // surface.
6681        for &variant in RestartStrategy::ALL {
6682            let wire = variant.as_str();
6683            assert_eq!(
6684                <RestartStrategy as TryFrom<&str>>::try_from(wire),
6685                Ok(variant),
6686                "TryFrom<&str> impl on RestartStrategy must round-trip \
6687                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
6688                 Ok(RestartStrategy::{variant:?}) — divergence from \
6689                 RestartStrategy::from_wire signals a silent detour off \
6690                 the substrate-primitive accessor"
6691            );
6692            assert_eq!(
6693                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
6694                RestartStrategy::from_wire(wire),
6695                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
6696                 RestartStrategy::from_wire on the same input"
6697            );
6698        }
6699    }
6700
6701    #[test]
6702    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
6703        // Rejection witness on the `impl TryFrom<&str> for
6704        // RestartStrategy` — sweeps a candidate set of byte-strings
6705        // outside the four-arm PascalCase wire accept-set the sibling
6706        // [`RestartStrategy::as_str`] emits and asserts every one lands on
6707        // `Err(())`, so a future accidental widening of the trait impl's
6708        // accept-set (a stray additional
6709        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
6710        // path, a silent inclusion of the kebab-case dispatcher-catalog
6711        // byte-string the pre-existing [`std::str::FromStr`] impl the
6712        // [`gen_platform::FromStrKind`] derive installs parses onto the
6713        // wire axis — which would collide the two-axis
6714        // wire/dispatcher-catalog split the sibling
6715        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
6716        // an English-rebrand or plural-arm silent alias that would
6717        // widen the wire accept-set past the OTP-canonical four) trips at
6718        // caixa-core test time. The candidate set includes the empty
6719        // string, whitespace-only padding, the kebab-case dispatcher-
6720        // catalog byte-strings on the sibling axis (a caller who confuses
6721        // the two axes trips here rather than at a downstream consumer's
6722        // silent reject), a lowercase / uppercase / mixed-case fold of
6723        // each PascalCase arm (a caller who assumes case-fold acceptance
6724        // trips here), leading/trailing whitespace padding, the trailing-
6725        // newline shape, quote-wrapped candidates, and a residual set of
6726        // plausible-but-wrong English rebrand candidates. Peer of the
6727        // sibling
6728        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
6729        // (3c83606) and
6730        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
6731        // (6fd00cd) rejection witnesses.
6732        let rejected: &[&str] = &[
6733            "",
6734            " ",
6735            "\n",
6736            "\t",
6737            "one-for-one",
6738            "one-for-all",
6739            "rest-for-one",
6740            "simple-one-for-one",
6741            "oneforone",
6742            "one_for_one",
6743            "OneForOnes",
6744            "ONEFORONE",
6745            "oneforall",
6746            "restforone",
6747            "simpleoneforone",
6748            "OneForOne ",
6749            " OneForOne",
6750            " OneForAll ",
6751            "OneForOne\n",
6752            "RestForOne\t",
6753            "OneForEach",
6754            "AllForOne",
6755            "one for one",
6756            "\"OneForOne\"",
6757            "?",
6758        ];
6759        for &input in rejected {
6760            assert_eq!(
6761                <RestartStrategy as TryFrom<&str>>::try_from(input),
6762                Err(()),
6763                "TryFrom<&str> impl on RestartStrategy must reject the \
6764                 non-wire byte-string {input:?} — silent acceptance signals \
6765                 an accept-set widening off the paired \
6766                 RestartStrategy::from_wire resolver"
6767            );
6768        }
6769    }
6770
6771    #[test]
6772    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
6773        // Cross-axis partition pin: the paired `TryFrom<&str>` and
6774        // `from_wire` reverse projections must resolve identically on
6775        // *every* input, not just the ones [`RestartStrategy::ALL`]
6776        // enumerates. Sweeps a mixed candidate set spanning accepted
6777        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
6778        // dispatcher-catalog byte-strings, empty, whitespace-padded,
6779        // quoted, English-rebrand candidates) inputs and asserts the
6780        // trait's `Result::ok()` projection byte-equals the method-named
6781        // resolver's `Option<Self>` return-shape on each, locking the two
6782        // paths together by construction so any future detour (a stray
6783        // `try_from` special-case that widens or narrows the accept-set
6784        // outside the paired `from_wire` resolver, an accidental swap
6785        // onto the kebab-case [`std::str::FromStr`] impl the
6786        // [`gen_platform::FromStrKind`] derive installs on the sibling
6787        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
6788        // the sibling
6789        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
6790        // pin — extends the round-trip discipline onto the M2-OTP-shape
6791        // sibling-restart axis.
6792        let candidates: &[&str] = &[
6793            "OneForOne",
6794            "OneForAll",
6795            "RestForOne",
6796            "SimpleOneForOne",
6797            "",
6798            "one-for-one",
6799            "one-for-all",
6800            "rest-for-one",
6801            "simple-one-for-one",
6802            "oneforone",
6803            "unknown",
6804            "OneForOne ",
6805            " OneForOne",
6806            "\"OneForOne\"",
6807            "OneForEach",
6808            "?",
6809        ];
6810        for &input in candidates {
6811            let via_trait: Option<RestartStrategy> =
6812                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
6813            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
6814            assert_eq!(
6815                via_trait, via_method,
6816                "TryFrom<&str> and from_wire must resolve identically on \
6817                 input {input:?} — divergence signals the two reverse-\
6818                 projection paths have drifted onto different accept-sets"
6819            );
6820        }
6821    }
6822
6823    #[test]
6824    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
6825        // Fail-before-pass-after byte-parity pin on the newly lifted
6826        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
6827        // library trait impl and the substrate-primitive
6828        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
6829        // the same three-arm accept-set across every arm the exhaustive
6830        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
6831        // detour that routes the trait impl through a divergent
6832        // projection (a per-arm inline `match s { "Permanent" =>
6833        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
6834        // link to the un-lifted arm-literal, a hypothetical
6835        // `#[serde(rename_all = "…")]` attribute drift that silently
6836        // splits the wire byte-string from every consumer that reaches
6837        // for this typed dispatch, an accidental swap onto the kebab-case
6838        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
6839        // impl parses through and which would collide the two-axis
6840        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
6841        // doc block makes load-bearing) trips at caixa-core test time
6842        // under `assert_eq!` rather than at a downstream
6843        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
6844        // every one of the three arms [`RestartPolicy::ALL`] carries so
6845        // no arm's projection is covered only by the sibling method-
6846        // named `from_wire` path. Peer of the sibling
6847        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
6848        // (5b828ed) — extends the trait-idiomatic reverse-projection
6849        // axis onto the third and final M2-OTP-shape closed-set typed
6850        // enum on the caixa surface (the paired per-child restart-
6851        // decision-policy sibling on the same M2 `:supervisor` slot).
6852        for &variant in RestartPolicy::ALL {
6853            let wire = variant.as_str();
6854            assert_eq!(
6855                <RestartPolicy as TryFrom<&str>>::try_from(wire),
6856                Ok(variant),
6857                "TryFrom<&str> impl on RestartPolicy must round-trip \
6858                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
6859                 Ok(RestartPolicy::{variant:?}) — divergence from \
6860                 RestartPolicy::from_wire signals a silent detour off \
6861                 the substrate-primitive accessor"
6862            );
6863            assert_eq!(
6864                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
6865                RestartPolicy::from_wire(wire),
6866                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
6867                 equal RestartPolicy::from_wire on the same input"
6868            );
6869        }
6870    }
6871
6872    #[test]
6873    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
6874        // Rejection witness on the `impl TryFrom<&str> for
6875        // RestartPolicy` — sweeps a candidate set of byte-strings
6876        // outside the three-arm PascalCase wire accept-set the sibling
6877        // [`RestartPolicy::as_str`] emits and asserts every one lands on
6878        // `Err(())`, so a future accidental widening of the trait impl's
6879        // accept-set (a stray additional
6880        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
6881        // path, a silent inclusion of the kebab-case dispatcher-catalog
6882        // byte-string the pre-existing [`std::str::FromStr`] impl the
6883        // [`gen_platform::FromStrKind`] derive installs parses onto the
6884        // wire axis — which would collide the two-axis
6885        // wire/dispatcher-catalog split the sibling
6886        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
6887        // an English-rebrand or plural-arm silent alias that would widen
6888        // the wire accept-set past the OTP-canonical three) trips at
6889        // caixa-core test time. The candidate set includes the empty
6890        // string, whitespace-only padding, the kebab-case dispatcher-
6891        // catalog byte-strings on the sibling axis (a caller who
6892        // confuses the two axes trips here rather than at a downstream
6893        // consumer's silent reject), a lowercase / uppercase / mixed-case
6894        // fold of each PascalCase arm (a caller who assumes case-fold
6895        // acceptance trips here), leading/trailing whitespace padding,
6896        // the trailing-newline shape, quote-wrapped candidates, and a
6897        // residual set of plausible-but-wrong English rebrand
6898        // candidates. Peer of the sibling
6899        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
6900        // (5b828ed) rejection witness.
6901        let rejected: &[&str] = &[
6902            "",
6903            " ",
6904            "\n",
6905            "\t",
6906            "permanent",
6907            "temporary",
6908            "transient",
6909            "PERMANENT",
6910            "TEMPORARY",
6911            "TRANSIENT",
6912            "Permanents",
6913            "Permanent ",
6914            " Permanent",
6915            " Temporary ",
6916            "Permanent\n",
6917            "Transient\t",
6918            "\"Permanent\"",
6919            "Ephemeral",
6920            "Always",
6921            "Never",
6922            "OnAbnormalExit",
6923            "intrinsic",
6924            "?",
6925        ];
6926        for &input in rejected {
6927            assert_eq!(
6928                <RestartPolicy as TryFrom<&str>>::try_from(input),
6929                Err(()),
6930                "TryFrom<&str> impl on RestartPolicy must reject the \
6931                 non-wire byte-string {input:?} — silent acceptance \
6932                 signals an accept-set widening off the paired \
6933                 RestartPolicy::from_wire resolver"
6934            );
6935        }
6936    }
6937
6938    #[test]
6939    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
6940        // Cross-axis partition pin: the paired `TryFrom<&str>` and
6941        // `from_wire` reverse projections must resolve identically on
6942        // *every* input, not just the ones [`RestartPolicy::ALL`]
6943        // enumerates. Sweeps a mixed candidate set spanning accepted
6944        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
6945        // case dispatcher-catalog byte-strings, empty, whitespace-
6946        // padded, quoted, English-rebrand candidates) inputs and asserts
6947        // the trait's `Result::ok()` projection byte-equals the method-
6948        // named resolver's `Option<Self>` return-shape on each, locking
6949        // the two paths together by construction so any future detour
6950        // (a stray `try_from` special-case that widens or narrows the
6951        // accept-set outside the paired `from_wire` resolver, an
6952        // accidental swap onto the kebab-case [`std::str::FromStr`]
6953        // impl the [`gen_platform::FromStrKind`] derive installs on the
6954        // sibling dispatcher-catalog axis) trips at caixa-core test
6955        // time. Peer of the sibling
6956        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
6957        // pin — extends the round-trip discipline onto the M2-OTP-shape
6958        // per-child restart-policy axis.
6959        let candidates: &[&str] = &[
6960            "Permanent",
6961            "Temporary",
6962            "Transient",
6963            "",
6964            "permanent",
6965            "temporary",
6966            "transient",
6967            "PERMANENT",
6968            "unknown",
6969            "Permanent ",
6970            " Permanent",
6971            "\"Permanent\"",
6972            "Ephemeral",
6973            "OnAbnormalExit",
6974            "?",
6975        ];
6976        for &input in candidates {
6977            let via_trait: Option<RestartPolicy> =
6978                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
6979            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
6980            assert_eq!(
6981                via_trait, via_method,
6982                "TryFrom<&str> and from_wire must resolve identically on \
6983                 input {input:?} — divergence signals the two reverse-\
6984                 projection paths have drifted onto different accept-sets"
6985            );
6986        }
6987    }
6988
6989    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
6990
6991    #[test]
6992    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
6993        // The fail-before-pass-after pin: pre-lift there was no
6994        // single-source binding between the [`RestartPolicy`] variant
6995        // name the un-`rename`d `Serialize` derive emits under
6996        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
6997        // byte-string every downstream cluster-side dispatcher (the
6998        // future wasm-operator's per-child post-exit restart-decision
6999        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7000        // materializer's admission-time enum-arm bind, the
7001        // `caixa-operator`'s hierarchical reconciliation scheduler's
7002        // per-child-policy fan-out) probes verbatim. A future
7003        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
7004        // or a per-variant `#[serde(rename = "…")]` override, or a
7005        // variant rename in the source — would silently rebrand the
7006        // emitted scalar under one spelling while every downstream
7007        // dispatcher still probed the other, with the failure surfacing
7008        // at the operator's reconcile posture (children coming up under
7009        // the `default()` `Permanent` arm rather than the typed slot's
7010        // declared policy — a `:temporary` `oneShot` child would be
7011        // restarted on clean exit, treating the successful-completion
7012        // signal as failure and re-running the completion-terminal
7013        // one-shot indefinitely; a `:transient` child that clean-exited
7014        // would be restarted, masking the clean-completion contract)
7015        // far from the source rebrand commit and with no field naming
7016        // the drift. Pinning the two paths (the `Serialize` derive's
7017        // serialized string AND the [`RestartPolicy::as_str`] helper)
7018        // to the same three lifted
7019        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
7020        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
7021        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
7022        // byte-strings makes any future drift on either endpoint fail
7023        // here at caixa-core build time. Peer of the sibling
7024        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
7025        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
7026        // and the M3
7027        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7028        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
7029        // same three-path-convergence discipline, extended to close the
7030        // third OTP-shaped closed-enum discriminator axis on the caixa
7031        // typed surface (per-child restart-decision policy).
7032        for (variant, expected) in [
7033            (
7034                RestartPolicy::Permanent,
7035                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7036            ),
7037            (
7038                RestartPolicy::Temporary,
7039                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7040            ),
7041            (
7042                RestartPolicy::Transient,
7043                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7044            ),
7045        ] {
7046            let json = serde_json::to_string(&variant).unwrap();
7047            assert_eq!(
7048                json,
7049                format!("\"{expected}\""),
7050                "RestartPolicy::{variant:?} must serialize to {expected:?}"
7051            );
7052            assert_eq!(
7053                variant.as_str(),
7054                expected,
7055                "RestartPolicy::{variant:?}.as_str() must return the lifted \
7056                 SUPERVISOR_CHILD_RESTART_* constant"
7057            );
7058        }
7059    }
7060
7061    #[test]
7062    fn supervisor_child_restart_consts_are_pairwise_distinct() {
7063        // Cross-arm drift-detection pin: a future collapse of two
7064        // canonical variant byte-strings onto the same value (e.g. an
7065        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
7066        // to also read `"Permanent"`) would silently reroute every
7067        // downstream operator's per-child-policy dispatch onto the
7068        // sibling arm's reconcile branch and pass every propagation-probe
7069        // test that expected only the stale arm's value — a `:transient`
7070        // child would come up under the `:permanent` restart-decision
7071        // posture on every subsequent clean exit, so a completion-terminal
7072        // child would be restarted indefinitely against its declared
7073        // policy. Peer of the sibling
7074        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
7075        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
7076        // and the four-way distinct pin
7077        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
7078        // top-level `SUPERVISOR_KEY_*` axis.
7079        let all = [
7080            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7081            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7082            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7083        ];
7084        for (i, a) in all.iter().enumerate() {
7085            for (j, b) in all.iter().enumerate() {
7086                if i != j {
7087                    assert_ne!(
7088                        a, b,
7089                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
7090                         — got duplicate {a:?} at indices {i} and {j}",
7091                    );
7092                }
7093            }
7094        }
7095    }
7096
7097    #[test]
7098    fn restart_policy_display_routes_through_as_str_helper() {
7099        // The fail-before-pass-after pin on the first half of the
7100        // three-path convergence: pre-convergence [`RestartPolicy`]
7101        // carried a [`std::fmt::Display`] surface via its
7102        // `#[discriminant(also_display)]` gen-platform derive route,
7103        // which arrived kebab-case as `"permanent"` / `"temporary"`
7104        // / `"transient"` on this three-arm enum (whose variant
7105        // names each collapse to their own lowercase form under the
7106        // kebab-case transform) while the wire format ran as
7107        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
7108        // through the un-`rename`d serde derive. Every consumer
7109        // reaching for a policy byte-string past the wire format had
7110        // to pick between three paths ([`RestartPolicy::as_str`],
7111        // the `Serialize` derive's serialized string, or
7112        // `format!("{v}")` on the discriminant-Display route), any
7113        // two of which a future variant rename or
7114        // `#[serde(rename_all = "kebab-case")]` attribute would
7115        // silently desynchronize. Wiring [`std::fmt::Display`]
7116        // through [`RestartPolicy::as_str`] closes the third path:
7117        // every `format!("{v}")` call reaches the same lifted
7118        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
7119        // wire format and the [`RestartPolicy::as_str`] helper
7120        // already route through, so a future variant rename lands at
7121        // exactly one place. Pin the routing here so a future
7122        // `impl std::fmt::Display for RestartPolicy`
7123        // reimplementation that hand-rolls the arms instead of
7124        // delegating to [`RestartPolicy::as_str`] fails at
7125        // caixa-core build time. Peer of the sibling
7126        // [`restart_strategy_display_routes_through_as_str_helper`]
7127        // on the per-supervisor sibling-restart-strategy axis and
7128        // the M3
7129        // `placement_strategy_display_routes_through_as_str_helper`
7130        // (cc8f749) — the third of three OTP-shape closed-enum
7131        // discriminator axes on the caixa typed surface now
7132        // converged onto the same three-path
7133        // (Display → as_str → lifted const) discipline.
7134        for variant in [
7135            RestartPolicy::Permanent,
7136            RestartPolicy::Temporary,
7137            RestartPolicy::Transient,
7138        ] {
7139            assert_eq!(
7140                variant.to_string(),
7141                variant.as_str(),
7142                "RestartPolicy::{variant:?} Display must route through \
7143                 RestartPolicy::as_str (single source of truth: the lifted \
7144                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
7145            );
7146        }
7147    }
7148
7149    #[test]
7150    fn restart_policy_display_matches_serialized_wire_byte_string() {
7151        // The fail-before-pass-after pin on the second half of the
7152        // three-path convergence: `Display` (user-facing text) agrees
7153        // byte-for-byte with the `Serialize` derive's wire format
7154        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
7155        // scalar) on every variant. Pre-convergence the two paths
7156        // were structurally independent — a future
7157        // `#[serde(rename_all = "kebab-case")]` attribute on the
7158        // enum would silently rebrand the emitted wire scalar
7159        // (`permanent`, `temporary`, `transient`) while every
7160        // consumer that pretty-prints the policy (the future
7161        // wasm-operator's per-child post-exit restart-decision
7162        // diagnostic line, the future `feira app graph` per-child
7163        // restart column, the future M4
7164        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7165        // per-child admission-webhook rejection body) would still
7166        // emit the PascalCase form the `as_str` / `Display` route
7167        // returns, with the mismatch surfacing at consumer parse
7168        // time / operator dispatch time far from the source rebrand
7169        // commit. Pin the two paths byte-for-byte here so any future
7170        // serde-attribute or variant-rename drift is a
7171        // caixa-core-build-time test failure at this call, not a
7172        // silent per-consumer dispatch miss. Peer of the sibling
7173        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
7174        // on the per-supervisor sibling-restart-strategy axis and
7175        // the M3
7176        // `placement_strategy_display_matches_serialized_wire_byte_string`
7177        // (cc8f749).
7178        for variant in [
7179            RestartPolicy::Permanent,
7180            RestartPolicy::Temporary,
7181            RestartPolicy::Transient,
7182        ] {
7183            let wire = serde_json::to_string(&variant).unwrap();
7184            let unquoted = wire
7185                .strip_prefix('"')
7186                .and_then(|s| s.strip_suffix('"'))
7187                .expect("serialized RestartPolicy is a JSON string");
7188            assert_eq!(
7189                variant.to_string(),
7190                unquoted,
7191                "RestartPolicy::{variant:?} Display byte-string must match the \
7192                 Serialize derive's wire byte-string (three-path convergence: \
7193                 Display + as_str + Serialize all resolve to the same \
7194                 SUPERVISOR_CHILD_RESTART_* const)"
7195            );
7196        }
7197    }
7198
7199    #[test]
7200    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
7201        // Fail-before-pass-after byte-parity pin on the lifted
7202        // `impl AsRef<str> for RestartPolicy` — asserts the
7203        // standard-library trait impl and the substrate-primitive
7204        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
7205        // to the same `&str` per instance across the three-arm
7206        // closed set, so any future silent detour that routes the
7207        // impl through a divergent projection (a per-arm inline
7208        // `match self { RestartPolicy::Permanent => "Permanent", … }`
7209        // re-inlining that opens a compile-time link to the un-lifted
7210        // arm-literal, a swap onto the kebab-case
7211        // [`gen_platform::Discriminant`] catalog identity that would
7212        // collide the wire axis with the dispatcher-catalog axis) trips
7213        // at caixa-core test time under `PartialEq` rather than at a
7214        // downstream `impl AsRef<str>`-bound consumer's silent split.
7215        // Sweeps every one of the three arms
7216        // [`RestartPolicy::ALL`] carries so no arm's projection is
7217        // covered only by the sibling wire-format `Serialize` derive
7218        // path. Peer of the sibling
7219        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
7220        // (63eb1a4) on the paired per-supervisor sibling-restart-
7221        // strategy axis and the [`crate::CaixaVersion`]
7222        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
7223        // top-level `:versao` typed newtype — the three pins together
7224        // cover the substrate primitive's `AsRef<str>` projection axis
7225        // on the paired newtype + M2 closed-set-typed-enum surface.
7226        for &variant in RestartPolicy::ALL {
7227            assert_eq!(
7228                <RestartPolicy as AsRef<str>>::as_ref(&variant),
7229                variant.as_str(),
7230                "AsRef<str> impl on RestartPolicy::{variant:?} must \
7231                 byte-equal RestartPolicy::as_str on the same instance \
7232                 — divergence signals a silent detour off the substrate-\
7233                 primitive accessor"
7234            );
7235        }
7236    }
7237
7238    #[test]
7239    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
7240        // Fail-before-pass-after byte-parity pin on the three-path
7241        // convergence discipline the M2 per-child-restart-policy
7242        // primitive now carries on the `&str`-projection axis:
7243        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
7244        // lifted impl), `format!("{v}")` (the pre-existing
7245        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
7246        // primitive `pub const fn` accessor both trait impls delegate
7247        // through) must resolve to the same byte-string on every
7248        // instance across the three-arm closed set. Refuses any future
7249        // divergence between the two trait impls (a stray
7250        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7251        // rather than delegating through the shared accessor; a
7252        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7253        // literal cascade) that would silently split the two
7254        // projection paths of the same closed-set typed enum. Mirrors
7255        // the sibling three-path-convergence discipline the peer
7256        // [`RestartStrategy`] typed enum carries on its
7257        // `AsRef<str>` / `Display` / `as_str` triple
7258        // (supervisor.rs pin
7259        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
7260        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
7261        // carries on the same triple (version.rs pin
7262        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7263        // 16d5c7e).
7264        for &variant in RestartPolicy::ALL {
7265            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
7266            let via_display: String = format!("{variant}");
7267            let via_accessor: &str = variant.as_str();
7268            assert_eq!(via_as_ref, via_accessor);
7269            assert_eq!(via_display, via_accessor);
7270            assert_eq!(via_as_ref, via_display.as_str());
7271        }
7272    }
7273
7274    #[test]
7275    fn restart_policy_all_enumerates_every_variant_exactly_once() {
7276        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
7277        // exhaustive-iteration surface: every variant appears exactly
7278        // once, and the slice length matches the arm count of the
7279        // closed set. Every consumer that walks the accepted-policy
7280        // set (a future `feira supervisor --restart …` CLI-side
7281        // arg-parse's "did you mean" hint, a future M4 admission-
7282        // webhook's per-child rejection body naming the accepted-
7283        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
7284        // projection consumers that iterate the accept-set for
7285        // diagnostic rendering) reads through this slice, so a future
7286        // arm addition that grows the enum but forgets to grow
7287        // [`Self::ALL`] silently truncates every downstream consumer's
7288        // accept-set at the same pre-addition boundary — this pin
7289        // fails at caixa-core build time on the pairwise-distinct +
7290        // arm-count invariants.
7291        //
7292        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
7293        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
7294        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7295        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7296        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7297        // pins on the peer closed-set typed-enum axes.
7298        let all: &[RestartPolicy] = RestartPolicy::ALL;
7299        assert_eq!(
7300            all.len(),
7301            3,
7302            "RestartPolicy::ALL must enumerate every variant of the \
7303             three-arm closed set (Permanent, Temporary, Transient); \
7304             got {all:?}"
7305        );
7306        for (i, a) in all.iter().enumerate() {
7307            for (j, b) in all.iter().enumerate() {
7308                if i != j {
7309                    assert_ne!(
7310                        a, b,
7311                        "RestartPolicy::ALL must carry every variant exactly \
7312                         once — got duplicate {a:?} at indices {i} and {j}"
7313                    );
7314                }
7315            }
7316        }
7317        for variant in [
7318            RestartPolicy::Permanent,
7319            RestartPolicy::Temporary,
7320            RestartPolicy::Transient,
7321        ] {
7322            assert!(
7323                all.contains(&variant),
7324                "RestartPolicy::ALL must contain {variant:?} — a future arm \
7325                 addition that grows the enum but forgets to grow the ALL slice \
7326                 silently truncates every downstream consumer's accept-set at \
7327                 the pre-addition boundary"
7328            );
7329        }
7330    }
7331
7332    #[test]
7333    fn restart_policy_from_wire_accepts_every_lifted_constant() {
7334        // Fail-before-pass-after pin on the forward accept-set of the
7335        // [`RestartPolicy::from_wire`] reverse projection: every
7336        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
7337        // constant the [`RestartPolicy::as_str`] emitter walks parses
7338        // back to its paired variant. Any future arm addition that
7339        // grows the emitter's `as_str` match but forgets to grow the
7340        // parser's `from_wire` match silently splits the two halves of
7341        // the round-trip — the wire byte-string one non-serde consumer
7342        // parses from the one the emitter wrote — with the failure
7343        // surfacing at the operator's reconcile posture (a `:temporary`
7344        // `oneShot` child restarted on clean exit, a `:transient` child
7345        // restarted after clean completion) far from the rebrand
7346        // commit. Pinning the three-arm accept-set here catches the
7347        // drift at caixa-core build time.
7348        //
7349        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
7350        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
7351        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
7352        // accept-set pins on the peer closed-set typed-enum `str → Self`
7353        // axes.
7354        for (wire, expected) in [
7355            (
7356                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7357                RestartPolicy::Permanent,
7358            ),
7359            (
7360                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7361                RestartPolicy::Temporary,
7362            ),
7363            (
7364                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7365                RestartPolicy::Transient,
7366            ),
7367        ] {
7368            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
7369                panic!(
7370                    "RestartPolicy::from_wire({wire:?}) must accept every \
7371                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
7372                     lifted canonical byte-string that RestartPolicy::{expected:?} \
7373                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
7374                )
7375            });
7376            assert_eq!(
7377                parsed, expected,
7378                "RestartPolicy::from_wire({wire:?}) must return \
7379                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
7380            );
7381        }
7382    }
7383
7384    #[test]
7385    fn restart_policy_from_wire_round_trips_through_as_str() {
7386        // Fail-before-pass-after pin on the closed round-trip between
7387        // the forward [`RestartPolicy::as_str`] emitter and the
7388        // reverse [`RestartPolicy::from_wire`] parser: for every
7389        // variant in [`RestartPolicy::ALL`], parsing the emitter's
7390        // output must return exactly the same variant. Any per-arm
7391        // divergence — a future arm added to `as_str` but not
7392        // `from_wire`, an accidental copy-paste flip in one but not
7393        // the other — silently splits the emit and parse halves and
7394        // the failure surfaces at consumer parse time far from the
7395        // drift site. The `ALL`-iterating shape means a future arm
7396        // addition picks up the coverage by construction.
7397        //
7398        // Peer of the sibling
7399        // [`restart_strategy_from_wire_round_trips_through_as_str`]
7400        // (4eec29c) round-trip pin on
7401        // [`RestartStrategy::from_wire`] and the M3
7402        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
7403        // (18c7342) round-trip pin on
7404        // [`crate::aplicacao::PlacementStrategy::from_wire`].
7405        for &variant in RestartPolicy::ALL {
7406            let wire = variant.as_str();
7407            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
7408                panic!(
7409                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
7410                     must be Some({variant:?}) — the two halves of the round-trip \
7411                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
7412                     got None on wire byte-string {wire:?}"
7413                )
7414            });
7415            assert_eq!(
7416                parsed, variant,
7417                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
7418                 must round-trip to the same variant; got {parsed:?}"
7419            );
7420        }
7421    }
7422
7423    #[test]
7424    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
7425        // Fail-before-pass-after pin on the closed-set refusal
7426        // discipline of [`RestartPolicy::from_wire`]: every
7427        // byte-string outside the three-arm accept-set returns `None`
7428        // rather than silently collapsing onto the [`Default`]
7429        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
7430        // exercised here sweeps the load-bearing drift shapes: the
7431        // empty string (a stripped serde-attribute drift), all-
7432        // whitespace strings (the canonical text-editor accidental
7433        // padding shape), the kebab-case dispatcher-catalog identities
7434        // (`"permanent"` / `"temporary"` / `"transient"` — the
7435        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
7436        // accept-set, which parses the *other* axis of this enum's
7437        // two-axis split and must not leak into the `from_wire`
7438        // PascalCase-wire accept-set — a lowercase leak here would
7439        // silently accept the operator's kebab-case
7440        // dispatcher-catalog probe under the wire-axis parser and mis-
7441        // route a `:permanent` intent), the padded canonical scalar
7442        // (`" Permanent "`), the trailing-newline shapes
7443        // (`"Permanent\n"`), the uppercase-single-word forms
7444        // (`"PERMANENT"`), and neighboring-but-unknown arms
7445        // (`"Restart"` — the canonical typo direction toward the
7446        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
7447        //
7448        // Peer of the sibling
7449        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
7450        // (4eec29c) +
7451        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
7452        // (2aa6d23) +
7453        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
7454        // (18c7342) refusal pins on the peer closed-set typed-enum
7455        // axes.
7456        for bad in [
7457            "",
7458            " ",
7459            "\n",
7460            "\t",
7461            "permanent",
7462            "temporary",
7463            "transient",
7464            "PERMANENT",
7465            "TEMPORARY",
7466            "TRANSIENT",
7467            "Permanents",
7468            "Permanent ",
7469            " Permanent",
7470            " Transient ",
7471            "Permanent\n",
7472            "perma",
7473            "Trans",
7474            "OneForOne",
7475            "Restart",
7476            "?",
7477        ] {
7478            assert!(
7479                RestartPolicy::from_wire(bad).is_none(),
7480                "RestartPolicy::from_wire({bad:?}) must return None — the \
7481                 parser's accept-set is exactly the three RestartPolicy::as_str \
7482                 outputs (Permanent, Temporary, Transient), and this \
7483                 byte-string is outside that closed set"
7484            );
7485        }
7486    }
7487
7488    #[test]
7489    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
7490        // Fail-before-pass-after pin on the fourth path of the four-path
7491        // convergence: `from_wire` (the reverse projection) inverts the
7492        // `Serialize` derive's wire byte-string on every variant.
7493        // Together with the pre-existing three-path convergence
7494        // (`Display` + `as_str` + `Serialize` all resolve to the same
7495        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
7496        // pinned by
7497        // [`restart_policy_display_matches_serialized_wire_byte_string`])
7498        // this closes the round-trip: the wire byte-string the
7499        // `Serialize` derive emits parses back to the same variant
7500        // through `from_wire`, so any future serde-attribute or variant-
7501        // rename drift on the emit half now surfaces as a matched drift
7502        // on the parse half at caixa-core build time — the two halves
7503        // migrate as a unit through the lifted consts on any future
7504        // rename, and the round-trip cannot silently split.
7505        //
7506        // Peer of the sibling
7507        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7508        // (4eec29c) wire-format pin on
7509        // [`RestartStrategy::from_wire`] and the M3
7510        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7511        // (18c7342) wire-format pin on
7512        // [`crate::aplicacao::PlacementStrategy::from_wire`].
7513        for &variant in RestartPolicy::ALL {
7514            let wire = serde_json::to_string(&variant).unwrap();
7515            let unquoted = wire
7516                .strip_prefix('"')
7517                .and_then(|s| s.strip_suffix('"'))
7518                .expect("serialized RestartPolicy is a JSON string");
7519            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
7520                panic!(
7521                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
7522                     Serialize derive's wire byte-string for \
7523                     RestartPolicy::{variant:?} — the four-path convergence \
7524                     (Display + as_str + Serialize + from_wire) resolves through \
7525                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
7526                )
7527            });
7528            assert_eq!(
7529                parsed, variant,
7530                "RestartPolicy::from_wire of the Serialize derive's wire \
7531                 byte-string for RestartPolicy::{variant:?} must round-trip \
7532                 to the same variant; got {parsed:?}"
7533            );
7534        }
7535    }
7536
7537    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
7538    //
7539    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
7540    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
7541    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
7542    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
7543    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
7544    // the peer per-`:upgrade-from :from` axis. The three pins jointly
7545    // brace the accessor against every future silent detour that would
7546    // desynchronize it from the raw `.caixa` field access every consumer
7547    // previously open-coded.
7548
7549    #[test]
7550    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
7551        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
7552        // [`ChildSpec::nome`] must return the `:children :caixa` field
7553        // byte-for-byte across every DNS-1123-label value the upstream
7554        // [`crate::render::require_valid_dns_1123_label`] gate at
7555        // `SupervisorSpec::validate` admits. Peer of the sibling
7556        // `membro_nome_returns_caixa_byte_equal_across_permutations`
7557        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
7558        // substrate-primitive accessor must byte-equal the raw field
7559        // access verbatim across every author-declared value" discipline
7560        // extended to the M2 supervisor-tree per-`:children` arm. Pins
7561        // against a future silent detour that re-normalized the child
7562        // identity (an accidental `.to_lowercase()` — every `:children
7563        // :caixa` is validated as a DNS-1123 label upstream, so any
7564        // re-normalization is redundant + a drift surface between the
7565        // validator and the accessor), a namespace-prefix rewrite (an
7566        // accidental `format!("{namespace}/{caixa}")` per-CR
7567        // fully-qualified rewrite that didn't land on the peer axes), or
7568        // a per-cluster alias stamp the future wasm-operator's
7569        // hierarchical reconciliation scheduler authors on one consumer
7570        // without the others. Five values sweep the accept-set the
7571        // DNS-1123 gate upstream admits (short single-word / dashed /
7572        // v-suffixed / mixed-digit child names).
7573        for name in [
7574            "worker",
7575            "cache-server",
7576            "scratch-job",
7577            "orders-v2",
7578            "session-8080",
7579        ] {
7580            let c = ChildSpec {
7581                caixa: name.into(),
7582                versao: "^0.1".into(),
7583                restart: RestartPolicy::Permanent,
7584            };
7585            assert_eq!(
7586                c.nome(),
7587                name,
7588                "ChildSpec::nome must return :children :caixa verbatim \
7589                 (got {:?}, expected {name:?})",
7590                c.nome(),
7591            );
7592            assert_eq!(
7593                c.nome(),
7594                c.caixa.as_str(),
7595                "ChildSpec::nome must byte-equal the .caixa field access",
7596            );
7597        }
7598    }
7599
7600    #[test]
7601    fn child_spec_nome_borrows_from_caixa_storage() {
7602        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
7603        // `&str` slice that borrows from the typed slot's own [`String`]
7604        // storage — same-address invariant with `c.caixa.as_str()`. Pins
7605        // against a future silent detour that allocated a fresh `String`
7606        // (`self.caixa.clone()` in the body would type-check but silently
7607        // drop the borrow, and every downstream consumer that assumed
7608        // the returned slice outlives `&self` would break on a stale-
7609        // reference use-after-free — the [`crate::render::insert_first_seen`]
7610        // dedup key at [`SupervisorSpec::validate`], the
7611        // [`validate_no_self_supervision`] equality check against the
7612        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
7613        // borrow — each would silently misbehave if this accessor
7614        // produced a detached copy). Peer of the sibling
7615        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
7616        // M3 per-`:membros` axis and the
7617        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
7618        // first M2 slot scalar accessor.
7619        let c = ChildSpec {
7620            caixa: "worker".into(),
7621            versao: "^0.1".into(),
7622            restart: RestartPolicy::Permanent,
7623        };
7624        let name = c.nome();
7625        let caixa_slice = c.caixa.as_str();
7626        assert_eq!(
7627            name.as_ptr(),
7628            caixa_slice.as_ptr(),
7629            "ChildSpec::nome must borrow from the .caixa String's backing \
7630             storage — a fresh allocation here means the accessor no \
7631             longer names the substrate-primitive typed dispatch and \
7632             every downstream consumer would silently carry a detached \
7633             copy",
7634        );
7635        assert_eq!(
7636            name.len(),
7637            caixa_slice.len(),
7638            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
7639             as well as in address",
7640        );
7641    }
7642
7643    #[test]
7644    fn validate_gates_child_nome_through_lifted_accessor() {
7645        // Bilateral coherence pin: every `:children :caixa` that
7646        // [`SupervisorSpec::validate`] accepts is one
7647        // [`crate::render::require_valid_dns_1123_label`] accepts on the
7648        // accessor-projected value, and vice versa on the reject side.
7649        // This closes the "the validator reads through the accessor"
7650        // contract structurally — a future silent detour that made the
7651        // accessor return a different byte-string than the validator
7652        // gates against would surface here as a coverage mismatch, not
7653        // as an apply-time DNS-1123 rejection at
7654        // `metadata.name: Invalid value` far from the caixa.lisp source.
7655        // Peer of the M2 sibling
7656        // `validate_parses_prior_versao_through_lifted_accessor`
7657        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
7658        // `validate_membros` peer discipline.
7659        //
7660        // Accept-set sweep: five DNS-1123-label values the upstream gate
7661        // admits.
7662        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
7663            let s = SupervisorSpec {
7664                children: vec![ChildSpec {
7665                    caixa: ok_name.into(),
7666                    versao: "^0.1".into(),
7667                    restart: RestartPolicy::Permanent,
7668                }],
7669                ..SupervisorSpec::default()
7670            };
7671            s.validate().unwrap_or_else(|e| {
7672                panic!(
7673                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
7674                     (upstream DNS-1123 gate accepts it): got {e:?}",
7675                );
7676            });
7677            let c = ChildSpec {
7678                caixa: ok_name.into(),
7679                versao: "^0.1".into(),
7680                restart: RestartPolicy::Permanent,
7681            };
7682            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
7683                .unwrap_or_else(|()| {
7684                    panic!(
7685                        "require_valid_dns_1123_label must accept the accessor-projected \
7686                     :children :caixa {ok_name:?}",
7687                    );
7688                });
7689        }
7690        // Reject-set sweep: five DNS-1123-label-violating shapes the
7691        // upstream gate refuses (empty / uppercase / underscore / dot /
7692        // leading-hyphen). Every rejection at the validator must
7693        // correspond to a rejection when the accessor's projected value
7694        // is fed back through the shared gate.
7695        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
7696            let s = SupervisorSpec {
7697                children: vec![ChildSpec {
7698                    caixa: bad_name.into(),
7699                    versao: "^0.1".into(),
7700                    restart: RestartPolicy::Permanent,
7701                }],
7702                ..SupervisorSpec::default()
7703            };
7704            let err = s.validate().unwrap_err();
7705            assert!(
7706                matches!(
7707                    err,
7708                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
7709                ),
7710                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
7711                 via the DNS-1123 gate: got {err:?}",
7712            );
7713            let c = ChildSpec {
7714                caixa: bad_name.into(),
7715                versao: "^0.1".into(),
7716                restart: RestartPolicy::Permanent,
7717            };
7718            assert!(
7719                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
7720                    .is_err(),
7721                "require_valid_dns_1123_label must reject the accessor-projected \
7722                 :children :caixa {bad_name:?}",
7723            );
7724        }
7725    }
7726
7727    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
7728    //
7729    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
7730    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
7731    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
7732    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
7733    // trio on the peer per-`:children` `String`-carry axis. The three pins
7734    // jointly brace the accessor against every future silent detour that
7735    // would desynchronize it from the raw `.versao` field access the
7736    // requirement gate + error carrier previously open-coded.
7737    //
7738    // Closes the last unlifted per-`:children` `String`-carry axis: the
7739    // pair (`nome`, `versao_requirement`) now jointly projects the
7740    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
7741    // consumer that fans on per-child identity + version pin reads,
7742    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
7743    // pair discipline verbatim.
7744    #[test]
7745    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
7746        // The canonical per-`:children` child-`:versao`-scalar pin:
7747        // [`ChildSpec::versao_requirement`] must return the `:children
7748        // :versao` field byte-for-byte across every Cargo-shaped semver
7749        // requirement value the upstream
7750        // [`crate::render::require_valid_versao_requirement`] gate admits.
7751        // Peer of the sibling
7752        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
7753        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
7754        // substrate-primitive accessor must byte-equal the raw field
7755        // access verbatim across every author-declared value" discipline
7756        // extended to the M2 supervisor-tree per-`:children` arm. Pins
7757        // against a future silent detour that re-canonicalized the
7758        // requirement (an accidental `.to_string()` via
7759        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
7760        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
7761        // silently drifted the error carrier's quoted requirement away
7762        // from the source `caixa.lisp`, an accidental whitespace trim on
7763        // `"^ 0.1"` that no consumer ever produced from the field-access
7764        // side, an accidental per-cluster lacre-projected concrete-version
7765        // rewrite that didn't land on the peer requirement-gate call).
7766        // Five values sweep the accept-set the shared
7767        // [`crate::render::require_valid_versao_requirement`] gate admits
7768        // (caret / tilde / exact / wildcard / bare-major).
7769        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
7770            let c = ChildSpec {
7771                caixa: "worker".into(),
7772                versao: req.into(),
7773                restart: RestartPolicy::Permanent,
7774            };
7775            assert_eq!(
7776                c.versao_requirement(),
7777                req,
7778                "ChildSpec::versao_requirement must return :children :versao \
7779                 verbatim (got {:?}, expected {req:?})",
7780                c.versao_requirement(),
7781            );
7782            assert_eq!(
7783                c.versao_requirement(),
7784                c.versao.as_str(),
7785                "ChildSpec::versao_requirement must byte-equal the .versao \
7786                 field access",
7787            );
7788        }
7789    }
7790
7791    #[test]
7792    fn child_spec_versao_requirement_borrows_from_versao_storage() {
7793        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
7794        // return a `&str` slice that borrows from the typed slot's own
7795        // [`String`] storage — same-address invariant with
7796        // `c.versao.as_str()`. Pins against a future silent detour that
7797        // allocated a fresh `String` (`self.versao.clone()` in the body
7798        // would type-check but silently drop the borrow, and every
7799        // downstream consumer that assumed the returned slice outlives
7800        // `&self` — the [`crate::render::require_valid_versao_requirement`]
7801        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
7802        // `.to_string()` carrier's byte-length assumption — would silently
7803        // misbehave if this accessor produced a detached copy). Peer of
7804        // the sibling `child_spec_nome_borrows_from_caixa_storage`
7805        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
7806        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
7807        // pin on the peer per-`:membros` `:versao` axis.
7808        let c = ChildSpec {
7809            caixa: "worker".into(),
7810            versao: "^0.1".into(),
7811            restart: RestartPolicy::Permanent,
7812        };
7813        let req = c.versao_requirement();
7814        let versao_slice = c.versao.as_str();
7815        assert_eq!(
7816            req.as_ptr(),
7817            versao_slice.as_ptr(),
7818            "ChildSpec::versao_requirement must borrow from the .versao \
7819             String's backing storage — a fresh allocation here means the \
7820             accessor no longer names the substrate-primitive typed \
7821             dispatch and every downstream consumer would silently carry \
7822             a detached copy",
7823        );
7824        assert_eq!(
7825            req.len(),
7826            versao_slice.len(),
7827            "ChildSpec::versao_requirement and .versao.as_str() must \
7828             byte-equal in length as well as in address",
7829        );
7830    }
7831
7832    #[test]
7833    fn validate_gates_child_versao_through_lifted_accessor() {
7834        // Bilateral coherence pin: every `:children :versao` that
7835        // [`SupervisorSpec::validate`] accepts is one
7836        // [`crate::render::require_valid_versao_requirement`] accepts on
7837        // the accessor-projected value, and vice versa on the reject side.
7838        // This closes the "the validator reads through the accessor"
7839        // contract structurally — a future silent detour that made the
7840        // accessor return a different byte-string than the validator gates
7841        // against would surface here as a coverage mismatch, not as a
7842        // resolver-time semver-parse rejection at lacre-closure time far
7843        // from the caixa.lisp source. Peer of the sibling
7844        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
7845        // the per-`:children :caixa` axis and the M2
7846        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
7847        // on the peer per-`:upgrade-from :from` axis.
7848        //
7849        // Accept-set sweep: five Cargo-shaped semver requirement values
7850        // the upstream gate admits (caret / tilde / exact / wildcard /
7851        // bare-major).
7852        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
7853            let s = SupervisorSpec {
7854                children: vec![ChildSpec {
7855                    caixa: "worker".into(),
7856                    versao: ok_req.into(),
7857                    restart: RestartPolicy::Permanent,
7858                }],
7859                ..SupervisorSpec::default()
7860            };
7861            s.validate().unwrap_or_else(|e| {
7862                panic!(
7863                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
7864                     (upstream versao-requirement gate accepts it): got {e:?}",
7865                );
7866            });
7867            let c = ChildSpec {
7868                caixa: "worker".into(),
7869                versao: ok_req.into(),
7870                restart: RestartPolicy::Permanent,
7871            };
7872            crate::render::require_valid_versao_requirement(
7873                c.versao_requirement(),
7874                || (),
7875                |_reason| (),
7876            )
7877            .unwrap_or_else(|()| {
7878                panic!(
7879                    "require_valid_versao_requirement must accept the accessor-projected \
7880                     :children :versao {ok_req:?}",
7881                );
7882            });
7883        }
7884        // Reject-set sweep: five requirement-violating shapes the upstream
7885        // gate refuses. The empty string closes the empty-first arm of the
7886        // shared [`crate::render::require_valid_versao_requirement`]
7887        // cascade; the four non-empty arms exercise distinct semver-parse
7888        // failure modes the M3 peer per-`:membros` reject-set already pins
7889        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
7890        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
7891        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
7892        // shared parser routing means the same reject-set must fail
7893        // identically at the M2 supervisor-tree per-`:children` accessor
7894        // arm here. Every rejection at the validator must correspond to a
7895        // rejection when the accessor's projected value is fed back
7896        // through the shared gate.
7897        //
7898        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
7899        // `"not-a-semver"` are intentionally *not* in the reject-set: the
7900        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
7901        // and the identifier-tail arm's grammar admits some non-canonical
7902        // shapes — matching what the M3 peer test suite already documents
7903        // as the shared parser's accept-set edges.)
7904        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
7905            let s = SupervisorSpec {
7906                children: vec![ChildSpec {
7907                    caixa: "worker".into(),
7908                    versao: bad_req.into(),
7909                    restart: RestartPolicy::Permanent,
7910                }],
7911                ..SupervisorSpec::default()
7912            };
7913            let err = s.validate().unwrap_err();
7914            assert!(
7915                matches!(
7916                    err,
7917                    SupervisorError::EmptyChildVersion { .. }
7918                        | SupervisorError::ChildVersaoInvalid { .. }
7919                ),
7920                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
7921                 via the versao-requirement gate: got {err:?}",
7922            );
7923            let c = ChildSpec {
7924                caixa: "worker".into(),
7925                versao: bad_req.into(),
7926                restart: RestartPolicy::Permanent,
7927            };
7928            assert!(
7929                crate::render::require_valid_versao_requirement(
7930                    c.versao_requirement(),
7931                    || (),
7932                    |_reason| (),
7933                )
7934                .is_err(),
7935                "require_valid_versao_requirement must reject the accessor-projected \
7936                 :children :versao {bad_req:?}",
7937            );
7938        }
7939    }
7940
7941    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
7942    //
7943    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
7944    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
7945    // already project the `String`-carry `(caixa, versao)` fields; the
7946    // `Copy`-composite-enum `restart` field is the third and final axis).
7947    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
7948    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
7949    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
7950    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
7951    // strategy scalar accessor — same "one typed dispatch on the substrate
7952    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
7953    // extended onto the M2 supervisor-slot per-`:children` restart-decision
7954    // axis. The pin below covers the accessor's byte-equal projection
7955    // against the raw field access across every variant in the closed
7956    // accept-set (`Permanent`, `Transient`, `Temporary`).
7957
7958    #[test]
7959    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
7960        // The canonical per-`:children` restart-decision-policy-scalar
7961        // pin: [`ChildSpec::restart`] must return the `:children :restart`
7962        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
7963        // typed slot's own [`RestartPolicy`] storage across every variant
7964        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
7965        // Pins against a future silent detour that re-derived the policy
7966        // from a peer axis (an accidental fallback to
7967        // `if is_supervisor_child { Permanent } else { Temporary }` that
7968        // collapsed the child's kind axis into the restart discriminator),
7969        // a variant remap the operator authors on one consumer without the
7970        // other, or a stale-derive detour that substituted
7971        // [`RestartPolicy::default`] when the field held any explicit
7972        // variant (which would silently collapse the distinction between
7973        // "author explicitly declared `:restart Permanent`" and "author
7974        // omitted the slot and inherited the default" the future
7975        // per-cluster restart-decision override slot depends on).
7976        //
7977        // Peer of the sibling per-`:supervisor`
7978        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
7979        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
7980        // axis and the M3
7981        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
7982        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
7983        // — same "the substrate-primitive accessor must byte-equal the raw
7984        // field access verbatim across every author-declared value"
7985        // discipline extended onto the M2 supervisor-slot per-`:children`
7986        // restart-decision-policy axis, closing the last unlifted axis on
7987        // the per-`:children` [`ChildSpec`] type.
7988        for restart in [
7989            RestartPolicy::Permanent,
7990            RestartPolicy::Transient,
7991            RestartPolicy::Temporary,
7992        ] {
7993            let c = ChildSpec {
7994                caixa: "worker".into(),
7995                versao: "^0.1".into(),
7996                restart,
7997            };
7998            assert_eq!(
7999                c.restart(),
8000                restart,
8001                "ChildSpec::restart must return :children :restart \
8002                 verbatim (got {:?}, expected {restart:?})",
8003                c.restart(),
8004            );
8005            assert_eq!(
8006                c.restart(),
8007                c.restart,
8008                "ChildSpec::restart accessor and .restart field access \
8009                 must byte-equal — the accessor is the substrate-primitive \
8010                 typed dispatch every downstream per-child restart-\
8011                 decision consumer must route through",
8012            );
8013        }
8014    }
8015
8016    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
8017    //
8018    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
8019    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
8020    // distribution-strategy accessor discipline onto the M2 supervisor-slot
8021    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
8022    // scalar axis. The two pins below cover (1) the accessor's byte-equal
8023    // projection against the raw field access across every variant in the
8024    // closed accept-set, and (2) the two-consumer coherence between the
8025    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
8026    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
8027    // carrier's `estrategia:` field — peer of the sibling M3
8028    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
8029    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
8030    // pair on the per-`:placement` distribution-strategy axis.
8031
8032    #[test]
8033    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
8034        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
8035        // pin: [`SupervisorSpec::estrategia`] must return the
8036        // `:supervisor :estrategia` field verbatim as a
8037        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
8038        // [`RestartStrategy`] storage across every variant in the closed
8039        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
8040        // `SimpleOneForOne`). Pins against a future silent detour that
8041        // re-derived the strategy from a peer axis (an accidental
8042        // fallback to `if children.is_empty() { SimpleOneForOne } else {
8043        // OneForOne }` collapse that read the children-count axis into
8044        // the strategy discriminator), a variant remap the operator
8045        // authors on one consumer without the other, or a stale-derive
8046        // detour that substituted [`RestartStrategy::default`] when the
8047        // field held any explicit variant (which would silently collapse
8048        // the distinction between "author explicitly declared
8049        // `:estrategia OneForOne`" and "author omitted the slot and
8050        // inherited the default" the future per-cluster strategy override
8051        // slot depends on). Peer of the sibling M3
8052        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
8053        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
8054        // axis — same "the substrate-primitive accessor must byte-equal
8055        // the raw field access verbatim across every author-declared
8056        // value" discipline extended onto the M2 supervisor-slot
8057        // per-`:supervisor` sibling-restart-strategy axis.
8058        for &estrategia in RestartStrategy::ALL {
8059            // `SimpleOneForOne` requires `children.is_empty()`; the peer
8060            // three strategies require a non-empty static children list.
8061            // Build each shape coherently so the pin's fixture would
8062            // itself pass [`SupervisorSpec::validate`] once fed through
8063            // the sibling coherence pin below — the byte-equal projection
8064            // asserted here is a strictly weaker property (a `Copy` field
8065            // read) that does not depend on `validate` running, but
8066            // keeping the fixture validate-clean means a future extension
8067            // of the pin to exercise `validate` end-to-end does not have
8068            // to re-author the children shape.
8069            //
8070            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
8071            // shape partition through the [`gen_platform::IsVariant`]
8072            // derive-generated
8073            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
8074            // than the raw `matches!(estrategia, RestartStrategy::
8075            // SimpleOneForOne)` open-coded pattern-match — same closed-
8076            // set-typed-enum arm-discriminator dispatch discipline the
8077            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
8078            // convergence (915a934) extended onto its two paired positive
8079            // / negated `matches!` sites and the peer
8080            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
8081            // predicate convergence (766ec63) extended onto the M3 mesh-
8082            // slot per-`:placement` distribution-strategy discriminator
8083            // axis. See the sibling `round_trip_all_strategies` and the
8084            // peer `manifest::tests::
8085            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
8086            // fixture for the two peer sites the same lift closes on.
8087            let children = if estrategia.is_simple_one_for_one() {
8088                Vec::new()
8089            } else {
8090                vec![ChildSpec {
8091                    caixa: "worker".into(),
8092                    versao: "^0.1".into(),
8093                    restart: RestartPolicy::Permanent,
8094                }]
8095            };
8096            let s = SupervisorSpec {
8097                estrategia,
8098                children,
8099                ..SupervisorSpec::default()
8100            };
8101            assert_eq!(
8102                s.estrategia(),
8103                estrategia,
8104                "SupervisorSpec::estrategia must return :supervisor :estrategia \
8105                 verbatim (got {:?}, expected {estrategia:?})",
8106                s.estrategia(),
8107            );
8108            assert_eq!(
8109                s.estrategia(),
8110                s.estrategia,
8111                "SupervisorSpec::estrategia accessor and .estrategia field \
8112                 access must byte-equal — the accessor is the substrate-\
8113                 primitive typed dispatch every downstream sibling-restart-\
8114                 strategy consumer must route through",
8115            );
8116        }
8117    }
8118
8119    #[test]
8120    fn validate_reads_through_lifted_estrategia_accessor() {
8121        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
8122        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
8123        // dispatch (which reads through [`SupervisorSpec::estrategia`]
8124        // to fan across the strategy-arm shape-gate cascades) and the
8125        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
8126        // error carrier's `estrategia:` field (which reads through
8127        // [`SupervisorSpec::estrategia`] to name the strategy the empty
8128        // `:children` list was declared against) must both key off the
8129        // lifted accessor, so any future rebrand on the typed slot's
8130        // reader shape lands at exactly one place. Pins the two-site
8131        // coherence by exercising the `NoChildren` error surface end-to-
8132        // end across every non-`SimpleOneForOne` variant and asserting
8133        // the surfaced `estrategia:` field byte-equals the accessor's
8134        // return. Peer of the sibling M3
8135        // `validate_placement_reads_through_lifted_estrategia_accessor`
8136        // (921fe1b) three-consumer coherence pin on the per-`:placement`
8137        // distribution-strategy axis.
8138        for estrategia in [
8139            RestartStrategy::OneForOne,
8140            RestartStrategy::OneForAll,
8141            RestartStrategy::RestForOne,
8142        ] {
8143            let s = SupervisorSpec {
8144                estrategia,
8145                children: Vec::new(),
8146                ..SupervisorSpec::default()
8147            };
8148            let err = s.validate().unwrap_err();
8149            match err {
8150                SupervisorError::NoChildren { estrategia: e } => {
8151                    assert_eq!(
8152                        e,
8153                        s.estrategia(),
8154                        "NoChildren.estrategia must byte-equal \
8155                         SupervisorSpec::estrategia() — the empty-`:children` \
8156                         refusal reads through the lifted accessor",
8157                    );
8158                    assert_eq!(
8159                        e, estrategia,
8160                        "NoChildren.estrategia must carry the author-declared \
8161                         :supervisor :estrategia variant verbatim (got {e:?}, \
8162                         expected {estrategia:?})",
8163                    );
8164                }
8165                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
8166            }
8167        }
8168    }
8169
8170    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
8171    //
8172    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
8173    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
8174    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
8175    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
8176    // The two pins below cover (1) the accessor's byte-equal projection
8177    // against the raw field access across every representative value in
8178    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
8179    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
8180    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
8181    // zero-floor / cap composition — the validate gate and the accessor
8182    // must route through the same substrate-primitive typed dispatch, so
8183    // any future silent detour that had the accessor perform a
8184    // bounds-collapsing clamp would fail here at caixa-core build time.
8185    // Peer of the sibling M3
8186    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
8187    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
8188
8189    #[test]
8190    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
8191        // The canonical per-`:supervisor` restart-budget-count scalar pin:
8192        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
8193        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
8194        // typed slot's own `u32` storage, byte-equal to the raw field
8195        // access across every representative value in the accept-set —
8196        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
8197        // accept-set the surrounding [`SupervisorSpec::validate`] gate
8198        // carves out on the sibling `ZeroMaxRestarts` refusal),
8199        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
8200        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
8201        // (a past-the-guard sentinel that pins the accessor doesn't
8202        // perform a silent bounds-collapse into `1` on the zero arm —
8203        // validate rejects zero but the accessor must ship the raw slot
8204        // verbatim so a validate-time gate regression surfaces at the
8205        // emit boundary rather than being silently absorbed), `u32::MAX`
8206        // (a past-the-guard sentinel that pins the accessor doesn't
8207        // perform a silent bounds-collapse through
8208        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
8209        //
8210        // Peer of the sibling M3
8211        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
8212        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
8213        // required-scalar axis — same "the substrate-primitive accessor
8214        // must byte-equal the raw field access verbatim across every
8215        // value in the `u32` accept-set" discipline extended onto the M2
8216        // supervisor-slot per-`:supervisor` restart-budget-count axis.
8217        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
8218            let s = SupervisorSpec {
8219                max_restarts,
8220                ..SupervisorSpec::default()
8221            };
8222            assert_eq!(
8223                s.max_restarts(),
8224                max_restarts,
8225                "SupervisorSpec::max_restarts must return :supervisor \
8226                 :max-restarts verbatim (got {}, expected {max_restarts})",
8227                s.max_restarts(),
8228            );
8229            assert_eq!(
8230                s.max_restarts(),
8231                s.max_restarts,
8232                "SupervisorSpec::max_restarts accessor and .max_restarts \
8233                 field access must byte-equal — the accessor is the \
8234                 substrate-primitive typed dispatch every downstream \
8235                 restart-budget-count consumer must route through",
8236            );
8237        }
8238    }
8239
8240    #[test]
8241    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
8242        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
8243        // zero-floor + upper-cap bracket must key off
8244        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
8245        // field access. Structurally: a `SupervisorSpec { max_restarts:
8246        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
8247        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
8248        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
8249        // (with the offending count carried verbatim from the accessor
8250        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
8251        // lower boundary of the accept-set) plus a `SupervisorSpec {
8252        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
8253        // boundary) must pass validate. The four together jointly pin the
8254        // accessor + validate-gate composition: any future silent detour
8255        // that had the accessor return a fresh `1` on the zero arm (a
8256        // `.max_restarts().max(1)` collapse) would silently absorb the
8257        // `ZeroMaxRestarts` refusal at the accessor boundary and the
8258        // validate gate would accept a struct-literal `SupervisorSpec {
8259        // max_restarts: 0, .. }` — the composition pin catches that at
8260        // caixa-core build time.
8261        //
8262        // Peer of the sibling M3
8263        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
8264        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
8265        // composition axis — same "the validate / shape-gate predicate
8266        // must route through the substrate-primitive typed dispatch"
8267        // discipline extended onto the peer M2 supervisor-slot
8268        // required-`u32` composition axis.
8269        let child = ChildSpec {
8270            caixa: "worker".into(),
8271            versao: "^0.1".into(),
8272            restart: RestartPolicy::Permanent,
8273        };
8274        // Zero-floor arm.
8275        let s = SupervisorSpec {
8276            max_restarts: 0,
8277            children: vec![child.clone()],
8278            ..SupervisorSpec::default()
8279        };
8280        assert_eq!(
8281            s.validate().unwrap_err(),
8282            SupervisorError::ZeroMaxRestarts,
8283            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
8284             — the accessor and the validate gate must route through the \
8285             same substrate-primitive typed dispatch on the zero-floor arm",
8286        );
8287        // Cap arm — the surfaced `max_restarts:` field must byte-equal
8288        // the accessor's return so a future rebrand on the accessor
8289        // lands in the diagnostic without a coordinated rewrite.
8290        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
8291        let s = SupervisorSpec {
8292            max_restarts: over_cap,
8293            children: vec![child.clone()],
8294            ..SupervisorSpec::default()
8295        };
8296        match s.validate().unwrap_err() {
8297            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
8298                assert_eq!(
8299                    max_restarts,
8300                    s.max_restarts(),
8301                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
8302                     SupervisorSpec::max_restarts() — the cap-arm refusal \
8303                     reads through the lifted accessor",
8304                );
8305                assert_eq!(
8306                    max_restarts, over_cap,
8307                    "MaxRestartsExceedsCap.max_restarts must carry the \
8308                     author-declared :supervisor :max-restarts value \
8309                     verbatim (got {max_restarts}, expected {over_cap})",
8310                );
8311            }
8312            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
8313        }
8314        // Lower + upper accept-set boundaries.
8315        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
8316            let s = SupervisorSpec {
8317                max_restarts,
8318                children: vec![child.clone()],
8319                ..SupervisorSpec::default()
8320            };
8321            assert!(
8322                s.validate().is_ok(),
8323                "validate must accept max_restarts == {max_restarts} \
8324                 (an accept-set boundary of \
8325                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
8326            );
8327        }
8328    }
8329
8330    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
8331    //
8332    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
8333    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
8334    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
8335    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
8336    // supervisor-slot per-`:supervisor` restart-intensity-denominator
8337    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
8338    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
8339    // per-`:supervisor` scalar-value axis. The three pins below cover
8340    // (1) the accessor's byte-equal projection against the raw field
8341    // access across every representative value in the `Option<Duration>`
8342    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
8343    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
8344    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
8345    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
8346    // `if let Some(w) = self.restart_window() { … }` bracket-arm
8347    // composition — the validate gate and the accessor must route through
8348    // the same substrate-primitive typed dispatch, so any future silent
8349    // detour that had the accessor perform a bounds-collapsing clamp
8350    // would fail here at caixa-core build time, and (3) the accessor's
8351    // by-copy idempotence pin — the returned `Option<Duration>` must
8352    // outlive `&self` and two successive calls must return byte-equal
8353    // values. Peer of the sibling M2
8354    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
8355    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
8356    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
8357    // (7073d0f) pin on the per-`:politicas :timeout` axis.
8358
8359    #[test]
8360    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
8361        // The canonical per-`:supervisor` restart-intensity-denominator
8362        // scalar pin: [`SupervisorSpec::restart_window`] must return the
8363        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
8364        // `Option<Duration>`, `Copy`-projected from the typed slot's own
8365        // `Option<Duration>` storage, byte-equal to the raw field access
8366        // across every representative value in the accept-set — `None`
8367        // (the "never reset — every restart across the supervisor's
8368        // lifetime counts against the sibling `:max-restarts` budget"
8369        // sentinel the field's own docstring names and the peer
8370        // `validate_accepts_none_restart_window` pin locks in on the
8371        // [`SupervisorSpec::validate`] entry-side),
8372        // `Some(Duration::from_millis(1))` (the structural minimum a
8373        // validated `:restart-window` may carry, the integer-millisecond
8374        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
8375        // everything sub-ms; `Duration::ZERO` is separately rejected by
8376        // [`SupervisorError::RestartWindowZero`]),
8377        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
8378        // surrounding [`SupervisorSpec::validate`] gate carves out on the
8379        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
8380        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
8381        // accessor doesn't perform a silent bounds-collapse into `None` on
8382        // the zero-Duration arm — validate rejects zero but the accessor
8383        // must ship the raw slot verbatim so a validate-time gate
8384        // regression surfaces at the emit boundary rather than being
8385        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
8386        // sentinel that pins the accessor doesn't perform a silent
8387        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
8388        // return path).
8389        //
8390        // Peer of the sibling M2
8391        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
8392        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
8393        // sibling M3
8394        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
8395        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
8396        // substrate-primitive accessor must byte-equal the raw field
8397        // access verbatim across every value in the `Option<Duration>`
8398        // accept-set" discipline extended onto the M2 supervisor-slot
8399        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
8400        // silent detour that re-derived the restart-window from a peer
8401        // axis (an accidental `.max_restarts.into()` collapse that read
8402        // the restart-budget-count as a duration — the two axes serve
8403        // different halves of the `MaxIntensity / Period` restart-
8404        // intensity ratio, and confusing them silently inverts the
8405        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
8406        // "zero means never reset" collapse (the canonical
8407        // `Option<Duration>` → `Duration` collapse footgun the
8408        // [`SupervisorError::RestartWindowZero`] validate arm guards on
8409        // the peer zero-floor axis; a zero period either trips on the
8410        // first failure or never trips depending on operator
8411        // interpretation, neither of which is the author's "never reset"
8412        // intent that `None` expresses structurally), or a per-arm
8413        // variant swap that landed on one consumer without the other.
8414        for restart_window in [
8415            None,
8416            Some(Duration::from_millis(1)),
8417            Some(SUPERVISOR_RESTART_WINDOW_MAX),
8418            Some(Duration::ZERO),
8419            Some(Duration::MAX),
8420        ] {
8421            let s = SupervisorSpec {
8422                restart_window,
8423                ..SupervisorSpec::default()
8424            };
8425            assert_eq!(
8426                s.restart_window(),
8427                restart_window,
8428                "SupervisorSpec::restart_window must return :supervisor \
8429                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
8430                s.restart_window(),
8431            );
8432            assert_eq!(
8433                s.restart_window(),
8434                s.restart_window,
8435                "SupervisorSpec::restart_window accessor and \
8436                 .restart_window field access must byte-equal — the \
8437                 accessor is the substrate-primitive typed dispatch every \
8438                 downstream restart-intensity-denominator consumer must \
8439                 route through",
8440            );
8441        }
8442    }
8443
8444    #[test]
8445    fn validate_restart_window_bracket_arm_routes_through_accessor() {
8446        // Composition pin: [`SupervisorSpec::validate`]'s
8447        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
8448        // zero-floor + integer-millisecond canonical-form + upper-cap
8449        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
8450        // the raw `.restart_window` field access. Structurally: a
8451        // `SupervisorSpec { restart_window: None, .. }` must pass the
8452        // arm gate structurally (the `if let Some(_)` shape returns
8453        // early on the `None` arm — the accessor and the validate gate
8454        // must agree on `None → skip the bracket cascade` so an authored
8455        // `:restart-window ()` structurally routes through the "never
8456        // reset" sentinel path), a `SupervisorSpec { restart_window:
8457        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
8458        // refusal exactly, a `SupervisorSpec { restart_window:
8459        // Some(Duration::from_micros(1500)), .. }` must surface the
8460        // `RestartWindowNotCanonical` refusal exactly (with the offending
8461        // duration carried verbatim from the accessor return), a
8462        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
8463        // + Duration::from_millis(1)), .. }` must surface the
8464        // `RestartWindowExceedsCap` refusal exactly (with the offending
8465        // duration carried verbatim from the accessor return), and a
8466        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
8467        // .. }` (the lower boundary of the accept-set) plus a
8468        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
8469        // .. }` (the upper boundary) must pass validate. The six together
8470        // jointly pin the accessor + validate-gate composition: any future
8471        // silent detour that had the accessor return a fresh `None` on any
8472        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
8473        // collapse) would silently absorb the `RestartWindowZero` refusal
8474        // at the accessor boundary and the validate gate would accept a
8475        // struct-literal `SupervisorSpec { restart_window:
8476        // Some(Duration::ZERO), .. }` — the composition pin catches that
8477        // at caixa-core build time.
8478        //
8479        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
8480        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
8481        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
8482        // accessor-composition pin on the per-`:politicas :timeout` axis —
8483        // same "the validate / shape-gate predicate must route through
8484        // the substrate-primitive typed dispatch" discipline extended
8485        // onto the peer M2 supervisor-slot optional-`Duration` axis.
8486        let child = ChildSpec {
8487            caixa: "worker".into(),
8488            versao: "^0.1".into(),
8489            restart: RestartPolicy::Permanent,
8490        };
8491        // None arm — must not surface any :restart-window-shaped refusal;
8492        // the `if let Some(_)` bracket returns early on `None` structurally.
8493        let s = SupervisorSpec {
8494            restart_window: None,
8495            children: vec![child.clone()],
8496            ..SupervisorSpec::default()
8497        };
8498        assert!(
8499            s.validate().is_ok(),
8500            "validate must accept restart_window: None (the never-reset \
8501             sentinel) — the `if let Some(_)` bracket returns early on \
8502             the None arm and the accessor must agree",
8503        );
8504        // Zero-floor arm.
8505        let s = SupervisorSpec {
8506            restart_window: Some(Duration::ZERO),
8507            children: vec![child.clone()],
8508            ..SupervisorSpec::default()
8509        };
8510        assert_eq!(
8511            s.validate().unwrap_err(),
8512            SupervisorError::RestartWindowZero,
8513            "validate must reject restart_window == Some(Duration::ZERO) \
8514             with RestartWindowZero — the accessor and the validate gate \
8515             must route through the same substrate-primitive typed \
8516             dispatch on the zero-floor arm",
8517        );
8518        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
8519        // byte-equal the accessor's return so a future rebrand on the
8520        // accessor lands in the diagnostic without a coordinated rewrite.
8521        let sub_ms = Duration::from_micros(1500);
8522        let s = SupervisorSpec {
8523            restart_window: Some(sub_ms),
8524            children: vec![child.clone()],
8525            ..SupervisorSpec::default()
8526        };
8527        match s.validate().unwrap_err() {
8528            SupervisorError::RestartWindowNotCanonical { window } => {
8529                assert_eq!(
8530                    Some(window),
8531                    s.restart_window(),
8532                    "RestartWindowNotCanonical.window must byte-equal \
8533                     SupervisorSpec::restart_window().unwrap() — the \
8534                     non-canonical-arm refusal reads through the lifted \
8535                     accessor",
8536                );
8537                assert_eq!(
8538                    window, sub_ms,
8539                    "RestartWindowNotCanonical.window must carry the \
8540                     author-declared :supervisor :restart-window value \
8541                     verbatim (got {window:?}, expected {sub_ms:?})",
8542                );
8543            }
8544            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
8545        }
8546        // Cap arm — the surfaced `window:` field must byte-equal the
8547        // accessor's return.
8548        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
8549        let s = SupervisorSpec {
8550            restart_window: Some(over_cap),
8551            children: vec![child.clone()],
8552            ..SupervisorSpec::default()
8553        };
8554        match s.validate().unwrap_err() {
8555            SupervisorError::RestartWindowExceedsCap { window } => {
8556                assert_eq!(
8557                    Some(window),
8558                    s.restart_window(),
8559                    "RestartWindowExceedsCap.window must byte-equal \
8560                     SupervisorSpec::restart_window().unwrap() — the \
8561                     cap-arm refusal reads through the lifted accessor",
8562                );
8563                assert_eq!(
8564                    window, over_cap,
8565                    "RestartWindowExceedsCap.window must carry the \
8566                     author-declared :supervisor :restart-window value \
8567                     verbatim (got {window:?}, expected {over_cap:?})",
8568                );
8569            }
8570            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
8571        }
8572        // Lower + upper accept-set boundaries.
8573        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
8574            let s = SupervisorSpec {
8575                restart_window: Some(restart_window),
8576                children: vec![child.clone()],
8577                ..SupervisorSpec::default()
8578            };
8579            assert!(
8580                s.validate().is_ok(),
8581                "validate must accept restart_window == Some({restart_window:?}) \
8582                 (an accept-set boundary of \
8583                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
8584            );
8585        }
8586    }
8587
8588    #[test]
8589    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
8590        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
8591        // `Option<Duration>` by copy — `Duration` is `Copy` (so
8592        // `Option<Duration>` is `Copy`) and the accessor must return by
8593        // value, not by reference. Peer of the sibling M2
8594        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
8595        // per-`:limits :wall-clock` axis and the sibling M3
8596        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
8597        // per-`:politicas :timeout` axis, extended onto the peer M2
8598        // supervisor-slot `Option<Duration>` copy-invariant shape — the
8599        // accessor's returned `Option<Duration>` must outlive `&self`
8600        // (multiple calls must return equal values from a dropped-`&self`
8601        // copy, since the returned Option carries no borrow), and calling
8602        // the accessor twice on the same SupervisorSpec must yield the
8603        // same `Option<Duration>` verbatim (idempotent, no side effects
8604        // on `&self`).
8605        //
8606        // Pins against a future silent detour that returned
8607        // `Option<&Duration>` (which would type-check but silently break
8608        // every downstream caller — the future wasm-operator's
8609        // per-supervisor restart-intensity counter consumes `Duration` by
8610        // value and `&Duration` would fold to a detached copy at the call
8611        // site), an accidental `Option::as_ref()` projection
8612        // (`self.restart_window.as_ref()` would also type-check but
8613        // return `Option<&Duration>`), or a one-arm-only accessor that
8614        // reads `Some(*w)` in the Some arm but reads a fresh
8615        // `Default::default()` (which would collapse to `Duration::ZERO`,
8616        // not `None`) in the None arm — a footgun the
8617        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
8618        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
8619        // requires `Period > 0` and `None` structurally expresses "never
8620        // reset" instead.
8621        for restart_window in [
8622            None,
8623            Some(Duration::from_millis(1)),
8624            Some(Duration::from_secs(60)),
8625            Some(SUPERVISOR_RESTART_WINDOW_MAX),
8626        ] {
8627            let s = SupervisorSpec {
8628                restart_window,
8629                ..SupervisorSpec::default()
8630            };
8631            let first = s.restart_window();
8632            let second = s.restart_window();
8633            assert_eq!(
8634                first, second,
8635                "SupervisorSpec::restart_window must be idempotent — two \
8636                 successive calls on the same &self must return the \
8637                 same Option<Duration>",
8638            );
8639            assert_eq!(
8640                first, restart_window,
8641                "SupervisorSpec::restart_window must return :supervisor \
8642                 :restart-window verbatim by copy — got {first:?}, \
8643                 expected {restart_window:?}",
8644            );
8645        }
8646    }
8647
8648    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
8649    //
8650    // The [`SupervisorSpec::children`] accessor lift is the seed of the
8651    // slice-return (`&[T]`) accessor discipline on the substrate — the four
8652    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
8653    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
8654    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
8655    // access at the time of this seed, and inherit this pin family's
8656    // discipline as future compounding runs migrate their consumers. The
8657    // three pins below cover (1) the accessor's byte-equal projection
8658    // against the raw field access across the empty / singleton / cohort
8659    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
8660    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
8661    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
8662    // consumer routing through the accessor on both arms, and (3) the
8663    // per-child validate loop's traversal reading the same slice-view the
8664    // accessor projects. Peer of the sibling M2
8665    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
8666    // two-consumer coherence pin on the per-`:supervisor`
8667    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
8668    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
8669
8670    #[test]
8671    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
8672        // The canonical per-`:supervisor` static-child-list scalar-shape
8673        // pin: [`SupervisorSpec::children`] must return the `:supervisor
8674        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
8675        // slice-view over the same backing buffer the raw
8676        // `self.children.as_slice()` field access borrows from, byte-
8677        // equal across every representative fixture in the accept-set —
8678        // the empty slice (the `SimpleOneForOne`-arm sentinel),
8679        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
8680        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
8681        // with the peer three restart-policy variants in play).
8682        //
8683        // Pins against a future silent detour that returned
8684        // `&Vec<ChildSpec>` (which would type-check but leak the
8685        // storage-side `Vec`'s grow/push/reserve surface no consumer of
8686        // the typed view reaches for), a fresh-allocated
8687        // `Vec<ChildSpec>` copy (which would type-check via a coercion
8688        // but silently break every downstream caller that relied on the
8689        // slice sharing the backing buffer's identity), or an
8690        // out-of-order or length-drifted projection (which would silently
8691        // split the per-child validate loop's traversal input from the
8692        // paired partition-dispatch `.is_empty()` probe's input).
8693        //
8694        // Peer of the sibling
8695        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
8696        // (eafb619) `Copy`-composite-enum byte-equal pin on the
8697        // per-`:supervisor` sibling-restart-strategy axis, extended onto
8698        // the per-`:supervisor` static-child-list `Vec`-carry axis.
8699        let fixtures: Vec<Vec<ChildSpec>> = vec![
8700            Vec::new(),
8701            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
8702            vec![
8703                child("worker", "^0.1", RestartPolicy::Permanent),
8704                child("cache-server", "^0.1", RestartPolicy::Transient),
8705            ],
8706            vec![
8707                child("worker", "^0.1", RestartPolicy::Permanent),
8708                child("cache-server", "^0.1", RestartPolicy::Transient),
8709                child("scratch-job", "^0.1", RestartPolicy::Temporary),
8710            ],
8711        ];
8712        for children in fixtures {
8713            let s = SupervisorSpec {
8714                children: children.clone(),
8715                ..SupervisorSpec::default()
8716            };
8717            assert_eq!(
8718                s.children(),
8719                children.as_slice(),
8720                "SupervisorSpec::children must return :supervisor \
8721                 :children verbatim (got {:?}, expected {:?})",
8722                s.children(),
8723                children.as_slice(),
8724            );
8725            assert_eq!(
8726                s.children(),
8727                s.children.as_slice(),
8728                "SupervisorSpec::children accessor and \
8729                 .children.as_slice() field access must byte-equal — \
8730                 the accessor is the substrate-primitive typed \
8731                 dispatch every downstream static-child-list consumer \
8732                 must route through",
8733            );
8734            assert_eq!(
8735                s.children().len(),
8736                s.children.len(),
8737                "SupervisorSpec::children().len() must byte-equal \
8738                 self.children.len() — a length-drift would silently \
8739                 split the paired partition-dispatch `.is_empty()` \
8740                 probe input from the per-child validate loop's \
8741                 traversal input",
8742            );
8743        }
8744    }
8745
8746    #[test]
8747    fn validate_reads_through_lifted_children_accessor() {
8748        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
8749        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
8750        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
8751        // when the accessor projects a non-empty slice under a
8752        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
8753        // `self.children().is_empty()` refusal probe (which must trip
8754        // [`SupervisorError::NoChildren`] when the accessor projects the
8755        // empty slice under any peer estrategia), and the per-child
8756        // validate loop's `for child in self.children()` traversal
8757        // (which must reach every entry in the same order the accessor
8758        // projects) must all key off the lifted accessor, so any future
8759        // rebrand on the typed slot's reader shape lands at exactly one
8760        // place. Pins the three-site coherence by exercising each
8761        // production consumer end-to-end: (1) the
8762        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
8763        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
8764        // refusal under the empty slice + non-`SimpleOneForOne`
8765        // estrategia across every peer variant, and (3) the per-child
8766        // duplicate-detection surface fires on the second entry of a
8767        // two-child cohort that shares a `:caixa` name (which requires
8768        // the loop to reach both entries — a first-entry-only projection
8769        // would silently pass since the dedup HashSet has room for the
8770        // first insert).
8771        //
8772        // Peer of the sibling M2
8773        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
8774        // two-consumer coherence pin on the per-`:supervisor`
8775        // sibling-restart-strategy axis, extended onto the
8776        // per-`:supervisor` static-child-list `Vec`-carry axis.
8777
8778        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
8779        // `SimpleOneForOne` estrategia must trip
8780        // `SimpleOneForOneWithStaticChildren`.
8781        let s = SupervisorSpec {
8782            estrategia: RestartStrategy::SimpleOneForOne,
8783            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
8784            ..SupervisorSpec::default()
8785        };
8786        assert_eq!(
8787            s.validate().unwrap_err(),
8788            SupervisorError::SimpleOneForOneWithStaticChildren,
8789            "SimpleOneForOne + non-empty children must trip \
8790             SimpleOneForOneWithStaticChildren — the accessor projects \
8791             a non-empty slice, and the SimpleOneForOne-arm refusal \
8792             probe reads through the lifted accessor",
8793        );
8794        assert!(
8795            !s.children().is_empty(),
8796            "the SimpleOneForOne-arm refusal input must be a non-empty \
8797             slice per the accessor's projection",
8798        );
8799
8800        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
8801        // under any peer estrategia must trip `NoChildren`.
8802        for estrategia in [
8803            RestartStrategy::OneForOne,
8804            RestartStrategy::OneForAll,
8805            RestartStrategy::RestForOne,
8806        ] {
8807            let s = SupervisorSpec {
8808                estrategia,
8809                children: Vec::new(),
8810                ..SupervisorSpec::default()
8811            };
8812            match s.validate().unwrap_err() {
8813                SupervisorError::NoChildren { estrategia: e } => {
8814                    assert_eq!(
8815                        e, estrategia,
8816                        "NoChildren.estrategia must carry the author-\
8817                         declared :supervisor :estrategia variant \
8818                         verbatim (got {e:?}, expected {estrategia:?})",
8819                    );
8820                }
8821                other => panic!(
8822                    "expected NoChildren, got {other:?} for \
8823                     estrategia={estrategia:?}"
8824                ),
8825            }
8826            assert!(
8827                s.children().is_empty(),
8828                "the non-SimpleOneForOne-arm refusal input must be the \
8829                 empty slice per the accessor's projection",
8830            );
8831        }
8832
8833        // (3) Per-child validate loop: a two-child cohort that shares a
8834        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
8835        // reach both entries through the accessor.
8836        let s = SupervisorSpec {
8837            estrategia: RestartStrategy::OneForOne,
8838            children: vec![
8839                child("worker", "^0.1", RestartPolicy::Permanent),
8840                child("worker", "^0.2", RestartPolicy::Transient),
8841            ],
8842            ..SupervisorSpec::default()
8843        };
8844        match s.validate().unwrap_err() {
8845            SupervisorError::DuplicateChildCaixa { caixa } => {
8846                assert_eq!(
8847                    caixa, "worker",
8848                    "DuplicateChildCaixa.caixa must carry the shared \
8849                     child `:caixa` name verbatim",
8850                );
8851            }
8852            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
8853        }
8854        assert_eq!(
8855            s.children().len(),
8856            2,
8857            "the per-child validate loop's traversal input must be a \
8858             two-element slice per the accessor's projection",
8859        );
8860    }
8861
8862    // Shared helper for the M2 per-`:children` per-slot-gate ≡
8863    // `validate` equivalence pins: builds an `OneForOne`-estrategia
8864    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
8865    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
8866    // bracket all pass cleanly so the sole failing surface is the
8867    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
8868    // pins the two-altitude equivalence on the paired probe.
8869    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
8870        let s = SupervisorSpec {
8871            estrategia: RestartStrategy::OneForOne,
8872            children,
8873            ..SupervisorSpec::default()
8874        };
8875        let via_gate = s.validate_children().unwrap_err();
8876        let via_validate = s.validate().unwrap_err();
8877        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
8878        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
8879        assert_eq!(
8880            via_gate, via_validate,
8881            "per-slot gate ≡ validate() must discriminate the same \
8882             refusal shape",
8883        );
8884    }
8885
8886    #[test]
8887    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
8888        // Fail-before-pass-after equivalence pin on the M2
8889        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
8890        // convergence — sibling of the M3 mesh-slot
8891        // `validate_membros_*` / `validate_contratos_*` /
8892        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
8893        // peer per-entry axes. Sweeps four of the five refusal shapes
8894        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
8895        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
8896        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
8897        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
8898        // duplicate-`:caixa` fan-out. Companion pin
8899        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
8900        // covers `ChildVersaoInvalid` (whose parser-owned reason string
8901        // needs pattern-matching, not equality) and the clean-pass
8902        // canonical fixture; together the two pins guarantee the
8903        // per-slot gate and `validate` discriminate the same set on
8904        // every per-child-covered input.
8905        assert_validate_children_matches_gate(
8906            vec![child("", "^0.1", RestartPolicy::Permanent)],
8907            &SupervisorError::EmptyChildName,
8908        );
8909        assert_validate_children_matches_gate(
8910            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
8911            &SupervisorError::ChildCaixaInvalid {
8912                caixa: "Worker".into(),
8913                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
8914            },
8915        );
8916        assert_validate_children_matches_gate(
8917            vec![child("worker", "", RestartPolicy::Permanent)],
8918            &SupervisorError::EmptyChildVersion {
8919                caixa: "worker".into(),
8920            },
8921        );
8922        assert_validate_children_matches_gate(
8923            vec![
8924                child("worker", "^0.1", RestartPolicy::Permanent),
8925                child("worker", "^0.2", RestartPolicy::Transient),
8926            ],
8927            &SupervisorError::DuplicateChildCaixa {
8928                caixa: "worker".into(),
8929            },
8930        );
8931    }
8932
8933    #[test]
8934    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
8935        // Second half of the two-altitude equivalence pin — covers the
8936        // one refusal shape whose reason string is parser-owned
8937        // (`ChildVersaoInvalid`, whose reason comes from the shared
8938        // [`crate::version::parse_requirement`] impl and may drift) and
8939        // the clean-pass canonical fixture. Sibling pin
8940        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
8941        // covers the four equality-comparable refusal shapes.
8942        let s_bad_versao = SupervisorSpec {
8943            estrategia: RestartStrategy::OneForOne,
8944            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
8945            ..SupervisorSpec::default()
8946        };
8947        let via_gate = s_bad_versao.validate_children().unwrap_err();
8948        let via_validate = s_bad_versao.validate().unwrap_err();
8949        match (&via_gate, &via_validate) {
8950            (
8951                SupervisorError::ChildVersaoInvalid {
8952                    caixa: cg,
8953                    versao: vg,
8954                    ..
8955                },
8956                SupervisorError::ChildVersaoInvalid {
8957                    caixa: cv,
8958                    versao: vv,
8959                    ..
8960                },
8961            ) => {
8962                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
8963                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
8964                assert_eq!(cv, "worker", "validate() :caixa carrier");
8965                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
8966            }
8967            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
8968        }
8969        assert_eq!(
8970            via_gate, via_validate,
8971            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
8972        );
8973
8974        let s_ok = SupervisorSpec {
8975            estrategia: RestartStrategy::OneForOne,
8976            children: vec![
8977                child("worker-a", "^0.1", RestartPolicy::Permanent),
8978                child("worker-b", "~0.2.3", RestartPolicy::Transient),
8979                child("collector", "*", RestartPolicy::Temporary),
8980            ],
8981            ..SupervisorSpec::default()
8982        };
8983        s_ok.validate_children()
8984            .expect("per-slot gate must accept the clean-pass fixture");
8985        s_ok.validate()
8986            .expect("validate() must accept the clean-pass fixture");
8987    }
8988
8989    #[test]
8990    fn validate_children_is_self_contained_on_children_slot() {
8991        // Self-containment pin: [`SupervisorSpec::validate_children`]
8992        // resolves the per-child cascade against `&self` alone, without
8993        // depending on the peer `:estrategia`/`:max-restarts`/
8994        // `:restart-window` gates having run first — same posture the M3
8995        // peer per-slot gates carry (`validate_membros`,
8996        // `validate_contratos`, `validate_entrada`, `validate_placement`,
8997        // routing through their own oracles rather than borrowing state
8998        // threaded down from `validate`). A future consumer that reaches
8999        // the per-slot gate directly on a spec whose peer slots would
9000        // fail `validate` still surfaces the per-child refusal, not the
9001        // peer refusal.
9002        //
9003        // Construct a spec whose `:max-restarts` is `0` (which would
9004        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
9005        // the partition-dispatch) and whose `:children` carries a
9006        // `DuplicateChildCaixa` shape: the per-slot gate called directly
9007        // must surface `DuplicateChildCaixa`, proving it does not depend
9008        // on the peer `:max-restarts` gate running first.
9009        let s = SupervisorSpec {
9010            estrategia: RestartStrategy::OneForOne,
9011            max_restarts: 0,
9012            restart_window: Some(Duration::from_secs(60)),
9013            children: vec![
9014                child("worker", "^0.1", RestartPolicy::Permanent),
9015                child("worker", "^0.2", RestartPolicy::Transient),
9016            ],
9017        };
9018        assert_eq!(
9019            s.validate_children().unwrap_err(),
9020            SupervisorError::DuplicateChildCaixa {
9021                caixa: "worker".into(),
9022            },
9023            "per-slot gate must resolve per-child refusal directly against \
9024             `&self` — a dependency on the peer `:max-restarts` gate \
9025             running first would surface ZeroMaxRestarts here instead",
9026        );
9027        // The peer gate is still the surface `validate` reaches — pin
9028        // the ordering to establish that `validate_children` truly runs
9029        // last in `validate`'s dispatch, so a direct call bypasses the
9030        // peer gates on any spec whose per-child cascade would fail.
9031        assert_eq!(
9032            s.validate().unwrap_err(),
9033            SupervisorError::ZeroMaxRestarts,
9034            "validate() must surface the peer `:max-restarts` gate before \
9035             reaching the per-child cascade — this pins the dispatch \
9036             ordering the per-slot gate's self-containment complements",
9037        );
9038    }
9039
9040    #[test]
9041    fn child_spec_restart_accessor_is_const_fn() {
9042        // The [`ChildSpec::restart`] per-`:children` restart-decision-
9043        // policy `Copy`-return scalar accessor is declared
9044        // `#[must_use] pub const fn` — matching the sibling M2
9045        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
9046        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
9047        // both converted in this commit), the sibling M2
9048        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
9049        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
9050        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
9051        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
9052        // `Copy`-return `pub const fn` scalar accessors on the sibling
9053        // M3 surface. Pin the `const`-eval posture here so a future
9054        // accidental downgrade to non-`const` (an added runtime helper
9055        // reachable only from a non-`const` context, an
9056        // `Option<RestartPolicy>`-shape migration on the per-child
9057        // restart-decision axis once heterogeneous per-cluster
9058        // restart-policy overlays land that would silently drop the
9059        // `const` qualifier, a manual hand-rolled shadow) trips at
9060        // caixa-core build time rather than surfacing as a downstream
9061        // `const`-context regression far from the declaration.
9062        //
9063        // Same shape as the sibling M3
9064        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
9065        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
9066        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
9067        // accessor axis — the load-bearing witness lives in the
9068        // module-scope `const fn` wrapper `restart_via_const_fn` below:
9069        // a body that calls [`ChildSpec::restart`] under a `const fn`
9070        // signature is well-formed only when the callee is itself
9071        // `const fn`, so any future accidental downgrade of
9072        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
9073        // build time (const-eval E0015 `cannot call non-const method`),
9074        // strictly stronger than a runtime `assert!(CONST)` and
9075        // side-stepping the destructor-in-const restriction that
9076        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
9077        // items on `ChildSpec`'s `String` carriers.
9078        //
9079        // The runtime body sweeps every closed-set [`RestartPolicy`]
9080        // arm and asserts the wrapped and direct dispatches agree.
9081        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
9082            c.restart()
9083        }
9084        for restart in [
9085            RestartPolicy::Permanent,
9086            RestartPolicy::Transient,
9087            RestartPolicy::Temporary,
9088        ] {
9089            let c = ChildSpec {
9090                caixa: "worker".into(),
9091                versao: "^0.1".into(),
9092                restart,
9093            };
9094            assert_eq!(
9095                restart_via_const_fn(&c),
9096                c.restart(),
9097                "const-fn-wrapped and direct dispatch on \
9098                 ChildSpec::restart must agree for {restart:?}",
9099            );
9100            assert_eq!(
9101                c.restart(),
9102                restart,
9103                "ChildSpec::restart must return the storage-side \
9104                 RestartPolicy verbatim for {restart:?} (a violation \
9105                 means the accessor stopped being a raw field-return \
9106                 copy)",
9107            );
9108        }
9109    }
9110
9111    #[test]
9112    fn supervisor_spec_estrategia_accessor_is_const_fn() {
9113        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
9114        // sibling-restart-strategy `Copy`-return scalar accessor is
9115        // declared `#[must_use] pub const fn` — matching the sibling M2
9116        // per-`:children` [`ChildSpec::restart`] (pinned by
9117        // [`child_spec_restart_accessor_is_const_fn`] above, both
9118        // converted in this commit), the sibling M2 per-`:supervisor`
9119        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
9120        // accessor already `pub const fn`, and mirroring the peer M3
9121        // mesh-slot per-`:placement`
9122        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
9123        // `pub const fn` scalar accessor whose method-name discipline
9124        // the [`SupervisorSpec::estrategia`] method was authored to
9125        // match. Pin the `const`-eval posture here so a future
9126        // accidental downgrade to non-`const` (an added runtime helper
9127        // reachable only from a non-`const` context, an
9128        // `Option<RestartStrategy>`-shape migration once the substrate
9129        // grows per-cluster strategy overlays that would silently drop
9130        // the `const` qualifier, a manual hand-rolled shadow) trips at
9131        // caixa-core build time rather than surfacing as a downstream
9132        // `const`-context regression far from the declaration.
9133        //
9134        // Same shape as the sibling
9135        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
9136        // load-bearing witness lives in the module-scope `const fn`
9137        // wrapper `estrategia_via_const_fn` below: a body that calls
9138        // [`SupervisorSpec::estrategia`] under a `const fn` signature
9139        // is well-formed only when the callee is itself `const fn`,
9140        // side-stepping the destructor-in-const restriction that would
9141        // otherwise block a direct
9142        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
9143        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
9144        // carriers.
9145        //
9146        // The runtime body sweeps every closed-set [`RestartStrategy`]
9147        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
9148        // direct dispatches agree.
9149        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
9150            s.estrategia()
9151        }
9152        for &estrategia in RestartStrategy::ALL {
9153            let s = SupervisorSpec {
9154                estrategia,
9155                max_restarts: 5,
9156                restart_window: Some(Duration::from_secs(60)),
9157                children: Vec::new(),
9158            };
9159            assert_eq!(
9160                estrategia_via_const_fn(&s),
9161                s.estrategia(),
9162                "const-fn-wrapped and direct dispatch on \
9163                 SupervisorSpec::estrategia must agree for {estrategia:?}",
9164            );
9165            assert_eq!(
9166                s.estrategia(),
9167                estrategia,
9168                "SupervisorSpec::estrategia must return the storage-side \
9169                 RestartStrategy verbatim for {estrategia:?} (a violation \
9170                 means the accessor stopped being a raw field-return \
9171                 copy)",
9172            );
9173        }
9174    }
9175
9176    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
9177    // macro definition (see the paired doc-block above the macro
9178    // definition) — every generated `<ctor>(caixa: &str) -> Self`
9179    // constructor folds the uniform `Self::<Variant> { caixa:
9180    // caixa.to_string() }` one-field struct-literal onto one substrate
9181    // primitive. The three per-variant equivalence pins below
9182    // (fail-before-pass-after by construction — a byte-mismatched macro
9183    // arm would trip its equivalence pin first) lock each generated
9184    // constructor to its struct-literal peer under `PartialEq`, so
9185    // every wire-up in [`SupervisorSpec::validate_children`] and
9186    // [`validate_no_self_supervision`] on that variant produces a
9187    // byte-equal `SupervisorError` to the pre-lift open-coded
9188    // struct-literal. The cross-axis pin that follows (non-default
9189    // caixa name) routes the sole constructor input axis through
9190    // `.to_string()`, so the fold does not silently collapse onto a
9191    // fixed name.
9192    //
9193    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
9194    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
9195    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
9196    // `missing_entry_ctor_matches_struct_literal_wrap` /
9197    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
9198    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
9199    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
9200    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
9201    // on the six sibling ctor families the recent trajectory closed
9202    // on the peer `LayoutError` / `AplicacaoError` envelopes.
9203
9204    #[test]
9205    fn empty_child_version_ctor_matches_struct_literal_wrap() {
9206        assert_eq!(
9207            SupervisorError::empty_child_version("worker"),
9208            SupervisorError::EmptyChildVersion {
9209                caixa: "worker".to_string(),
9210            },
9211            "generated empty_child_version ctor must produce byte-equal \
9212             SupervisorError to the open-coded struct-literal wrap on the \
9213             same &str fixture",
9214        );
9215    }
9216
9217    #[test]
9218    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
9219        assert_eq!(
9220            SupervisorError::duplicate_child_caixa("worker"),
9221            SupervisorError::DuplicateChildCaixa {
9222                caixa: "worker".to_string(),
9223            },
9224            "generated duplicate_child_caixa ctor must produce byte-equal \
9225             SupervisorError to the open-coded struct-literal wrap on the \
9226             same &str fixture",
9227        );
9228    }
9229
9230    #[test]
9231    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
9232        assert_eq!(
9233            SupervisorError::child_supervises_self("orquestra"),
9234            SupervisorError::ChildSupervisesSelf {
9235                caixa: "orquestra".to_string(),
9236            },
9237            "generated child_supervises_self ctor must produce byte-equal \
9238             SupervisorError to the open-coded struct-literal wrap on the \
9239             same &str fixture",
9240        );
9241    }
9242
9243    // Per-variant equivalence pins for the two lifted
9244    // [`SupervisorError::child_caixa_invalid`] /
9245    // [`SupervisorError::child_versao_invalid`] inherent constructors
9246    // (fail-before-pass-after by construction — a byte-mismatched ctor body
9247    // would trip its equivalence pin first). Each pins the ctor output to
9248    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
9249    // in [`SupervisorSpec::validate_children`] on the two variants
9250    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
9251    // struct-literal on the same scalar fixtures. Peers of the sibling
9252    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
9253    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
9254    // the peer `AplicacaoError` envelope's
9255    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
9256
9257    #[test]
9258    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
9259        let caixa = "Worker";
9260        let reason = "sample reason text";
9261        assert_eq!(
9262            SupervisorError::child_caixa_invalid(caixa, reason),
9263            SupervisorError::ChildCaixaInvalid {
9264                caixa: caixa.to_string(),
9265                reason: reason.to_string(),
9266            },
9267            "lifted child_caixa_invalid ctor must produce byte-equal \
9268             SupervisorError to the open-coded struct-literal wrap on the \
9269             same (&str, reason) fixture",
9270        );
9271    }
9272
9273    #[test]
9274    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
9275        let caixa = "worker";
9276        let versao = "not-a-req";
9277        let reason = "sample reason text";
9278        assert_eq!(
9279            SupervisorError::child_versao_invalid(caixa, versao, reason),
9280            SupervisorError::ChildVersaoInvalid {
9281                caixa: caixa.to_string(),
9282                versao: versao.to_string(),
9283                reason: reason.to_string(),
9284            },
9285            "lifted child_versao_invalid ctor must produce byte-equal \
9286             SupervisorError to the open-coded struct-literal wrap on the \
9287             same (&str, &str, reason) fixture",
9288        );
9289    }
9290
9291    #[test]
9292    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
9293        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
9294        // against a `&str`-literal vs. `format!(…)` reason input to pin
9295        // both constructors accept the `impl Into<String>` bound
9296        // uniformly, so neither wire-up site drifts under a per-arm
9297        // wrapper transformation on the caller-side `reason` axis. Peer
9298        // of the sibling
9299        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
9300        // sweep on the peer `AplicacaoError` envelope.
9301        let via_literal = "literal reason text";
9302        let via_format = format!("{} reason text", "literal");
9303        assert_eq!(
9304            SupervisorError::child_caixa_invalid("Worker", via_literal),
9305            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
9306        );
9307        assert_eq!(
9308            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
9309            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
9310        );
9311    }
9312
9313    #[test]
9314    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
9315        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
9316        // &str`) through a non-default fixture name against every
9317        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
9318        // so any wrapper-side lowercase / trim / truncate / re-order on
9319        // the `caixa.to_string()` sole-field construction surfaces
9320        // here rather than at a downstream diagnostic-shape mismatch.
9321        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
9322        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
9323        // through_to_string` / `contrato_target_ctors_route_edge_
9324        // triple_through_verbatim` / `contrato_empty_pair_ctors_
9325        // route_edge_pair_through_verbatim` cross-axis routing pins on
9326        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
9327        // here onto the `SupervisorError` `{ caixa: String }` envelope
9328        // so every substrate-primitive ctor family in caixa-core
9329        // guarantees the sole-field construction routes the caller's
9330        // `&str` through `.to_string()` verbatim.
9331        let name = "cache-v2";
9332        assert_eq!(
9333            SupervisorError::empty_child_version(name),
9334            SupervisorError::EmptyChildVersion {
9335                caixa: name.to_string(),
9336            },
9337        );
9338        assert_eq!(
9339            SupervisorError::duplicate_child_caixa(name),
9340            SupervisorError::DuplicateChildCaixa {
9341                caixa: name.to_string(),
9342            },
9343        );
9344        assert_eq!(
9345            SupervisorError::child_supervises_self(name),
9346            SupervisorError::ChildSupervisesSelf {
9347                caixa: name.to_string(),
9348            },
9349        );
9350    }
9351
9352    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
9353    //
9354    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
9355    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
9356    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
9357    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
9358    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
9359    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
9360    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
9361    // / silent constant-substitution on any one variant surfaces here rather
9362    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
9363    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
9364    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
9365    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
9366    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
9367    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
9368    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
9369    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
9370    #[test]
9371    fn no_children_ctor_matches_struct_literal_wrap() {
9372        let estrategia = RestartStrategy::OneForAll;
9373        assert_eq!(
9374            SupervisorError::no_children(estrategia),
9375            SupervisorError::NoChildren { estrategia },
9376            "generated no_children ctor must produce byte-equal \
9377             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
9378             on the same `Copy`-`RestartStrategy` fixture",
9379        );
9380    }
9381
9382    #[test]
9383    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
9384        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
9385        assert_eq!(
9386            SupervisorError::max_restarts_exceeds_cap(max_restarts),
9387            SupervisorError::MaxRestartsExceedsCap { max_restarts },
9388            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
9389             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
9390             struct-literal wrap on the same `Copy`-`u32` fixture",
9391        );
9392    }
9393
9394    #[test]
9395    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
9396        let window = Duration::from_micros(1_500);
9397        assert_eq!(
9398            SupervisorError::restart_window_not_canonical(window),
9399            SupervisorError::RestartWindowNotCanonical { window },
9400            "generated restart_window_not_canonical ctor must produce \
9401             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
9402             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
9403        );
9404    }
9405
9406    #[test]
9407    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
9408        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
9409        assert_eq!(
9410            SupervisorError::restart_window_exceeds_cap(window),
9411            SupervisorError::RestartWindowExceedsCap { window },
9412            "generated restart_window_exceeds_cap ctor must produce \
9413             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
9414             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
9415        );
9416    }
9417
9418    #[test]
9419    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
9420        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
9421        // constructor input axis through a non-default `Copy` fixture against
9422        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
9423        // side silent `.into()` / silent constant-substitution / silent field
9424        // re-name away from the canonical `estrategia | max_restarts | window`
9425        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
9426        // axis silently rerouted through some other `Copy` coercion, surfaces
9427        // here rather than at a downstream per-`:supervisor` diagnostic-shape
9428        // drift. Peer of the sibling
9429        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
9430        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
9431        // envelope's per-`:politicas` per-axis ctor family, extended here onto
9432        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
9433        // variant family folded onto a substrate primitive.
9434        //
9435        // Fixtures picked out of each variant's accept-set boundary rather
9436        // than the default value so a silent constant-substitution to a per-
9437        // variant sentinel surfaces here on the structural-equality assertion.
9438        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
9439        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
9440        // isn't the `SimpleOneForOne` arm the sibling
9441        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
9442        // `max_restarts` fixture picks an above-cap magnitude the cap arm
9443        // rejects; the two `Duration` fixtures pick the sub-millisecond and
9444        // above-cap ends of the `:restart-window` canonical-form + cap
9445        // bracket respectively.
9446        let estrategia = RestartStrategy::RestForOne;
9447        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
9448        let sub_ms = Duration::from_micros(1_500);
9449        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
9450        assert_eq!(
9451            SupervisorError::no_children(estrategia),
9452            SupervisorError::NoChildren { estrategia },
9453        );
9454        assert_eq!(
9455            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
9456            SupervisorError::MaxRestartsExceedsCap {
9457                max_restarts: above_cap_restarts,
9458            },
9459        );
9460        assert_eq!(
9461            SupervisorError::restart_window_not_canonical(sub_ms),
9462            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
9463        );
9464        assert_eq!(
9465            SupervisorError::restart_window_exceeds_cap(above_hour),
9466            SupervisorError::RestartWindowExceedsCap { window: above_hour },
9467        );
9468    }
9469
9470    #[test]
9471    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
9472        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
9473        // generated ctor `const fn` so a caller can pin a `SupervisorError`
9474        // at compile time — the same zero-runtime-work property the pre-lift
9475        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
9476        // its `Copy`-pass-through construction path (no `.to_string()` /
9477        // `.into()` allocation, no branching). If any future edit silently
9478        // drops the `const` qualifier from the macro body the per-arm `const`
9479        // bindings below fail to compile, which surfaces the regression at
9480        // the substrate-primitive definition rather than at some downstream
9481        // consumer that had come to rely on the `const`-constructibility.
9482        // Peer of the sibling
9483        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
9484        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
9485        // per-`:politicas` per-axis ctor family.
9486        const NO_CHILDREN: SupervisorError =
9487            SupervisorError::no_children(RestartStrategy::OneForAll);
9488        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
9489        const WINDOW_NC: SupervisorError =
9490            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
9491        const WINDOW_CAP: SupervisorError =
9492            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
9493        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
9494        assert!(matches!(
9495            MAX_RESTARTS_CAP,
9496            SupervisorError::MaxRestartsExceedsCap { .. }
9497        ));
9498        assert!(matches!(
9499            WINDOW_NC,
9500            SupervisorError::RestartWindowNotCanonical { .. }
9501        ));
9502        assert!(matches!(
9503            WINDOW_CAP,
9504            SupervisorError::RestartWindowExceedsCap { .. }
9505        ));
9506    }
9507}