Skip to main content

caixa_core/
supervisor.rs

1//! OTP-shaped supervisor trees, encoded as a typed `:kind Supervisor`
2//! caixa with a strategy + restart-policy children list.
3//!
4//! See `theory/INSPIRATIONS.md` §II.2 + §III.2 for the prior-art frame
5//! (Erlang OTP supervisor + Lunatic supervisor strategies as Rust types).
6//!
7//! ```lisp
8//! (defcaixa
9//!   :nome           "my-app-root"
10//!   :versao         "0.1.0"
11//!   :kind           Supervisor
12//!   :estrategia     OneForOne
13//!   :max-restarts   5
14//!   :restart-window "60s"
15//!   :children       ((:caixa "worker"       :versao "^0.1" :restart Permanent)
16//!                    (:caixa "cache-server" :versao "^0.1" :restart Transient)
17//!                    (:caixa "scratch-job"  :versao "^0.1" :restart Temporary)))
18//! ```
19//!
20//! wasm-operator (M3) walks the tree, materializes one ComputeUnit per
21//! child, and applies the strategy on child failure. The Rust types
22//! here are the typed contract; the runtime owns lifecycle.
23
24use std::time::Duration;
25
26use serde::{Deserialize, Serialize};
27use thiserror::Error;
28
29/// One of the four canonical Erlang/OTP restart strategies.
30///
31/// The strategy decides what happens to *sibling* children when one
32/// child dies. Per-child behaviour is governed by [`RestartPolicy`].
33#[derive(
34    Serialize,
35    Deserialize,
36    Debug,
37    Clone,
38    Copy,
39    PartialEq,
40    Eq,
41    Hash,
42    gen_platform::TypedDispatcher,
43    gen_platform::Discriminant,
44    gen_platform::IsVariant,
45    gen_platform::FromStrKind,
46)]
47pub enum RestartStrategy {
48    /// On child failure, restart only that child. Default; matches
49    /// most "tree of independent workers" use cases.
50    OneForOne,
51    /// On child failure, restart every child. Used when children
52    /// share state and must be in sync.
53    OneForAll,
54    /// On child failure, restart the failed child and every child
55    /// started *after* it (preserving startup order). Used when later
56    /// children depend on earlier ones.
57    RestForOne,
58    /// Dynamic children of the same shape, started on demand. The
59    /// supervisor doesn't know its children at boot; they're added as
60    /// they're needed (e.g. one child per session).
61    SimpleOneForOne,
62}
63
64impl Default for RestartStrategy {
65    fn default() -> Self {
66        // Route the [`Default for RestartStrategy`] impl through the
67        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
68        // `pub const` rather than a raw `Self::OneForOne` arm — one
69        // source of truth for the Erlang/OTP `one_for_one` half of Learn
70        // You Some Erlang's `{one_for_one, intensity, 5, 60}` worker-
71        // supervisor canonical default, paired with the sibling
72        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `MaxIntensity` half (b698ec0)
73        // and `SUPERVISOR_RESTART_WINDOW_DEFAULT` `Period` half (f7dcd0e).
74        // Pinned by `restart_strategy_default_routes_through_lifted_default`.
75        SUPERVISOR_ESTRATEGIA_DEFAULT
76    }
77}
78
79impl RestartStrategy {
80    /// Exhaustive iteration surface for every consumer that walks the
81    /// closed four-arm [`RestartStrategy`] discriminator set (the future
82    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
83    /// admission-webhook rejection body naming the accepted-`:estrategia`
84    /// list, a future `feira supervisor --estrategia …` CLI arg-parse's
85    /// "did you mean" hint via a [`Self::from_wire`]-scan over the slice,
86    /// the future `feira app graph` per-supervisor `:estrategia` column,
87    /// any future round-trip fuzz harness that sweeps every arm). A
88    /// future arm addition (an OTP-`rest_for_all` arm the theory
89    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
90    /// might reach for once the four canonical OTP strategies stop
91    /// covering the substrate's discovered load-shape) extends this
92    /// slice as one edit and every consumer picks up the new entry by
93    /// construction; the compiler-checked exhaustiveness on the sibling
94    /// method `match` arms ([`Self::as_str`] / [`Self::from_wire`]) is
95    /// the build-time guarantee that no arm forgets to grow.
96    ///
97    /// Peer of the sibling closed-set typed enums'
98    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
99    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
100    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
101    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
102    /// surfaces — the fifth (and the first M2 OTP-shape) closed-set
103    /// typed enum on the caixa surface to converge onto the same
104    /// one-canonical-arm-list-per-enum discipline.
105    pub const ALL: &'static [Self] = &[
106        Self::OneForOne,
107        Self::OneForAll,
108        Self::RestForOne,
109        Self::SimpleOneForOne,
110    ];
111
112    /// Canonical PascalCase discriminator scalar this variant serializes
113    /// as under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`]. The four arms
114    /// return the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
115    /// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
116    /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
117    /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] lifted
118    /// constants so every substrate consumer that dispatches on the
119    /// per-supervisor sibling-restart strategy (the future
120    /// wasm-operator's per-supervisor sibling-restart branch, the future
121    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
122    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
123    /// reconciliation scheduler's per-strategy fan-out) reads the same
124    /// byte-string the `Serialize` derive emits — the pin test in
125    /// [`tests::restart_strategy_variants_serialize_to_lifted_scalar_values`]
126    /// asserts the two paths agree, peer of the M3
127    /// `PlacementStrategy::as_str` (cc8f749) on the sibling per-Aplicacao
128    /// distribution-strategy axis.
129    #[must_use]
130    pub const fn as_str(self) -> &'static str {
131        match self {
132            Self::OneForOne => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
133            Self::OneForAll => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
134            Self::RestForOne => crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
135            Self::SimpleOneForOne => crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
136        }
137    }
138
139    /// Substrate-canonical reverse projection on the `:supervisor
140    /// :estrategia` closed-set axis — parses the `PascalCase`
141    /// discriminator scalar back to the typed variant, or `None` when
142    /// `s` is outside
143    /// the closed-set arm-string set [`Self::as_str`] emits. Dispatches
144    /// on the same lifted
145    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
146    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
147    /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
148    /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
149    /// constants the [`Self::as_str`] emitter walks, so the parse and
150    /// emit halves of the round-trip migrate through one caixa-core
151    /// edit on any future arm addition.
152    ///
153    /// Prior to this lift the substrate carried only the forward
154    /// `Self → &str` projection on the OTP sibling-restart axis (the
155    /// [`Self::as_str`] emitter, the [`std::fmt::Display`] impl routed
156    /// through it, the `Serialize` derive that emits the same
157    /// byte-string under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`])
158    /// plus the kebab-case dispatcher-catalog identity via
159    /// [`Self::discriminant`] — every non-serde consumer that wanted to
160    /// parse a wire-form `PascalCase` strategy scalar had to re-inline
161    /// a four-arm `match s { "OneForOne" => …, "OneForAll" => …,
162    /// "RestForOne" => …, "SimpleOneForOne" => …, _ => … }` cascade
163    /// that expressed no compile-time link back to the typed variant's
164    /// canonical lifted constant. A future variant rename or per-arm
165    /// serde-attribute drift would silently split the wire byte-string
166    /// one non-serde consumer parsed from the one the emitter wrote,
167    /// with the failure surfacing at parse time far from the rebrand
168    /// commit.
169    ///
170    /// Distinct axis from the [`std::str::FromStr`] impl the
171    /// [`gen_platform::FromStrKind`] derive already installs on this
172    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
173    /// dispatcher-catalog identity (`"one-for-one"` / `"one-for-all"` /
174    /// `"rest-for-one"` / `"simple-one-for-one"` — the inverse of
175    /// [`Self::discriminant`]), while this method inverts the
176    /// `PascalCase` wire byte-string [`Self::as_str`] emits. The
177    /// two-axis split lets the dispatcher-catalog identity live in
178    /// kebab-case
179    /// (where every peer catalog identifier already lives) without
180    /// forcing a wire-format rename on the tatara-lisp author surface
181    /// (`:estrategia OneForOne`, `PascalCase`) — the same two-axis
182    /// distinction the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
183    /// / [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
184    /// carry on their peer closed-set typed-enum wire round-trips.
185    ///
186    /// Same closed-set-reverse-projection discipline the sibling
187    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
188    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
189    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
190    /// carry on the peer wire-side `str → Self` axes — extended onto
191    /// the M2 OTP-shape sibling-restart-strategy closed-set axis, the
192    /// fifth substrate-side closed-set typed enum to converge on the
193    /// two-way `str ↔ Self` round-trip. Method-named `from_wire` (not
194    /// `from_str`) to match the peer [`crate::CaixaKind::from_wire`]
195    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
196    /// derive already installs on the sibling kebab-case axis. Returns
197    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
198    /// shapes: the caller picks the diagnostic form appropriate for
199    /// its use site.
200    #[must_use]
201    pub fn from_wire(s: &str) -> Option<Self> {
202        match s {
203            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE => Some(Self::OneForOne),
204            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL => Some(Self::OneForAll),
205            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE => Some(Self::RestForOne),
206            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE => Some(Self::SimpleOneForOne),
207            _ => None,
208        }
209    }
210}
211
212/// [`std::fmt::Display`] routed through [`RestartStrategy::as_str`], so the
213/// pretty-printed byte-string every consumer that formats the strategy as
214/// user-facing text lands on (the future wasm-operator's per-supervisor
215/// sibling-restart-strategy diagnostic line, the future `feira app graph`
216/// per-supervisor strategy line, the future M4
217/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission-webhook
218/// rejection body) reaches for the same lifted
219/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
220/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
221/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
222/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
223/// wire-format `Serialize` derive already emits under
224/// [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the
225/// [`RestartStrategy::as_str`] helper already returns.
226///
227/// Pre-convergence the two paths structurally disagreed — the
228/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
229/// route (now retired here) sent [`std::fmt::Display`] through the
230/// gen-platform discriminant catalog string, which arrives kebab-case as
231/// `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
232/// `"simple-one-for-one"`, while the wire format ran as `PascalCase`
233/// `"OneForOne"` / `"OneForAll"` / `"RestForOne"` / `"SimpleOneForOne"`
234/// through the un-`rename`d serde derive. Every consumer that formatted
235/// the strategy for a diagnostic line, a graph, or a rejection body under
236/// `format!("{v}")` therefore landed under a different byte-string than
237/// the wire format the operator's per-strategy dispatch keyed off — a
238/// silent split whose apply-time symptom (a `format!("{v}")`-carrying
239/// diagnostic quoting `"one-for-one"` while the wire scalar the operator
240/// probed was `"OneForOne"`) surfaced as a confused correlate at
241/// operator-log time far from the two-declaration site.
242///
243/// Routing `Display` through [`RestartStrategy::as_str`] closes the third
244/// path: every `format!("{v}")` call reaches the same lifted
245/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const the wire format and
246/// the [`RestartStrategy::as_str`] helper route through — `Debug` (the
247/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
248/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
249/// byte-string per variant. A future variant rename or
250/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
251/// exactly one place, structurally.
252///
253/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
254/// (from `#[derive(gen_platform::Discriminant)]`) still returns
255/// `"one-for-one"` / etc., and the fleet-wide
256/// [`gen_platform::register_dispatcher!("caixa.restart-strategy", …)`]
257/// registration keys the catalog off the same kebab identity. The two
258/// naming worlds now live on separate typed methods (`Display` /
259/// `as_str` for the wire byte-string, `discriminant` for the catalog
260/// identity) rather than sharing one `Display` route that structurally
261/// disagrees with the wire format.
262///
263/// Pin tests
264/// [`tests::restart_strategy_display_routes_through_as_str_helper`]
265/// and
266/// [`tests::restart_strategy_display_matches_serialized_wire_byte_string`]
267/// assert the three paths agree byte-for-byte on every variant, so a
268/// future variant rename or per-arm serde attribute drift is a build
269/// error visible at caixa-core test time, not a silent per-consumer
270/// dispatch miss at apply / reconcile time.
271///
272/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
273/// (aplicacao.rs:2306) on the sibling per-Aplicacao distribution-strategy
274/// axis — same three-path-convergence discipline, extended to close the
275/// second of three OTP-shaped closed-enum discriminator axes on the
276/// caixa typed surface.
277impl std::fmt::Display for RestartStrategy {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        f.write_str(self.as_str())
280    }
281}
282
283/// Substrate-canonical [`AsRef<str>`] projection on the M2
284/// per-supervisor sibling-restart [`RestartStrategy`] closed-set typed
285/// enum — routes through the same [`RestartStrategy::as_str`]
286/// `pub const fn` scalar accessor the paired [`std::fmt::Display`]
287/// impl and the un-`rename`d [`serde::Serialize`] derive already key
288/// off, so any future consumer that binds a [`RestartStrategy`]
289/// through the standard-library `impl AsRef<str>` bound (a future
290/// [`caixa-feira`] `feira supervisor --estrategia <arm>` verb that
291/// composes the emitted `PascalCase` wire scalar into a
292/// [`std::process::Command::arg`] shell-out of the future
293/// wasm-operator's admission gate, a per-supervisor structured-log
294/// recorder on the future `caixa-operator`'s hierarchical
295/// reconciliation surface that accepts `impl AsRef<str>` at the
296/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
297/// lookup keyed on the estrategia wire byte through
298/// `map.get::<str>(strategy.as_ref())` on a future per-strategy
299/// dispatch table) reaches the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
300/// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
301/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
302/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
303/// lifted-const through one substrate-primitive dispatch rather
304/// than an open-coded `.as_str()` projection at every wire-up.
305///
306/// Peer of the sibling [`std::fmt::Display`] impl on the same
307/// primitive — both delegate to the shared
308/// [`RestartStrategy::as_str`] `pub const fn` accessor, so
309/// [`format!("{s}")`], `s.as_str()`, and
310/// `<RestartStrategy as AsRef<str>>::as_ref(&s)` resolve to the same
311/// byte-string per instance by construction. A future variant rename
312/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
313/// enum reaches every one of the three paths (plus the wire-format
314/// `Serialize` derive that already routes through the same lifted
315/// const) through exactly one caixa-core edit.
316///
317/// Same "route the trait impl through the substrate-primitive
318/// accessor" discipline the sibling [`crate::CaixaVersion`]
319/// [`AsRef<str>`] impl (16d5c7e) carries on the paired top-level
320/// `:versao` typed newtype — extends it onto the second `AsRef<str>`
321/// axis on the caixa typed surface (the first M2 OTP-shape
322/// closed-set typed enum to converge onto the standard-library
323/// [`AsRef<str>`] projection). Rust-side newtype/typed-enum
324/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
325/// primitive so a caller who has one has both; before this lift,
326/// [`RestartStrategy`] carried [`fmt::Display`] but not the paired
327/// [`AsRef<str>`] impl the convention names.
328///
329/// Pinned load-bearing by
330/// [`tests::restart_strategy_as_ref_str_routes_through_as_str_accessor`]
331/// (byte-parity pin against [`RestartStrategy::as_str`] across the
332/// four-arm closed set) — any future silent detour that routes the
333/// impl through a divergent projection (a per-arm inline
334/// `match self { … }` re-inlining that opens a compile-time link to
335/// the un-lifted arm-literal, a swap onto the kebab-case
336/// [`gen_platform::Discriminant`] catalog identity that would collide
337/// the wire axis with the dispatcher-catalog axis) trips at
338/// caixa-core test time under `assert_eq!` rather than at a
339/// downstream `impl AsRef<str>`-bound consumer's silent split.
340impl AsRef<str> for RestartStrategy {
341    fn as_ref(&self) -> &str {
342        self.as_str()
343    }
344}
345
346/// Trait-idiomatic reverse projection on the M2-OTP-shape sibling-restart
347/// [`RestartStrategy`] closed-set typed enum — routes byte-for-byte through
348/// the paired substrate-primitive [`RestartStrategy::from_wire`]
349/// `Option<Self>` accessor so every future consumer that binds a
350/// `PascalCase` `:supervisor :estrategia` wire byte-string through the
351/// standard-library `.try_into()` / [`TryFrom`] axis (a future
352/// [`caixa-feira`] `feira supervisor --estrategia <OneForOne|OneForAll|
353/// RestForOne|SimpleOneForOne>` CLI arg-parse that composes into
354/// `let estrategia: RestartStrategy = s.try_into()?`, a future
355/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
356/// `spec.estrategia: String` field through
357/// `RestartStrategy::try_from(&s)?`, a generic
358/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
359/// set typed enums) reaches the same four-arm accept-set the sibling
360/// [`RestartStrategy::from_wire`] resolver parses through and the sibling
361/// [`RestartStrategy::as_str`] emits, rather than an open-coded per-arm
362/// `match s { "OneForOne" => …, "OneForAll" => …, "RestForOne" => …,
363/// "SimpleOneForOne" => …, _ => … }` cascade whose arm-set has no
364/// compile-time link back to the substrate primitive.
365///
366/// Complements the pre-existing forward-projection triple
367/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartStrategy::as_str`])
368/// with the paired trait-idiomatic reverse-projection axis: Rust-side
369/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
370/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
371/// caller who can project *out to* a `&str` can also project *in from*
372/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
373/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
374/// lint the sibling method-named [`RestartStrategy::from_wire`] would
375/// trigger under a `FromStr` impl and to avoid colliding with the
376/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
377/// already installs on the paired *kebab-case dispatcher-catalog* axis
378/// (which parses `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
379/// `"simple-one-for-one"`, the inverse of [`Self::discriminant`]) — this
380/// impl closes the trait-idiomatic reverse axis on the *`PascalCase` wire*
381/// half without disturbing either the method-named `from_wire` shape every
382/// sibling closed-set typed enum on the substrate already carries or the
383/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
384/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
385///
386/// `type Error = ()` matches the sibling [`RestartStrategy::from_wire`]'s
387/// `Option<Self>` return-shape's deliberate deferral of error typing: the
388/// caller picks the diagnostic form appropriate for its use site (a future
389/// `feira supervisor --estrategia` arg-parse composes its own per-verb
390/// "unknown strategy: <arg> — accepted: {…}" message enumerating
391/// [`RestartStrategy::ALL`], a future M4 admission-webhook rejection body
392/// wraps the `Err(())` outcome with the accepted-set enumeration for
393/// operator diagnostics, a `Result::map_err` at the call site lifts the
394/// unit-error to a per-verb error type). Same shape the peer
395/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136),
396/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd), and
397/// [`crate::provedor::ferrite::FerriteRuntime::from_wire`] blocks motivate
398/// on their peer closed-set typed enums' reverse projections.
399///
400/// The paired [`TryFrom<&str>`] impl reaches the same four-arm accept-set
401/// the [`RestartStrategy::from_wire`] resolver dispatches through, so any
402/// future arm addition (an OTP-`rest_for_all` fifth arm the theory
403/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
404/// might reach for once the four canonical OTP strategies stop covering
405/// the substrate's discovered load-shape) grows the trait-idiomatic axis
406/// by construction — one caixa-core edit on
407/// [`RestartStrategy::from_wire`] extends both the method-named reverse
408/// projection every existing consumer keys off and the trait-idiomatic
409/// reverse projection this impl exposes, without a coordinated rewrite
410/// across every future `TryFrom<&str>`-bound consumer's arm-set.
411///
412/// Extends the substrate-wide closed-set-enum reverse-projection family
413/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via bf33136,
414/// [`crate::aplicacao::PlacementStrategy`] via 6fd00cd) onto the first
415/// M2-OTP-shape closed-set typed enum on the caixa surface — the
416/// `:supervisor :estrategia` closed set the future wasm-operator's
417/// hierarchical reconciliation scheduler keys off end-to-end.
418///
419/// Pinned load-bearing by
420/// [`tests::restart_strategy_try_from_str_routes_through_from_wire_accessor`]
421/// (byte-parity pin against [`RestartStrategy::from_wire`] across the
422/// four-arm accept-set) and
423/// [`tests::restart_strategy_try_from_str_rejects_unknown_byte_strings`]
424/// (rejection witness against silent accept-set widening).
425impl TryFrom<&str> for RestartStrategy {
426    type Error = ();
427
428    fn try_from(s: &str) -> Result<Self, Self::Error> {
429        Self::from_wire(s).ok_or(())
430    }
431}
432
433/// Trait-idiomatic *forward* projection on the M2-OTP-shape sibling-restart
434/// [`RestartStrategy`] closed-set typed enum onto the `&'static str` axis —
435/// routes byte-for-byte through the paired substrate-primitive
436/// [`RestartStrategy::as_str`] `pub const fn` accessor so every future
437/// consumer that binds a [`RestartStrategy`] through the standard-library
438/// `.into()` / [`From<Self> for &'static str`] (equivalently
439/// [`Into<&'static str>`]) axis (a future
440/// `tracing::field::valuable::Value::Str(strategy.into())` structured-log
441/// recorder where the `Str` arm typing demands `&'static str` and the
442/// sibling [`AsRef<str>`] impl's borrowed `&str` return-type does not
443/// satisfy the bound, a future `Cow::Borrowed::<'static, str>(strategy.into())`
444/// composer on the future M4 admission-webhook rejection body where the
445/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`] borrowed
446/// return, a generic `<T: Into<&'static str>>`-bound serializer on a
447/// per-strategy diagnostic column) reaches the same lifted
448/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
449/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
450/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
451/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
452/// paired [`std::fmt::Display`], [`AsRef<str>`], and
453/// [`RestartStrategy::as_str`] surfaces already return, rather than an
454/// open-coded per-arm `match s { OneForOne => "OneForOne", … }` cascade
455/// whose arm-set has no compile-time link back to the substrate primitive.
456///
457/// Complements the pre-existing quadruple
458/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartStrategy::as_str`],
459/// [`TryFrom<&str>`] via 5b828ed) with the paired trait-idiomatic
460/// forward-projection axis: Rust-side newtype/typed-enum convention pairs
461/// [`TryFrom<&str>`] (trait-idiomatic reverse) with [`From<Self> for
462/// &'static str`] (trait-idiomatic forward) on the same primitive so a
463/// caller who can project *in from* a `&str` via the trait axis can also
464/// project *out to* one — mirroring the `strum::IntoStaticStr` /
465/// `serde::Serialize`-shape idiom where both projection halves share one
466/// trait-driven vocabulary. Before this lift the substrate carried a
467/// `&str`-returning [`AsRef<str>`] but not the paired `&'static str`-
468/// returning [`From<Self> for &'static str`] axis every downstream
469/// generic that specifically needs `'static` byte-string bytes reaches for.
470///
471/// The paired [`RestartStrategy::as_str`] returns `&'static str` by
472/// construction (each `match` arm resolves to a
473/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str` with static
474/// lifetime), so the trait's return-type promise is upheld structurally.
475/// Any future silent detour that routes the impl through a non-static
476/// projection (a per-arm inline `String::from("OneForOne")`-shaped
477/// re-inlining that would `.leak()`-cast for the `'static` bound, a
478/// hypothetical rebrand of one arm's [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
479/// const to a non-`const &str`) is a caixa-core-build-time failure through
480/// the `pub const fn as_str` signature the trait routes through.
481///
482/// The paired impl reaches the same four-arm emit-set the
483/// [`RestartStrategy::as_str`] accessor dispatches through, so any future
484/// arm addition (an OTP-`rest_for_all` fifth arm the theory
485/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
486/// might reach for once the four canonical OTP strategies stop covering
487/// the substrate's discovered load-shape) grows the trait-idiomatic
488/// forward axis by construction — one caixa-core edit on
489/// [`RestartStrategy::as_str`] extends every one of the five sibling
490/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
491/// [`RestartStrategy::as_str`] itself, this [`From<Self> for &'static str`],
492/// and the un-`rename`d [`serde::Serialize`] derive that also emits
493/// [`Self::as_str`]'s bytes) without a coordinated rewrite across every
494/// future `Into<&'static str>`-bound consumer's arm-set.
495///
496/// Opens the substrate-wide trait-idiomatic *forward*-projection family on
497/// closed-set fieldless typed enums — the mirror of the recently-closed
498/// trait-idiomatic *reverse*-projection family ([`crate::CaixaKind`] via
499/// 3c83606, [`crate::CaixaDialeto`] via bf33136,
500/// [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, this enum via
501/// 5b828ed, [`crate::supervisor::RestartPolicy`] via 6fdd0d9,
502/// [`crate::aplicacao::WitShape`] via 5472902,
503/// [`crate::aplicacao::RateLimitUnit`] via bf78400,
504/// [`crate::render::PathShapeViolation`] via e67e48a, and the four
505/// downstream-crate peers — [`caixa_arch::InvariantKind`] via e21a857,
506/// [`caixa_arch::ArchVerdict`] via 0a4cc45, [`caixa_lint::Severity`] via
507/// a7bf74c, [`caixa_lint::FixSafety`] via df86c94,
508/// [`caixa_theme::Semantic`] via bd7da69, and
509/// [`caixa_provedor::ferrite::FerriteRuntime`] via 42ab951). This lift
510/// picks [`RestartStrategy`] as the first-mover on the forward-projection
511/// family because its wire byte-string (`PascalCase`) and diagnostic
512/// byte-string ([`as_str`] return) coincide by construction — the sibling
513/// [`crate::CaixaKind`] two-axis split (lowercase Portuguese diagnostic
514/// vs `PascalCase` wire) would leave a first-mover peer arbitrarily
515/// picking one axis; on [`RestartStrategy`] the choice is unambiguous.
516///
517/// Pinned load-bearing by
518/// [`tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
519/// (byte-parity pin against [`RestartStrategy::as_str`] across the
520/// four-arm emit-set, plus a `const`-context materialization witness for
521/// the `&'static str` lifetime promise) and
522/// [`tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
523/// (partition pin asserting `<&'static str as From<RestartStrategy>>::from`
524/// and [`RestartStrategy::as_str`] agree on every arm, so no future
525/// silent bifurcation of the two forward-projection paths can land
526/// silently).
527impl From<RestartStrategy> for &'static str {
528    fn from(strategy: RestartStrategy) -> &'static str {
529        strategy.as_str()
530    }
531}
532
533/// Trait-idiomatic *forward* projection on [`RestartStrategy`] from a
534/// *borrowed* input onto the `&'static str` axis — the borrowed-input
535/// companion to the paired owned-input [`From<RestartStrategy> for
536/// &'static str`] impl immediately above. Routes byte-for-byte through
537/// the same substrate-primitive [`RestartStrategy::as_str`] `pub const
538/// fn` accessor so every consumer that binds a `&RestartStrategy`
539/// through the standard-library `.into()` / [`From<&Self> for &'static
540/// str`] axis (a `RestartStrategy::ALL.iter().map(<&'static
541/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
542/// whose iterator over `&'static [RestartStrategy]` yields
543/// `&RestartStrategy`, not `RestartStrategy`, so the owned-input
544/// [`From<RestartStrategy>`] axis alone forces every call site through
545/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
546/// rather than the direct trait-idiomatic projection; a future generic
547/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
548/// that walks the `iter().map(Into::into)` shape verbatim across every
549/// substrate-wide closed-set typed enum; the future wasm-operator's
550/// per-supervisor sibling-restart-strategy diagnostic line that
551/// composes the accepted-set enumeration from an iterated
552/// `RestartStrategy::ALL.iter().map(|s| s.into())` pipe rather than a
553/// per-arm `match s { … }` cascade; a future
554/// `HashMap::<&'static str, RestartStrategy>::from_iter(
555///     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
556/// per-strategy reverse-lookup table the sibling [`TryFrom<&str>`]
557/// impl cannot compose without this borrowed-input axis in place)
558/// reaches the same four-arm lifted
559/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
560/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
561/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
562/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
563/// the paired owned-input [`From<RestartStrategy> for &'static str`],
564/// the sibling [`std::fmt::Display`], [`AsRef<str>`], and
565/// [`RestartStrategy::as_str`] surfaces already return.
566///
567/// Fourth peer on the substrate-wide trait-idiomatic *borrowed-input*
568/// forward-projection family opened on [`crate::dep::DepList`]
569/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a) and
570/// [`crate::CaixaDialeto`] (807b0b5). Rust's `From` trait does not
571/// auto-derive the `From<&Self>` sibling from a `From<Self>` impl (the
572/// blanket `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does
573/// not exist in `core`), so every closed-set typed enum that carries
574/// the owned-input axis but not the borrowed-input axis forces every
575/// borrowed-input call site through a `.copied()` /
576/// `<&'static str>::from(*strategy)` / `strategy.as_str()` detour whose
577/// type bounds have no compile-time link to the substrate primitive.
578/// [`RestartStrategy`] is the first M2 OTP-shape peer to converge onto
579/// this campaign (mirroring the first-mover role it played on the
580/// owned-input axis in 523157d); the remaining eleven substrate-wide
581/// closed-set fieldless typed enum peers (`RestartPolicy`, `WitShape`,
582/// `RateLimitUnit`, `PlacementStrategy`, `PathShapeViolation`,
583/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
584/// `FerriteRuntime`) are the future targets of this campaign.
585///
586/// Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
587/// [`From<Self> for &'static str`] emits the lowercase Portuguese
588/// [`Self::as_str`] diagnostic vocabulary while the reverse
589/// [`TryFrom<&str>`] parses the `PascalCase` [`Self::wire_name`]
590/// author-surface vocabulary, forcing the round-trip through an
591/// intermediate wire-vocab hop), [`RestartStrategy`]'s
592/// [`Self::as_str`] emit and [`Self::from_wire`] parse share the same
593/// `PascalCase` vocabulary by construction, so the borrowed-input
594/// forward axis and the reverse axis compose directly — the round-trip
595/// witness pin below locks this direct composition without the
596/// intermediate hop the peer axis requires.
597///
598/// Pinned load-bearing by
599/// [`tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
600/// (byte-parity pin against [`RestartStrategy::as_str`] across the
601/// four-arm emit-set via a borrowed input, plus a `const`-context
602/// materialization witness for the `&'static str` lifetime promise,
603/// plus a blanket `.into()` shape) and
604/// [`tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
605/// (cross-axis partition pin against the paired owned-input
606/// [`From<RestartStrategy> for &'static str`] impl, plus a
607/// `.iter().map(Into::into)` pipe witness over
608/// [`RestartStrategy::ALL`], plus a direct round-trip witness through
609/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
610/// Self` round-trip without the wire-vocab intermediate the peer
611/// [`crate::CaixaKind`] axis pair requires).
612impl From<&RestartStrategy> for &'static str {
613    fn from(strategy: &RestartStrategy) -> &'static str {
614        strategy.as_str()
615    }
616}
617
618/// Trait-idiomatic *owned-`String`* forward projection on the M2
619/// OTP-shape sibling-restart-strategy closed-set typed enum — the
620/// owned-heap-string companion to the paired `&'static str`-returning
621/// [`From<RestartStrategy> for &'static str`] / [`From<&RestartStrategy>
622/// for &'static str`] impls immediately above. Routes byte-for-byte
623/// through the substrate-primitive [`RestartStrategy::as_str`]
624/// `pub const fn` accessor (via [`str::to_owned`]) so every consumer
625/// that binds a [`RestartStrategy`] through the standard-library
626/// `.into()` / [`From<Self> for String`] (equivalently
627/// [`Into<String>`]) axis — a future
628/// `serde_json::Value::String(strategy.into())` structured-payload
629/// composer where the `Value::String` arm typing demands an owned
630/// [`String`] and the sibling [`&'static str`]-returning axis forces an
631/// explicit `.to_owned()` / `String::from` restatement at every call
632/// site, a future
633/// `HashMap::<String, RestartStrategy>::from_iter(RestartStrategy::ALL
634/// .iter().map(|s| (s.into(), *s)))` per-strategy lookup where the
635/// map's key type is owned [`String`] rather than [`&'static str`], a
636/// future `Cow::<'static, str>::Owned(strategy.into())` composer on
637/// the future M4 admission-webhook rejection body's owned-arm, the
638/// future wasm-operator's per-supervisor `serde_json::json!({
639/// "estrategia": strategy })` diagnostic emit where the JSON
640/// serializer's `Serialize` impl on [`String`] owns the emit-path — reaches
641/// the same four-arm lifted
642/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
643/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
644/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
645/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
646/// paired [`std::fmt::Display`], [`AsRef<str>`],
647/// [`RestartStrategy::as_str`], and the two `&'static str`-returning
648/// forward-projection impls already return.
649///
650/// Opens the trait-idiomatic *owned-`String`* forward-projection axis
651/// on the closed-set fieldless typed enum surface — first-mover on the
652/// M2 OTP-shape sibling-restart-strategy axis, mirror of the
653/// [`crate::supervisor::RestartStrategy`] first-mover position that
654/// opened the paired owned-`&'static str` axis (523157d) and the
655/// borrowed-input `&'static str` axis on
656/// [`crate::dep::DepList`] (64aa742). Rust's standard library does not
657/// carry a blanket `impl<T: AsRef<str>> From<T> for String` (nor an
658/// `impl<T: fmt::Display> From<T> for String`), so every closed-set
659/// typed enum that carries the paired `AsRef<str>` / `Display` /
660/// `From<Self> for &'static str` triple but not the owned-[`String`]
661/// axis forces every owned-string call site through a `.to_string()` /
662/// `.as_str().to_owned()` / `String::from(strategy.as_str())` detour
663/// whose type bounds have no compile-time link to the substrate
664/// primitive.
665///
666/// Deliberately routes through the human-readable
667/// [`RestartStrategy::as_str`] axis — for this enum the wire format
668/// (`PascalCase`, tatara-lisp author surface `:estrategia OneForOne`)
669/// and the diagnostic byte-string share the same vocabulary by
670/// construction (unlike the sibling [`crate::CaixaKind`] enum whose two
671/// axes diverge), so the owned-[`String`] projection lands
672/// byte-identically on both the wire vocabulary the paired
673/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
674/// [`RestartStrategy::as_str`] helper returns.
675///
676/// The remaining fourteen closed-set typed enums on the caixa
677/// substrate surface (`RestartPolicy`, `CaixaKind`, `CaixaDialeto`,
678/// `DepList`, `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
679/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
680/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets of
681/// this campaign — each carries the same paired `AsRef<str>` /
682/// `Display` / `From<Self> for &'static str` / `From<&Self> for
683/// &'static str` quadruple that this owned-[`String`] axis extends onto.
684///
685/// Pinned load-bearing by
686/// [`tests::restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
687/// (byte-parity pin against [`RestartStrategy::as_str`] across the
688/// four-arm emit-set, plus a blanket `.into::<String>()` shape witness)
689/// and
690/// [`tests::restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm`]
691/// (cross-axis partition pin against the paired owned-input
692/// [`From<RestartStrategy> for &'static str`] impl and the sibling
693/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
694/// plus a direct round-trip witness through [`TryFrom<&str>`] on the
695/// owned-[`String`]'s [`String::as_str`] borrow that closes the two-way
696/// `Self → String → Self` round-trip on the trait-idiomatic
697/// owned-[`String`] forward + reverse axis pair).
698impl From<RestartStrategy> for String {
699    fn from(strategy: RestartStrategy) -> String {
700        strategy.as_str().to_owned()
701    }
702}
703
704/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
705/// projection on the M2 OTP-shape sibling-restart-strategy closed-set
706/// typed enum — the fourth (and closing) corner of the
707/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
708/// projection family. Routes byte-for-byte through the
709/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
710/// accessor (via [`str::to_owned`]) so every consumer that holds a
711/// borrowed [`&RestartStrategy`] and needs an owned [`String`] — a
712/// future `serde_json::Value::String(String::from(&strategy))`
713/// structured-payload composer over a borrowed field, a future
714/// `Iterator::map` over `&[RestartStrategy]` that projects to owned
715/// keys through `.iter().map(String::from)`, a future
716/// `HashMap::<String, RestartStrategy>::from_iter` that keys off a
717/// borrowed-iteration axis where dereferencing the strategy would force
718/// an unnecessary `Copy` at every step, the future wasm-operator's
719/// per-supervisor `strategies.iter().map(String::from).collect()`
720/// diagnostic emit whose iteration axis is borrowed by construction —
721/// reaches the same four-arm lifted
722/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
723/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
724/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
725/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
726/// paired [`std::fmt::Display`], [`AsRef<str>`],
727/// [`RestartStrategy::as_str`], and the three other trait-idiomatic
728/// forward-projection impls
729/// ([`From<RestartStrategy> for &'static str`],
730/// [`From<&RestartStrategy> for &'static str`],
731/// [`From<RestartStrategy> for String`]) already return.
732///
733/// Opens the trait-idiomatic *borrowed-input, owned-`String` output*
734/// forward-projection axis on closed-set fieldless typed enums —
735/// first-mover on the 2×2 completion corner, mirror of the
736/// [`crate::supervisor::RestartStrategy`] first-mover position that
737/// opened the paired owned-input owned-`String` axis (7baa18a), the
738/// owned-input owned-`&'static str` axis (523157d), and the paired
739/// [`crate::dep::DepList`] first-mover position that opened the
740/// borrowed-input `&'static str` axis (64aa742). Rust's standard
741/// library does not carry a blanket `impl<T: AsRef<str>> From<&T> for
742/// String` (nor an `impl<T: fmt::Display> From<&T> for String`), so
743/// every closed-set typed enum that carries the paired `AsRef<str>` /
744/// `Display` / `From<Self> for &'static str` / `From<&Self> for
745/// &'static str` / `From<Self> for String` quintuple but not the
746/// borrowed-input owned-[`String`] axis forces every borrowed-input
747/// owned-string call site through a `strategy.as_str().to_owned()` /
748/// `String::from(*strategy)` (with a spurious `Copy`) /
749/// `strategy.to_string()` (through `Display`) detour whose type bounds
750/// have no compile-time link to the substrate primitive.
751///
752/// Deliberately routes through the human-readable
753/// [`RestartStrategy::as_str`] axis — for this enum the wire format
754/// (`PascalCase`, tatara-lisp author surface `:estrategia OneForOne`)
755/// and the diagnostic byte-string share the same vocabulary by
756/// construction (unlike the sibling [`crate::CaixaKind`] enum whose two
757/// axes diverge), so the borrowed-input owned-[`String`] projection
758/// lands byte-identically on both the wire vocabulary the paired
759/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
760/// [`RestartStrategy::as_str`] helper returns.
761///
762/// The remaining fourteen closed-set typed enums on the caixa
763/// substrate surface (`RestartPolicy`, `CaixaKind`, `CaixaDialeto`,
764/// `DepList`, `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
765/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
766/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets of
767/// this 2×2-completion campaign — each carries the same paired
768/// quintuple that this borrowed-input owned-[`String`] axis extends onto.
769///
770/// Pinned load-bearing by
771/// [`tests::restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
772/// (byte-parity pin against [`RestartStrategy::as_str`] across the
773/// four-arm emit-set through the borrowed-input surface) and
774/// [`tests::restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
775/// (cross-axis partition pin against the paired owned-input owned-
776/// [`String`] [`From<RestartStrategy> for String`] impl, the paired
777/// borrowed-input owned-[`&'static str`] [`From<&RestartStrategy> for
778/// &'static str`] impl, and the sibling [`ToString::to_string`] surface
779/// routed through [`std::fmt::Display`], plus a direct round-trip
780/// witness through [`TryFrom<&str>`] on the owned-[`String`]'s
781/// [`String::as_str`] borrow that closes the two-way
782/// `&Self → String → Self` round-trip on the trait-idiomatic
783/// borrowed-input owned-[`String`] forward + reverse axis pair).
784impl From<&RestartStrategy> for String {
785    fn from(strategy: &RestartStrategy) -> String {
786        strategy.as_str().to_owned()
787    }
788}
789
790/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
791/// output* forward projection on the M2 OTP-shape sibling-restart
792/// [`RestartStrategy`] closed-set typed enum — extends the substrate-
793/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
794/// opened on [`crate::CaixaKind`] (99c1735) onto the first M2 OTP-
795/// shape closed-set fieldless typed enum peer on the caixa surface
796/// (`:supervisor :estrategia`). Routes byte-for-byte through the
797/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
798/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
799/// that binds a [`RestartStrategy`] through the trait-idiomatic
800/// [`std::borrow::Cow<'static, str>`] axis — a future
801/// `axum::response::IntoResponse` composer whose per-strategy
802/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
803/// borrowed return, a future M4 admission-webhook rejection body
804/// that composes the accepted-strategy enumeration through the same
805/// `RestartStrategy::ALL.iter().map(Cow::from)` shape [`CaixaKind`]
806/// already routes through, a generic `<T: for<'a>
807/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
808/// emitter on a per-supervisor diagnostic column — reaches the same
809/// four-arm lifted [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
810/// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
811/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
812/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
813/// the paired [`std::fmt::Display`], [`AsRef<str>`],
814/// [`RestartStrategy::as_str`], and the four
815/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
816/// forward-projection corners already return.
817///
818/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
819/// [`std::borrow::Cow::Owned`] — the substrate-primitive
820/// [`RestartStrategy::as_str`] accessor's return carries the
821/// `&'static str` lifetime by construction (each `match` arm resolves
822/// to a [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str`
823/// with static lifetime), so the zero-alloc borrowed arm is the
824/// type-correct projection with no runtime allocation.
825///
826/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
827/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
828/// From<T> for Cow<'static, str>`), so the paired sibling
829/// [`From<RestartStrategy> for &'static str`],
830/// [`From<RestartStrategy> for String`], [`AsRef<str>`], and
831/// [`std::fmt::Display`] surfaces do not implicitly extend to a
832/// [`Cow<'static, str>`]-bound call site — every such site is forced
833/// through a `Cow::Borrowed(strategy.as_str())` /
834/// `Cow::Owned(strategy.to_string())` open-code whose type bounds
835/// have no compile-time link back to the substrate primitive until
836/// this lift.
837///
838/// First peer to extend the substrate-wide trait-idiomatic
839/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
840/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input,
841/// d45c409 borrowed-input) onto the wider substrate — the remaining
842/// twelve peers (`RestartPolicy`, `PlacementStrategy`, `RateLimitUnit`,
843/// `DepList`, `CaixaDialeto`, and the outside-`caixa-core` peers
844/// `WitShape`, `PathShapeViolation`, `InvariantKind`, `ArchVerdict`,
845/// `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`) are the
846/// future targets of this campaign.
847///
848/// Pinned load-bearing by
849/// [`tests::restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor`]
850/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
851/// against [`RestartStrategy::as_str`] across the four-arm
852/// [`RestartStrategy::ALL`]) and
853/// [`tests::restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
854/// (cross-axis partition pin against the paired [`From<RestartStrategy>
855/// for &'static str`], [`From<RestartStrategy> for String`], and
856/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
857/// `.iter().copied().map(Cow::from)` pipe witness over
858/// [`RestartStrategy::ALL`] that materializes the four-arm accept-set
859/// through the [`Cow<'static, str>`] axis alone and pins the
860/// zero-alloc discipline on every element).
861impl From<RestartStrategy> for std::borrow::Cow<'static, str> {
862    fn from(strategy: RestartStrategy) -> std::borrow::Cow<'static, str> {
863        std::borrow::Cow::Borrowed(strategy.as_str())
864    }
865}
866
867/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
868/// output* forward projection on the M2 OTP-shape sibling-restart
869/// [`RestartStrategy`] closed-set typed enum — the borrowed-input
870/// companion to the paired owned-input
871/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
872/// immediately above (7dd28b3). Routes byte-for-byte through the same
873/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
874/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
875/// that holds a `&RestartStrategy` and needs a
876/// [`std::borrow::Cow<'static, str>`] — a
877/// `RestartStrategy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
878/// per-arm accept-set materializer (whose iterator over
879/// `&'static [RestartStrategy]` yields `&RestartStrategy`, not
880/// `RestartStrategy`, so the paired owned-input
881/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] axis
882/// alone forces every call site through an explicit `.copied()` /
883/// dereference / [`Copy`]-bound restatement rather than the direct
884/// trait-idiomatic projection), a future generic
885/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
886/// on a per-strategy diagnostic column that walks the
887/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
888/// webhook rejection body that composes the accepted-strategy
889/// enumeration from an iterated
890/// `RestartStrategy::ALL.iter().map(|s| s.into())` pipe rather than a
891/// per-arm `match s { … }` cascade — reaches the same four-arm lifted
892/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
893/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
894/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
895/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
896/// the paired [`std::fmt::Display`], [`AsRef<str>`],
897/// [`RestartStrategy::as_str`], the four
898/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
899/// forward-projection corners, and the paired owned-input
900/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
901/// already return.
902///
903/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
904/// [`std::borrow::Cow::Owned`] — the substrate-primitive
905/// [`RestartStrategy::as_str`] accessor's return carries the
906/// `&'static str` lifetime by construction (each `match` arm resolves
907/// to a [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str`
908/// with static lifetime), so the zero-alloc borrowed arm is the
909/// type-correct projection with no runtime allocation.
910///
911/// Second peer on the substrate-wide trait-idiomatic
912/// [`std::borrow::Cow<'static, str>`] forward-projection family
913/// opened one commit prior (7dd28b3) on the paired owned-input
914/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
915/// — closes the `{Self, &Self}` input-shape corner of the
916/// [`Cow<'static, str>`] axis on the first M2 OTP-shape closed-set
917/// fieldless typed enum peer on the caixa surface, exactly as
918/// d45c409 closed it on the top-level [`crate::CaixaKind`] one commit
919/// after the owning half (99c1735) landed. Rust's standard library
920/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for
921/// Cow<'static, str>` (nor an `impl<T: fmt::Display> From<&T> for
922/// Cow<'static, str>`), so every closed-set fieldless typed enum peer
923/// on the substrate that carries the paired owned-input
924/// [`Cow<'static, str>`] axis but not the borrowed-input axis forces
925/// every borrowed-input [`Cow<'static, str>`]-parameterized call site
926/// through a spurious [`Copy`] deref
927/// (`std::borrow::Cow::from(*strategy)`) or a
928/// `std::borrow::Cow::Borrowed(strategy.as_str())` open-code whose
929/// type bounds have no compile-time link to the substrate primitive.
930///
931/// Pinned load-bearing by
932/// [`tests::restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
933/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
934/// against [`RestartStrategy::as_str`] across the four-arm
935/// [`RestartStrategy::ALL`] through the borrowed-input surface) and
936/// [`tests::restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
937/// (cross-axis partition pin against the paired owned-input
938/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`], the
939/// paired borrowed-input owned-`&'static str`
940/// [`From<&RestartStrategy> for &'static str`], and the paired
941/// borrowed-input owned-`String` [`From<&RestartStrategy> for String`]
942/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
943/// over [`RestartStrategy::ALL`] — whose iterator yields
944/// `&RestartStrategy` by construction, so the borrowed-input
945/// [`Cow<'static, str>`] axis is what routes the pipe through the
946/// substrate-primitive [`RestartStrategy::as_str`] accessor with the
947/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
948/// spurious [`Copy`] deref).
949impl From<&RestartStrategy> for std::borrow::Cow<'static, str> {
950    fn from(strategy: &RestartStrategy) -> std::borrow::Cow<'static, str> {
951        std::borrow::Cow::Borrowed(strategy.as_str())
952    }
953}
954
955/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
956/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
957/// closed-set fieldless typed enum — opens a fresh
958/// substrate-wide `Box<str>` forward-projection campaign tier on the
959/// first M2 OTP-shape closed-set fieldless typed enum peer on the
960/// caixa surface, immediately after the paired `Cow<'static, str>`
961/// axis (7dd28b3 / ee577fd) closed the
962/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
963/// corner on this enum. Routes byte-for-byte through the
964/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
965/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
966/// so every consumer that binds a
967/// `let key: Box<str> = strategy.into();`-shaped call site — a
968/// per-supervisor metric-key materializer that stashes the strategy
969/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
970/// clone (a shared-nothing per-strategy accept-set the
971/// `caixa-operator` reconciliation scheduler carries), a future
972/// admission-webhook rejection body whose per-arm `Box<str>` field
973/// composes from an owned `RestartStrategy` handle — reaches the
974/// same four-arm lifted
975/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
976/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
977/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
978/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
979/// the sibling
980/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
981/// forward-projection corner already returns. Rust's standard
982/// library carries `impl From<&str> for Box<str>` and
983/// `impl From<String> for Box<str>` but no blanket
984/// `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is a
985/// distinct trait-idiomatic surface that a downstream
986/// `RestartStrategy → Box<str>` `.into()` reaches through this impl
987/// and no other — without a
988/// `Box::from(strategy.as_str())` open-code whose type bounds have
989/// no compile-time link back to the substrate primitive.
990///
991/// Pinned load-bearing by
992/// [`tests::restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
993/// (byte-parity pin against [`RestartStrategy::as_str`] across the
994/// four-arm [`RestartStrategy::ALL`] emit-set on the owned-input
995/// surface, plus a blanket-derived [`Into`] shape witness).
996impl From<RestartStrategy> for Box<str> {
997    fn from(strategy: RestartStrategy) -> Box<str> {
998        Box::<str>::from(strategy.as_str())
999    }
1000}
1001
1002/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
1003/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
1004/// closed-set fieldless typed enum — closes the `{Self, &Self}`
1005/// input-shape corner of the substrate-wide `Box<str>`
1006/// forward-projection axis opened one commit prior (69ef45c) on the
1007/// paired owned-input [`From<RestartStrategy> for Box<str>`] impl.
1008/// Routes byte-for-byte through the same substrate-primitive
1009/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1010/// [`Box::<str>::from`] on the returned `&'static str`, so every
1011/// consumer that holds a `&RestartStrategy` and needs a
1012/// [`Box<str>`] — a
1013/// `RestartStrategy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
1014/// per-arm accept-set materializer (whose iterator over
1015/// `&'static [RestartStrategy]` yields `&RestartStrategy`, not
1016/// `RestartStrategy`, so the paired owned-input
1017/// [`From<RestartStrategy> for Box<str>`] axis alone forces every
1018/// call site through an explicit `.copied()` / dereference /
1019/// [`Copy`]-bound restatement rather than the direct trait-idiomatic
1020/// projection), a per-supervisor metric-key materializer holding
1021/// `&RestartStrategy` through a `caixa-operator` reconciliation
1022/// scheduler's borrow lifetime, a future admission-webhook rejection
1023/// body whose per-arm `Box<str>` field composes from a borrowed
1024/// `&RestartStrategy` handle without a spurious [`Copy`] deref —
1025/// reaches the same four-arm lifted
1026/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1027/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1028/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1029/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1030/// the paired owned-input [`From<RestartStrategy> for Box<str>`] and
1031/// the sibling
1032/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
1033/// forward-projection corner already return.
1034///
1035/// Second peer on the substrate-wide trait-idiomatic
1036/// [`Box<str>`] forward-projection family opened one commit prior
1037/// (69ef45c) on the paired owned-input
1038/// [`From<RestartStrategy> for Box<str>`] impl — closes the
1039/// `{Self, &Self}` input-shape corner of the [`Box<str>`] axis on
1040/// the first M2 OTP-shape closed-set fieldless typed enum peer on
1041/// the caixa surface (`:supervisor :estrategia`), exactly as
1042/// ee577fd closed the paired [`Cow<'static, str>`] axis one commit
1043/// after its owning half (7dd28b3) landed. Rust's standard library
1044/// carries `impl From<&str> for Box<str>` and
1045/// `impl From<String> for Box<str>` but no blanket
1046/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
1047/// `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
1048/// every closed-set fieldless typed enum peer on the substrate that
1049/// carries the paired owned-input `Box<str>` axis but not the
1050/// borrowed-input axis forces every borrowed-input
1051/// `Box<str>`-parameterized call site through a spurious [`Copy`]
1052/// deref (`Box::<str>::from((*strategy).as_str())`) or a
1053/// `Box::<str>::from(strategy.as_str())` open-code whose type bounds
1054/// have no compile-time link back to the substrate primitive.
1055///
1056/// Pinned load-bearing by
1057/// [`tests::restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
1058/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1059/// four-arm [`RestartStrategy::ALL`] emit-set on the borrowed-input
1060/// surface, plus a blanket-derived [`Into`] shape witness and a
1061/// cross-axis pin against the paired owned-input
1062/// [`From<RestartStrategy> for Box<str>`] and the sibling
1063/// borrowed-input `{&'static str, String, Cow<'static, str>}`
1064/// return-shape axes).
1065impl From<&RestartStrategy> for Box<str> {
1066    fn from(strategy: &RestartStrategy) -> Box<str> {
1067        Box::<str>::from(strategy.as_str())
1068    }
1069}
1070
1071/// Per-child restart policy.
1072///
1073/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
1074#[derive(
1075    Serialize,
1076    Deserialize,
1077    Debug,
1078    Clone,
1079    Copy,
1080    PartialEq,
1081    Eq,
1082    Hash,
1083    gen_platform::TypedDispatcher,
1084    gen_platform::Discriminant,
1085    gen_platform::IsVariant,
1086    gen_platform::FromStrKind,
1087)]
1088pub enum RestartPolicy {
1089    /// Always restart the child, regardless of how it died. Used for
1090    /// long-running services that must always be up.
1091    Permanent,
1092    /// Never restart. Used for one-shot work whose completion is
1093    /// itself the success signal (`oneShot` triggers map here).
1094    Temporary,
1095    /// Restart only when the child died *abnormally* (non-zero exit
1096    /// or unhandled exception). A clean exit completes the child.
1097    Transient,
1098}
1099
1100impl Default for RestartPolicy {
1101    fn default() -> Self {
1102        // Route the [`Default for RestartPolicy`] impl's return arm through
1103        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
1104        // `pub const` rather than a raw `Self::Permanent` arm — one source
1105        // of truth for the Erlang/OTP-canonical `permanent` worker-child
1106        // default across the two production consumers that currently
1107        // dispatch on it (this impl at the [`RestartPolicy::default`] call
1108        // and the serde-side `#[serde(default)]` on
1109        // [`ChildSpec::restart`] that resolves an author-omitted
1110        // `:children :restart` slot through `RestartPolicy::default()`).
1111        // Peer of the sibling per-`:supervisor` axis
1112        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1113        // route (95ffacc) — the two impls now share one substrate-primitive
1114        // lift discipline, so any future coherent rebrand of the OTP-shape
1115        // supervisor+child default set migrates through typed constants in
1116        // lockstep instead of splitting a lifted supervisor half against
1117        // an open-coded child half. Pinned by
1118        // `restart_policy_default_routes_through_lifted_default` +
1119        // `child_spec_serde_default_restart_routes_through_lifted_default`
1120        // in the tests module.
1121        SUPERVISOR_CHILD_RESTART_DEFAULT
1122    }
1123}
1124
1125impl RestartPolicy {
1126    /// Exhaustive iteration surface for every consumer that walks the
1127    /// closed three-arm [`RestartPolicy`] discriminator set (the future
1128    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1129    /// per-child admission-webhook rejection body naming the accepted-
1130    /// `:restart` list, a future `feira supervisor --restart …` CLI
1131    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
1132    /// over the slice, the future `feira app graph` per-child restart
1133    /// column, any future round-trip fuzz harness that sweeps every
1134    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
1135    /// theory
1136    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1137    /// might reach for once the three canonical OTP restart policies
1138    /// stop covering the substrate's discovered load-shape) extends
1139    /// this slice as one edit and every consumer picks up the new entry
1140    /// by construction; the compiler-checked exhaustiveness on the
1141    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
1142    /// is the build-time guarantee that no arm forgets to grow.
1143    ///
1144    /// Peer of the sibling closed-set typed enums'
1145    /// [`RestartStrategy::ALL`] (4eec29c) /
1146    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
1147    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
1148    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
1149    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
1150    /// surfaces — the sixth (and the third and final M2 OTP-shape)
1151    /// closed-set typed enum on the caixa surface to converge onto the
1152    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
1153    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
1154    /// sibling-restart-strategy axis; this closes the per-child
1155    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
1156    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
1157
1158    /// Canonical PascalCase discriminator scalar this variant serializes
1159    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
1160    /// arms return the paired
1161    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1162    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1163    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1164    /// constants so every substrate consumer that dispatches on the
1165    /// per-child restart-decision policy (the future wasm-operator's
1166    /// per-child post-exit restart-decision branch, the future M4
1167    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1168    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
1169    /// reconciliation scheduler's per-child-policy fan-out) reads the
1170    /// same byte-string the `Serialize` derive emits — the pin test in
1171    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1172    /// asserts the two paths agree, peer of the M2
1173    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
1174    /// sibling-restart-strategy axis and the M3
1175    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
1176    /// per-Aplicacao distribution-strategy axis — the third of three
1177    /// OTP-shaped closed-enum discriminator axes on the caixa typed
1178    /// surface to converge onto the same three-path-convergence
1179    /// (`Serialize` derive → `as_str` helper → lifted constant)
1180    /// drift-detection posture.
1181    #[must_use]
1182    pub const fn as_str(self) -> &'static str {
1183        match self {
1184            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1185            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1186            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1187        }
1188    }
1189
1190    /// Substrate-canonical reverse projection on the `:children :restart`
1191    /// closed-set axis — parses the `PascalCase` discriminator scalar
1192    /// back to the typed variant, or `None` when `s` is outside the
1193    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
1194    /// the same lifted
1195    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1196    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1197    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
1198    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
1199    /// of the round-trip migrate through one caixa-core edit on any
1200    /// future arm addition.
1201    ///
1202    /// Prior to this lift the substrate carried only the forward
1203    /// `Self → &str` projection on the OTP per-child restart-policy
1204    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
1205    /// impl routed through it, the `Serialize` derive that emits the
1206    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
1207    /// plus the kebab-case dispatcher-catalog identity via
1208    /// [`Self::discriminant`] — every non-serde consumer that wanted to
1209    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
1210    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
1211    /// "Transient" => …, _ => … }` cascade that expressed no
1212    /// compile-time link back to the typed variant's canonical lifted
1213    /// constant. A future variant rename or per-arm serde-attribute
1214    /// drift would silently split the wire byte-string one non-serde
1215    /// consumer parsed from the one the emitter wrote, with the failure
1216    /// surfacing at the operator's reconcile posture (a `:temporary`
1217    /// `oneShot` child being restarted on clean exit, treating the
1218    /// successful-completion signal as failure and re-running the
1219    /// completion-terminal one-shot indefinitely; a `:transient` child
1220    /// that clean-exited being restarted, masking the clean-completion
1221    /// contract) far from the rebrand commit and with no field naming
1222    /// the drift.
1223    ///
1224    /// Distinct axis from the [`std::str::FromStr`] impl the
1225    /// [`gen_platform::FromStrKind`] derive already installs on this
1226    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
1227    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
1228    /// `"transient"` — the inverse of [`Self::discriminant`]), while
1229    /// this method inverts the `PascalCase` wire byte-string
1230    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
1231    /// catalog identity live in kebab-case (where every peer catalog
1232    /// identifier already lives) without forcing a wire-format rename
1233    /// on the tatara-lisp author surface (`:restart Permanent`,
1234    /// `PascalCase`) — the same two-axis distinction the sibling
1235    /// [`RestartStrategy::from_wire`] (4eec29c) /
1236    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1237    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
1238    /// carry on their peer closed-set typed-enum wire round-trips.
1239    ///
1240    /// Same closed-set-reverse-projection discipline the sibling
1241    /// [`RestartStrategy::from_wire`] (4eec29c) /
1242    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1243    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
1244    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
1245    /// carry on the peer wire-side `str → Self` axes — extended onto
1246    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
1247    /// sixth substrate-side closed-set typed enum (and the third and
1248    /// final OTP-shape closed-enum discriminator axis) to converge on
1249    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
1250    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
1251    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
1252    /// derive already installs on the sibling kebab-case axis. Returns
1253    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
1254    /// shapes: the caller picks the diagnostic form appropriate for
1255    /// its use site.
1256    #[must_use]
1257    pub fn from_wire(s: &str) -> Option<Self> {
1258        match s {
1259            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
1260            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
1261            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
1262            _ => None,
1263        }
1264    }
1265}
1266
1267/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
1268/// pretty-printed byte-string every consumer that formats the policy as
1269/// user-facing text lands on (the future wasm-operator's per-child
1270/// post-exit restart-decision diagnostic line, the future `feira app
1271/// graph` per-child restart column, the future M4
1272/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1273/// admission-webhook rejection body) reaches for the same lifted
1274/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1275/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1276/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1277/// wire-format `Serialize` derive already emits under
1278/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
1279/// [`RestartPolicy::as_str`] helper already returns.
1280///
1281/// Pre-convergence the two paths structurally disagreed — the
1282/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1283/// route (now retired here) sent [`std::fmt::Display`] through the
1284/// gen-platform discriminant catalog string, which arrives kebab-case as
1285/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1286/// (whose variant names each collapse to their own lowercase form under
1287/// the kebab-case transform), while the wire format ran as `PascalCase`
1288/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1289/// serde derive. Every consumer that formatted the policy for a
1290/// diagnostic line, a graph column, or a rejection body under
1291/// `format!("{v}")` therefore landed under a different byte-string than
1292/// the wire format the operator's per-child-policy dispatch keyed off —
1293/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1294/// diagnostic quoting `"permanent"` while the wire scalar the operator
1295/// probed was `"Permanent"`) surfaced as a confused correlate at
1296/// operator-log time far from the two-declaration site.
1297///
1298/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1299/// path: every `format!("{v}")` call reaches the same lifted
1300/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1301/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1302/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1303/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1304/// byte-string per variant. A future variant rename or
1305/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1306/// exactly one place, structurally.
1307///
1308/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1309/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1310/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1311/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1312/// registration keys the catalog off the same kebab identity. The two
1313/// naming worlds now live on separate typed methods (`Display` /
1314/// `as_str` for the wire byte-string, `discriminant` for the catalog
1315/// identity) rather than sharing one `Display` route that structurally
1316/// disagrees with the wire format.
1317///
1318/// Pin tests
1319/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1320/// and
1321/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1322/// assert the three paths agree byte-for-byte on every variant, so a
1323/// future variant rename or per-arm serde attribute drift is a build
1324/// error visible at caixa-core test time, not a silent per-consumer
1325/// dispatch miss at apply / reconcile time.
1326///
1327/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1328/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1329/// and the sibling [`RestartStrategy`] `Display` impl on the
1330/// per-supervisor sibling-restart-strategy axis — same three-path-
1331/// convergence discipline, extended to close the third and final of
1332/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1333/// surface.
1334impl std::fmt::Display for RestartPolicy {
1335    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1336        f.write_str(self.as_str())
1337    }
1338}
1339
1340/// Substrate-canonical [`AsRef<str>`] projection on the M2
1341/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1342/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1343/// scalar accessor the paired [`std::fmt::Display`] impl and the
1344/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1345/// future consumer that binds a [`RestartPolicy`] through the
1346/// standard-library `impl AsRef<str>` bound (a future
1347/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1348/// composes the emitted `PascalCase` wire scalar into a
1349/// [`std::process::Command::arg`] shell-out of the future
1350/// wasm-operator's per-child admission gate, a per-child structured-
1351/// log recorder on the future `caixa-operator`'s hierarchical
1352/// reconciliation surface that accepts `impl AsRef<str>` at the
1353/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1354/// lookup keyed on the restart-policy wire byte through
1355/// `map.get::<str>(policy.as_ref())` on a future per-policy
1356/// dispatch table) reaches the paired
1357/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1358/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1359/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1360/// lifted-const through one substrate-primitive dispatch rather
1361/// than an open-coded `.as_str()` projection at every wire-up.
1362///
1363/// Peer of the sibling [`std::fmt::Display`] impl on the same
1364/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1365/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1366/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1367/// byte-string per instance by construction. A future variant rename
1368/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1369/// enum reaches every one of the three paths (plus the wire-format
1370/// `Serialize` derive that already routes through the same lifted
1371/// const) through exactly one caixa-core edit.
1372///
1373/// Same "route the trait impl through the substrate-primitive
1374/// accessor" discipline the sibling [`crate::CaixaVersion`]
1375/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1376/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1377/// the axis onto the paired per-child-restart-decision-policy
1378/// sibling on the same M2 `:supervisor` slot (the second M2
1379/// OTP-shape closed-set typed enum to converge onto the standard-
1380/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1381/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1382/// primitive so a caller who has one has both; before this lift,
1383/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1384/// [`AsRef<str>`] impl the convention names.
1385///
1386/// Pinned load-bearing by
1387/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1388/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1389/// three-arm closed set) and
1390/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1391/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1392/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1393/// arm) — any future silent detour that routes the impl through a
1394/// divergent projection (a per-arm inline `match self { … }`
1395/// re-inlining that opens a compile-time link to the un-lifted
1396/// arm-literal, a swap onto the kebab-case
1397/// [`gen_platform::Discriminant`] catalog identity that would
1398/// collide the wire axis with the dispatcher-catalog axis) trips at
1399/// caixa-core test time under `assert_eq!` rather than at a
1400/// downstream `impl AsRef<str>`-bound consumer's silent split.
1401impl AsRef<str> for RestartPolicy {
1402    fn as_ref(&self) -> &str {
1403        self.as_str()
1404    }
1405}
1406
1407/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1408/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1409/// byte-for-byte through the paired substrate-primitive
1410/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1411/// consumer that binds a `PascalCase` `:children :restart` wire
1412/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1413/// axis (a future [`caixa-feira`] `feira supervisor --restart
1414/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1415/// `let restart: RestartPolicy = s.try_into()?`, a future
1416/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1417/// `spec.children[*].restart: String` field through
1418/// `RestartPolicy::try_from(&s)?`, a generic
1419/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1420/// set typed enums) reaches the same three-arm accept-set the sibling
1421/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1422/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1423/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1424/// … }` cascade whose arm-set has no compile-time link back to the
1425/// substrate primitive.
1426///
1427/// Complements the pre-existing forward-projection triple
1428/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1429/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1430/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1431/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1432/// caller who can project *out to* a `&str` can also project *in from*
1433/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1434/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1435/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1436/// trigger under a `FromStr` impl and to avoid colliding with the
1437/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1438/// already installs on the paired *kebab-case dispatcher-catalog* axis
1439/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1440/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1441/// idiomatic reverse axis on the *`PascalCase` wire* half without
1442/// disturbing either the method-named `from_wire` shape every sibling
1443/// closed-set typed enum on the substrate already carries or the
1444/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1445/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1446///
1447/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1448/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1449/// caller picks the diagnostic form appropriate for its use site (a
1450/// future `feira supervisor --restart` arg-parse composes its own
1451/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1452/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1453/// wraps the `Err(())` outcome with the accepted-set enumeration for
1454/// operator diagnostics, a `Result::map_err` at the call site lifts the
1455/// unit-error to a per-verb error type). Same shape the peer
1456/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1457/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1458/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1459/// their peer closed-set typed enums' reverse projections.
1460///
1461/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1462/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1463/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1464/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1465/// might reach for once the three canonical OTP restart policies stop
1466/// covering the substrate's discovered load-shape) grows the trait-
1467/// idiomatic axis by construction — one caixa-core edit on
1468/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1469/// projection every existing consumer keys off and the trait-idiomatic
1470/// reverse projection this impl exposes, without a coordinated rewrite
1471/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1472///
1473/// Extends the substrate-wide closed-set-enum reverse-projection family
1474/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1475/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1476/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1477/// closed-enum discriminator axis on the caixa surface — the paired
1478/// per-child `:children :restart` closed set the future wasm-operator's
1479/// hierarchical reconciliation scheduler's per-child post-exit
1480/// restart-decision branch keys off end-to-end.
1481///
1482/// Pinned load-bearing by
1483/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1484/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1485/// three-arm accept-set),
1486/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1487/// (rejection witness against silent accept-set widening), and
1488/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1489/// (cross-axis partition pin locking the trait and method-named
1490/// projections onto one accept-set).
1491impl TryFrom<&str> for RestartPolicy {
1492    type Error = ();
1493
1494    fn try_from(s: &str) -> Result<Self, Self::Error> {
1495        Self::from_wire(s).ok_or(())
1496    }
1497}
1498
1499/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1500/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1501/// byte-for-byte through the paired substrate-primitive
1502/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1503/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1504/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1505/// &str` with `'static` lifetime, so the trait's return-type promise is
1506/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1507/// literal.
1508///
1509/// Every future consumer that specifically needs `&'static str` lifetime
1510/// bytes on the per-child restart-decision axis (a
1511/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1512/// arm's typing demands `&'static str`, a
1513/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1514/// on the future M4 admission-webhook rejection body where the
1515/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1516/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1517/// or error formatter that requires the `'static` bound) reaches the same
1518/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1519/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1520/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1521/// primitive dispatch rather than an open-coded per-arm literal cascade
1522/// whose arm-set has no compile-time link back to the substrate primitive.
1523///
1524/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1525/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1526/// the second (and second-of-two-in-M2) closed-set typed enum on the
1527/// caixa surface to converge onto the paired trait-idiomatic forward-
1528/// projection axis. With this lift the paired per-child
1529/// `:children :restart` closed-set typed enum carries the full sibling
1530/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1531/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1532/// lift) plus the round-trip witness through both the trait-idiomatic
1533/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1534/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1535/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1536/// (an OTP-`intrinsic` fourth arm the theory
1537/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1538/// might reach for once the three canonical OTP restart policies stop
1539/// covering the substrate's discovered load-shape) grows the trait-
1540/// idiomatic forward axis by construction: one caixa-core edit on
1541/// [`RestartPolicy::as_str`] extends every one of the five sibling
1542/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1543/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1544/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1545/// bytes) without a coordinated rewrite across every future
1546/// `Into<&'static str>`-bound consumer's arm-set.
1547///
1548/// Pinned load-bearing by
1549/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1550/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1551/// three-arm emit-set, plus a `const`-context materialization witness for
1552/// the `&'static str` lifetime promise) and
1553/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1554/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1555/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1556/// round-trip witness through the paired trait-idiomatic reverse-
1557/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1558/// `policy.into::<&'static str>()` output re-parses back through
1559/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1560/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1561impl From<RestartPolicy> for &'static str {
1562    fn from(policy: RestartPolicy) -> &'static str {
1563        policy.as_str()
1564    }
1565}
1566
1567/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
1568/// *borrowed* input onto the `&'static str` axis — the borrowed-input
1569/// companion to the paired owned-input [`From<RestartPolicy> for
1570/// &'static str`] impl immediately above. Routes byte-for-byte through
1571/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
1572/// fn` accessor so every consumer that binds a `&RestartPolicy`
1573/// through the standard-library `.into()` / [`From<&Self> for &'static
1574/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
1575/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
1576/// whose iterator over `&'static [RestartPolicy]` yields
1577/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
1578/// [`From<RestartPolicy>`] axis alone forces every call site through
1579/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
1580/// rather than the direct trait-idiomatic projection; a future generic
1581/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
1582/// that walks the `iter().map(Into::into)` shape verbatim across every
1583/// substrate-wide closed-set typed enum; the future wasm-operator's
1584/// per-child post-exit restart-decision diagnostic line that composes
1585/// the accepted-set enumeration from an iterated
1586/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1587/// per-arm `match p { … }` cascade; a future
1588/// `HashMap::<&'static str, RestartPolicy>::from_iter(
1589///     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
1590/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
1591/// cannot compose without this borrowed-input axis in place) reaches
1592/// the same three-arm lifted
1593/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1594/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1595/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1596/// paired owned-input [`From<RestartPolicy> for &'static str`], the
1597/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
1598/// [`RestartPolicy::as_str`] surfaces already return.
1599///
1600/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
1601/// forward-projection family opened on [`crate::dep::DepList`]
1602/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
1603/// [`crate::CaixaDialeto`] (807b0b5), and the paired
1604/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
1605/// (e941836). Rust's `From` trait does not auto-derive the
1606/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
1607/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
1608/// exist in `core`), so every closed-set typed enum that carries the
1609/// owned-input axis but not the borrowed-input axis forces every
1610/// borrowed-input call site through a `.copied()` /
1611/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
1612/// type bounds have no compile-time link to the substrate primitive.
1613/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
1614/// OTP-shape peer to converge onto this campaign — sibling of the
1615/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
1616/// with this lift both closed-set typed enums on the M2 `:supervisor`
1617/// slot now carry the full sibling quintet ([`std::fmt::Display`],
1618/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
1619/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
1620/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
1621/// forward-projection axis on the M2 OTP-shape slot as a unit.
1622///
1623/// Same three-path convergence discipline as the paired owned-input
1624/// impl (this borrowed-input axis, the paired owned-input
1625/// [`From<RestartPolicy> for &'static str`], and
1626/// [`RestartPolicy::as_str`] all route through the same lifted
1627/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
1628/// variant rename or per-arm serde-attribute drift reaches every one
1629/// of the six sibling forward-projection paths
1630/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1631/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
1632/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
1633/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
1634/// edit.
1635///
1636/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
1637/// parse share the same `PascalCase` vocabulary by construction, so
1638/// the borrowed-input forward axis and the reverse axis compose
1639/// directly — the round-trip witness pin below locks this direct
1640/// composition without the intermediate wire-vocab hop the peer
1641/// [`crate::CaixaKind`] axis pair requires.
1642///
1643/// Pinned load-bearing by
1644/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
1645/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1646/// three-arm emit-set via a borrowed input, plus a `const`-context
1647/// materialization witness for the `&'static str` lifetime promise,
1648/// plus a blanket `.into()` shape) and
1649/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
1650/// (cross-axis partition pin against the paired owned-input
1651/// [`From<RestartPolicy> for &'static str`] impl, plus a
1652/// `.iter().map(Into::into)` pipe witness over
1653/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1654/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
1655/// Self` round-trip without the wire-vocab intermediate the peer
1656/// [`crate::CaixaKind`] axis pair requires).
1657impl From<&RestartPolicy> for &'static str {
1658    fn from(policy: &RestartPolicy) -> &'static str {
1659        policy.as_str()
1660    }
1661}
1662
1663/// Trait-idiomatic *owned-`String`* forward projection on the second
1664/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
1665/// owned-heap-string companion to the paired `&'static str`-returning
1666/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
1667/// for &'static str`] impls immediately above. Routes byte-for-byte
1668/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
1669/// const fn` accessor (via [`str::to_owned`]) so every consumer that
1670/// binds a [`RestartPolicy`] through the standard-library `.into()` /
1671/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
1672/// future `serde_json::Value::String(policy.into())` structured-payload
1673/// composer where the `Value::String` arm typing demands an owned
1674/// [`String`] and the sibling [`&'static str`]-returning axis forces
1675/// an explicit `.to_owned()` / `String::from` restatement at every
1676/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
1677/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
1678/// lookup where the map's key type is owned [`String`] rather than
1679/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
1680/// composer on the future M4 admission-webhook rejection body's
1681/// owned-arm, the future wasm-operator's per-child post-exit
1682/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
1683/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
1684/// — reaches the same three-arm lifted
1685/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1686/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1687/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1688/// paired [`std::fmt::Display`], [`AsRef<str>`],
1689/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
1690/// forward-projection impls already return.
1691///
1692/// Extends the trait-idiomatic *owned-`String`* forward-projection
1693/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
1694/// the caixa surface — mirror of the first-mover
1695/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
1696/// axis on the sibling supervisor-level strategy enum. Rust's standard
1697/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
1698/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
1699/// every closed-set typed enum that carries the paired `AsRef<str>` /
1700/// `Display` / `From<Self> for &'static str` triple but not the
1701/// owned-[`String`] axis forces every owned-string call site through a
1702/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
1703/// detour whose type bounds have no compile-time link to the
1704/// substrate primitive.
1705///
1706/// Deliberately routes through the human-readable
1707/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1708/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1709/// the diagnostic byte-string share the same vocabulary by
1710/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1711/// two axes diverge), so the owned-[`String`] projection lands
1712/// byte-identically on both the wire vocabulary the paired
1713/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
1714/// [`RestartPolicy::as_str`] helper returns, and — because the paired
1715/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
1716/// axis parses the same `PascalCase` vocabulary — the direct two-way
1717/// `Self → String → Self` round-trip composes without the wire-vocab
1718/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
1719/// axis pair requires.
1720///
1721/// Pinned load-bearing by
1722/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
1723/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1724/// three-arm emit-set, plus a blanket `.into::<String>()` shape
1725/// witness) and
1726/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
1727/// (cross-axis partition pin against the paired owned-input
1728/// [`From<RestartPolicy> for &'static str`] impl and the sibling
1729/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
1730/// plus a `.iter().copied().map(String::from)` pipe witness over
1731/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1732/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
1733/// borrow that closes the two-way `Self → String → Self` round-trip
1734/// on the trait-idiomatic owned-[`String`] forward + reverse axis
1735/// pair).
1736impl From<RestartPolicy> for String {
1737    fn from(policy: RestartPolicy) -> String {
1738        policy.as_str().to_owned()
1739    }
1740}
1741
1742/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
1743/// projection on the second-of-two M2 OTP-shape closed-set typed enum
1744/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
1745/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1746/// projection family on this enum, mirror of the first-mover
1747/// [`From<&RestartStrategy> for String`] (579385f) that opened the
1748/// 2×2-completion corner on the sibling supervisor-level strategy
1749/// enum. Routes byte-for-byte through the substrate-primitive
1750/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
1751/// [`str::to_owned`]) so every consumer that holds a borrowed
1752/// [`&RestartPolicy`] and needs an owned [`String`] — a future
1753/// `serde_json::Value::String(String::from(&policy))` structured-payload
1754/// composer over a borrowed field, a future `Iterator::map` over
1755/// `&[RestartPolicy]` that projects to owned keys through
1756/// `.iter().map(String::from)`, a future `HashMap::<String,
1757/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
1758/// where dereferencing the policy would force an unnecessary `Copy` at
1759/// every step, the future wasm-operator's per-supervisor
1760/// `child_policies.iter().map(String::from).collect()` per-child post-
1761/// exit restart-decision diagnostic emit whose iteration axis is
1762/// borrowed by construction — reaches the same three-arm lifted
1763/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1764/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1765/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1766/// paired [`std::fmt::Display`], [`AsRef<str>`],
1767/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
1768/// forward-projection impls
1769/// ([`From<RestartPolicy> for &'static str`],
1770/// [`From<&RestartPolicy> for &'static str`],
1771/// [`From<RestartPolicy> for String`]) already return.
1772///
1773/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
1774/// owned-`String` output* forward-projection family opened on
1775/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
1776/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
1777/// both M2 OTP-shape sibling peers (the paired supervisor-level
1778/// sibling-restart-strategy axis and the per-child restart-decision-
1779/// policy axis), so the whole M2 OTP-shape axis pair now carries the
1780/// full four-corner family by construction. Rust's standard library
1781/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
1782/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
1783/// closed-set typed enum that carries the paired `AsRef<str>` /
1784/// `Display` / `From<Self> for &'static str` / `From<&Self> for
1785/// &'static str` / `From<Self> for String` quintuple but not the
1786/// borrowed-input owned-[`String`] axis forces every borrowed-input
1787/// owned-string call site through a `policy.as_str().to_owned()` /
1788/// `String::from(*policy)` (with a spurious `Copy`) /
1789/// `policy.to_string()` (through `Display`) detour whose type bounds
1790/// have no compile-time link to the substrate primitive.
1791///
1792/// Deliberately routes through the human-readable
1793/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1794/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1795/// the diagnostic byte-string share the same vocabulary by
1796/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1797/// two axes diverge), so the borrowed-input owned-[`String`]
1798/// projection lands byte-identically on both the wire vocabulary the
1799/// paired [`serde::Serialize`] derive emits and the diagnostic
1800/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
1801/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
1802/// reverse-projection axis parses the same `PascalCase` vocabulary —
1803/// the direct two-way `&Self → String → Self` round-trip composes
1804/// without the wire-vocab intermediate hop the peer
1805/// [`crate::CaixaKind`] axis pair requires.
1806///
1807/// The remaining thirteen closed-set typed enums on the caixa
1808/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
1809/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
1810/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
1811/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
1812/// of this 2×2-completion campaign — each carries the same paired
1813/// quintuple that this borrowed-input owned-[`String`] axis extends
1814/// onto.
1815///
1816/// Pinned load-bearing by
1817/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
1818/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1819/// three-arm emit-set through the borrowed-input surface) and
1820/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
1821/// (cross-axis partition pin against the paired owned-input owned-
1822/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
1823/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
1824/// &'static str`] impl, and the sibling [`ToString::to_string`]
1825/// surface routed through [`std::fmt::Display`], plus a direct round-
1826/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
1827/// [`String::as_str`] borrow that closes the two-way
1828/// `&Self → String → Self` round-trip on the trait-idiomatic
1829/// borrowed-input owned-[`String`] forward + reverse axis pair).
1830impl From<&RestartPolicy> for String {
1831    fn from(policy: &RestartPolicy) -> String {
1832        policy.as_str().to_owned()
1833    }
1834}
1835
1836/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
1837/// output* forward projection on the M2 OTP-shape per-child-restart
1838/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
1839/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
1840/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
1841/// borrowed-input) and first extended off it onto the sibling M2
1842/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
1843/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
1844/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
1845/// surface (`:children :restart`). Routes byte-for-byte through the
1846/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
1847/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
1848/// that binds a [`RestartPolicy`] through the trait-idiomatic
1849/// [`std::borrow::Cow<'static, str>`] axis — a future
1850/// `axum::response::IntoResponse` composer whose per-policy
1851/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
1852/// borrowed return, a future M4 admission-webhook rejection body
1853/// that composes the accepted-policy enumeration through the same
1854/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
1855/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
1856/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
1857/// emitter on a per-child-policy diagnostic column — reaches the same
1858/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
1859/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1860/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1861/// paired [`std::fmt::Display`], [`AsRef<str>`],
1862/// [`RestartPolicy::as_str`], and the four
1863/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1864/// forward-projection corners already return.
1865///
1866/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
1867/// [`std::borrow::Cow::Owned`] — the substrate-primitive
1868/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
1869/// str` lifetime by construction (each `match` arm resolves to a
1870/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
1871/// with static lifetime), so the zero-alloc borrowed arm is the
1872/// type-correct projection with no runtime allocation.
1873///
1874/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
1875/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
1876/// From<T> for Cow<'static, str>`), so the paired sibling
1877/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
1878/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
1879/// [`std::fmt::Display`] surfaces do not implicitly extend to a
1880/// [`Cow<'static, str>`]-bound call site — every such site is forced
1881/// through a `Cow::Borrowed(policy.as_str())` /
1882/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
1883/// no compile-time link back to the substrate primitive until this
1884/// lift.
1885///
1886/// Second peer to extend the substrate-wide trait-idiomatic
1887/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
1888/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
1889/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
1890/// tier of the campaign (both sibling peers, `RestartStrategy` and
1891/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
1892/// forward projection) so the remaining eleven peers
1893/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
1894/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
1895/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
1896/// `FerriteRuntime`) are the future targets. Every future arm addition
1897/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
1898/// might reach for once the three canonical OTP restart policies stop
1899/// covering the substrate's discovered load-shape) grows the
1900/// Cow<'static, str> axis by construction through one caixa-core edit
1901/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
1902/// across every future Cow<'static, str>-bound consumer site.
1903///
1904/// Pinned load-bearing by
1905/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
1906/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
1907/// against [`RestartPolicy::as_str`] across the three-arm
1908/// [`RestartPolicy::ALL`]) and
1909/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
1910/// (cross-axis partition pin against the paired [`From<RestartPolicy>
1911/// for &'static str`], [`From<RestartPolicy> for String`], and
1912/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
1913/// `.iter().copied().map(Cow::from)` pipe witness over
1914/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
1915/// through the [`Cow<'static, str>`] axis alone and pins the
1916/// zero-alloc discipline on every element).
1917impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
1918    fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
1919        std::borrow::Cow::Borrowed(policy.as_str())
1920    }
1921}
1922
1923/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
1924/// output* forward projection on the M2 OTP-shape per-child-restart
1925/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
1926/// companion to the paired owned-input
1927/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
1928/// immediately above (0612398). Routes byte-for-byte through the same
1929/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
1930/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
1931/// that holds a `&RestartPolicy` and needs a
1932/// [`std::borrow::Cow<'static, str>`] — a
1933/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
1934/// per-arm accept-set materializer (whose iterator over
1935/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
1936/// `RestartPolicy`, so the paired owned-input
1937/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
1938/// alone forces every call site through an explicit `.copied()` /
1939/// dereference / [`Copy`]-bound restatement rather than the direct
1940/// trait-idiomatic projection), a future generic
1941/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
1942/// on a per-child-policy diagnostic column that walks the
1943/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
1944/// webhook rejection body that composes the accepted-policy
1945/// enumeration from an iterated
1946/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1947/// per-arm `match p { … }` cascade — reaches the same three-arm
1948/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1949/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1950/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1951/// paired [`std::fmt::Display`], [`AsRef<str>`],
1952/// [`RestartPolicy::as_str`], the four
1953/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1954/// forward-projection corners, and the paired owned-input
1955/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
1956/// already return.
1957///
1958/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
1959/// [`std::borrow::Cow::Owned`] — the substrate-primitive
1960/// [`RestartPolicy::as_str`] accessor's return carries the
1961/// `&'static str` lifetime by construction (each `match` arm resolves
1962/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
1963/// with static lifetime), so the zero-alloc borrowed arm is the
1964/// type-correct projection with no runtime allocation.
1965///
1966/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
1967/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
1968/// one commit prior (0612398) on the paired owned-input
1969/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
1970/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
1971/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
1972/// which carries both {Self, &Self} × Cow<'static, str> corners since
1973/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
1974/// closed it on the top-level [`crate::CaixaKind`] one commit after
1975/// the owning half (99c1735) landed. This lift closes the whole M2
1976/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
1977/// forward-projection campaign on both input-shape corners
1978/// ({Self, &Self}) of both M2 OTP-shape sibling peers
1979/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
1980/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
1981/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
1982/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
1983/// `FerriteRuntime`) become the future targets of the campaign. Rust's
1984/// standard library does not carry a blanket
1985/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
1986/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
1987/// closed-set fieldless typed enum peer on the substrate that carries
1988/// the paired owned-input [`Cow<'static, str>`] axis but not the
1989/// borrowed-input axis forces every borrowed-input
1990/// [`Cow<'static, str>`]-parameterized call site through a spurious
1991/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
1992/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
1993/// bounds have no compile-time link to the substrate primitive.
1994///
1995/// Pinned load-bearing by
1996/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
1997/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
1998/// against [`RestartPolicy::as_str`] across the three-arm
1999/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
2000/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2001/// (cross-axis partition pin against the paired owned-input
2002/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
2003/// paired borrowed-input owned-`&'static str`
2004/// [`From<&RestartPolicy> for &'static str`], and the paired
2005/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
2006/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
2007/// over [`RestartPolicy::ALL`] — whose iterator yields
2008/// `&RestartPolicy` by construction, so the borrowed-input
2009/// [`Cow<'static, str>`] axis is what routes the pipe through the
2010/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
2011/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
2012/// spurious [`Copy`] deref).
2013impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
2014    fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
2015        std::borrow::Cow::Borrowed(policy.as_str())
2016    }
2017}
2018
2019// Fleet-wide dispatcher-catalog registrations for caixa's OTP
2020// supervisor surface — two more typed shadows over Erlang/OTP
2021// primitives the substrate now mechanically tracks (see
2022// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
2023// theory/TYPED-ABSORPTION.md for the absorption arc).
2024gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
2025gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
2026
2027/// One child entry in the supervisor's `:children` list.
2028///
2029/// Every child references another caixa by `:caixa <nome>` + version
2030/// constraint. The supervisor materializes one ComputeUnit per entry.
2031#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2032#[serde(rename_all = "camelCase")]
2033pub struct ChildSpec {
2034    /// The child caixa's `:nome`. Must resolve via the same dependency
2035    /// resolution path as `:deps` (caixa-resolver).
2036    pub caixa: String,
2037
2038    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
2039    /// [`crate::dep::Dep::versao`].
2040    pub versao: String,
2041
2042    /// Restart policy — an author-omitted slot degrades onto the
2043    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
2044    /// (`permanent`, the Erlang/OTP worker-child default) through the
2045    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
2046    /// to.
2047    #[serde(default)]
2048    pub restart: RestartPolicy,
2049}
2050
2051impl ChildSpec {
2052    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
2053    /// accessor every consumer that reads the OTP-shape supervised
2054    /// child's identity keys off — returns the author-declared
2055    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
2056    /// from the typed slot's own [`String`] storage.
2057    ///
2058    /// The `:children :caixa` slot carries the DNS-1123 label — the
2059    /// child caixa's `:nome` — that every emitted cluster artifact
2060    /// derives its `metadata.name` from verbatim: the rendered
2061    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
2062    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
2063    /// identity, and the per-child K8s Service `metadata.name` the
2064    /// future wasm-operator (M3) provisions for inter-child supervision-
2065    /// tree wiring. Every downstream consumer that fans on the child's
2066    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
2067    /// per-child DNS-1123 gate at
2068    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
2069    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
2070    /// [`validate_no_self_supervision`] cross-slot equality check
2071    /// against the parent's `:nome`, every `SupervisorError` variant
2072    /// carrying the offending child caixa verbatim for `feira lint`
2073    /// rendering, the future wasm-operator's hierarchical reconciliation
2074    /// scheduler's per-child ComputeUnit-name projection, the future M4
2075    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2076    /// admission webhook).
2077    ///
2078    /// Prior to this lift the `.caixa` byte-string was accessed inline
2079    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
2080    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
2081    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
2082    /// carriers' `child.caixa.clone()`, the dedup key's
2083    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
2084    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
2085    /// field-accesses that expressed no compile-time link back to the
2086    /// typed slot. A future extension of the `:children :caixa` axis to
2087    /// a richer author surface (a per-cluster alias table the operator
2088    /// pins through a future `:placement`-scoped slot on the supervisor
2089    /// tree, a namespace-qualified rewrite the M4 CR materializer
2090    /// applies per-CR, a per-child overlay from the future `:children
2091    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2092    /// acknowledges) would have had to be threaded through every
2093    /// open-coded copy in lockstep or one consumer would silently
2094    /// disagree with the peers on which caixa a given child resolves to
2095    /// — a child-set lookup that treated the name as `"cart-worker"`
2096    /// while the peer duplicate-detector treated it as
2097    /// `"tenant-a/cart-worker"` would silently split the
2098    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
2099    /// self-supervision detector's parent-equality check, a two-consumer
2100    /// split at the validator far from the source `caixa.lisp` with no
2101    /// field naming the identity-drift root cause. Lifting the resolution
2102    /// rule to a typed method on the substrate primitive means every
2103    /// downstream consumer of the Supervisor's per-`:children` identity
2104    /// surface reaches for exactly one typed dispatch — the resolver's
2105    /// accept-set migrates as a unit on any future axis addition.
2106    ///
2107    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
2108    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
2109    /// mesh-slot surface — same "one typed dispatch on the substrate
2110    /// primitive, thin projections at each consumer" discipline extended
2111    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
2112    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
2113    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
2114    /// accessor discipline for the shared substrate concept "another
2115    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
2116    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
2117    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
2118    /// slot family's typed-accessor discipline now spans both the
2119    /// upgrade axis (`:upgrade-from`) and the supervision axis
2120    /// (`:children`), matching the closed M3 mesh-slot accessor family's
2121    /// shape. Named `nome()` to match the tatara-lisp author-surface
2122    /// term the field's docstring already reaches for ("The child
2123    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
2124    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
2125    /// discipline the substrate already carries — the accessor's name
2126    /// maps directly onto the canonical caixa-identity vocabulary rather
2127    /// than shadowing the field's storage-side `caixa` label.
2128    #[must_use]
2129    pub const fn nome(&self) -> &str {
2130        self.caixa.as_str()
2131    }
2132
2133    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
2134    /// requirement scalar accessor every consumer that reads the OTP-shape
2135    /// supervised child's version pin keys off — returns the author-declared
2136    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
2137    /// the typed slot's own [`String`] storage.
2138    ///
2139    /// The `:children :versao` slot carries the Cargo-shaped semver
2140    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
2141    /// which release of the supervised child caixa the OTP-shape supervisor
2142    /// tree materializes against — the same requirement grammar the peer
2143    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
2144    /// shared [`crate::render::require_valid_versao_requirement`] cascade
2145    /// and the shared [`crate::version::parse_requirement`] parser. Every
2146    /// downstream consumer that fans on the child's version pin keys off
2147    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
2148    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
2149    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
2150    /// for `feira lint` rendering, every future per-cluster version-lock
2151    /// overlay the caixa-operator's hierarchical reconciliation scheduler
2152    /// pins through a future `:placement`-scoped supervisor-tree slot, the
2153    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2154    /// per-child version resolver, the future wasm-operator's per-child
2155    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
2156    ///
2157    /// Prior to this lift the `.versao` byte-string was accessed inline at
2158    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
2159    /// [`SupervisorSpec::validate`] requirement-gate call
2160    /// `require_valid_versao_requirement(&child.versao, …)` and the
2161    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
2162    /// `versao: child.versao.clone()` — two open-coded field-accesses that
2163    /// expressed no compile-time link back to the typed slot. A future
2164    /// extension of the `:children :versao` axis to a richer author surface
2165    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2166    /// flow, a lacre-projected concrete-version rewrite the operator
2167    /// materializes at CR-admission time, a future `:children :versao-lock`
2168    /// per-cluster override slot the wasm-operator's hierarchical
2169    /// reconciliation scheduler authors per-CR) would have had to be
2170    /// threaded through both open-coded copies in lockstep or one consumer
2171    /// would silently disagree with the peer on which release constraint a
2172    /// given child resolves to — the requirement-gate call reading
2173    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
2174    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
2175    /// the actual gate rejection input, a two-consumer split at the
2176    /// validator far from the source `caixa.lisp` with no field naming the
2177    /// version-pin drift root cause. Lifting the resolution rule to a typed
2178    /// method on the substrate primitive means every downstream
2179    /// requirement-facing consumer of the Supervisor's per-`:children`
2180    /// version-pin surface reaches for exactly one typed dispatch — the
2181    /// resolver's accept-set migrates as a unit on any future axis addition.
2182    ///
2183    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
2184    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
2185    /// surface — same "one typed dispatch on the substrate primitive, thin
2186    /// projections at each consumer" discipline extended onto the M2
2187    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
2188    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
2189    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
2190    /// one accessor discipline for the shared substrate concept "another
2191    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
2192    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
2193    /// `:nome` scalar accessor — the pair
2194    /// `(nome(), versao_requirement())` jointly projects the
2195    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
2196    /// that fans on per-child identity + version pin keys off, closing the
2197    /// last unlifted per-`:children` `String`-carry axis so every downstream
2198    /// per-`:children` reader now routes through a typed dispatch on the
2199    /// substrate primitive. Named `versao_requirement()` rather than
2200    /// `versao()` because the field's storage-side `.versao` label is
2201    /// already the author-surface term (`:versao`); the accessor's name
2202    /// carries the semantic role — the semver *requirement* string the
2203    /// shared [`crate::version::parse_requirement`] entry-point consumes —
2204    /// so a raw field access and a typed dispatch read differently at every
2205    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
2206    /// naming discipline verbatim.
2207    #[must_use]
2208    pub const fn versao_requirement(&self) -> &str {
2209        self.versao.as_str()
2210    }
2211
2212    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
2213    /// per-child post-exit restart-decision policy scalar accessor every
2214    /// consumer that dispatches on the supervised child's post-exit
2215    /// reconcile posture keys off — returns the author-declared
2216    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
2217    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
2218    /// storage.
2219    ///
2220    /// The `:children :restart` slot carries the closed-set OTP-shaped
2221    /// per-child restart-decision policy discriminator
2222    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
2223    /// worker-child default; [`RestartPolicy::Transient`] — restart only
2224    /// on abnormal exit, the OTP `transient` clean-completion-aware
2225    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
2226    /// `temporary` one-shot default) that every downstream consumer of
2227    /// the Supervisor's per-child post-exit reconcile branch keys off.
2228    /// Every future downstream consumer that fans on the per-child
2229    /// restart-decision keys off this scalar (the future `feira app
2230    /// graph` per-child restart column, the future wasm-operator's
2231    /// per-child post-exit restart-decision branch, the future M4
2232    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2233    /// admission webhook, the `caixa-operator`'s hierarchical
2234    /// reconciliation scheduler's per-child post-exit reconcile branch,
2235    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
2236    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
2237    /// pin threads through).
2238    ///
2239    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
2240    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
2241    /// scalar accessor and the M3 mesh-slot
2242    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
2243    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
2244    /// — same "one typed dispatch on the substrate primitive,
2245    /// `Copy`-projected closed-set enum-arm discriminator that partitions
2246    /// the downstream renderer's per-arm fan-out" discipline extended
2247    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
2248    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
2249    /// [`ChildSpec`] type — companion to the sibling per-`:children`
2250    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
2251    /// and the per-`:children` [`ChildSpec::versao_requirement`]
2252    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
2253    /// on the sibling `String`-carry axes. The triple
2254    /// `(nome(), versao_requirement(), restart())` jointly projects the
2255    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
2256    /// tree consumer that fans on per-child identity + version pin +
2257    /// restart-decision keys off, closing the last unlifted per-`:children`
2258    /// axis so every downstream per-`:children` reader now routes through
2259    /// a typed dispatch on the substrate primitive. Named `restart()` to
2260    /// match the storage field's name and the author-surface
2261    /// `:children :restart` slot term verbatim; the accessor's identity
2262    /// name maps onto the canonical OTP-shape per-child restart-decision-
2263    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
2264    /// carries.
2265    ///
2266    /// Declared `pub const fn` to close the last non-`const`
2267    /// `Copy`-return raw-field-getter posture on the M2
2268    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
2269    /// of the sibling M2 per-`:supervisor`
2270    /// [`SupervisorSpec::estrategia`] (converted in this commit)
2271    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
2272    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2273    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
2274    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
2275    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
2276    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
2277    /// downstream substrate-side `const`-context consumer of the
2278    /// per-`:children` restart-decision-policy scalar (a future
2279    /// module-scope `const _:() = assert!(matches!(child.restart(),
2280    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
2281    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2282    /// admission-webhook `const fn` per-child restart-decision floor
2283    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
2284    /// composer over the substrate primitive that fans on the per-child
2285    /// restart-decision policy at compile time) now reaches through the
2286    /// same typed dispatch on the substrate primitive at const-eval
2287    /// time as at runtime. A future non-`Copy`-return promotion of the
2288    /// scalar (an `Option<RestartPolicy>`-shape migration on the
2289    /// per-child restart-decision axis once heterogeneous per-cluster
2290    /// restart-policy overlays land, a per-tenant restart-policy-alias
2291    /// table the M4 CR materializer resolves per-CR) that would drop
2292    /// the `const` qualifier fails the fail-before-pass-after pin
2293    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
2294    /// build time rather than surfacing as a downstream consumer
2295    /// regression.
2296    #[must_use]
2297    pub const fn restart(&self) -> RestartPolicy {
2298        self.restart
2299    }
2300}
2301
2302/// Supervisor-typed slots that live alongside the standard Caixa
2303/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
2304/// the manifest stays a single typed form; this struct exists for
2305/// validation + conversion.
2306#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2307#[serde(rename_all = "camelCase")]
2308pub struct SupervisorSpec {
2309    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
2310    #[serde(default)]
2311    pub estrategia: RestartStrategy,
2312
2313    /// Max restarts within [`Self::restart_window`] before the
2314    /// supervisor itself terminates (and its parent supervisor decides
2315    /// what to do). Default 5.
2316    #[serde(default = "default_max_restarts")]
2317    pub max_restarts: u32,
2318
2319    /// Sliding window for `max_restarts`. Authored as a duration
2320    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
2321    /// is rejected by [`Self::validate`] — Erlang/OTP's
2322    /// `MaxIntensity / Period` invariant requires a positive window
2323    /// (a zero-period supervisor either trips on the first failure or
2324    /// never trips, depending on operator interpretation, neither of
2325    /// which is the author's intent). Omit the slot to express "no
2326    /// reset"; carry a positive duration to express the sliding window.
2327    #[serde(
2328        default,
2329        skip_serializing_if = "Option::is_none",
2330        with = "duration_codec"
2331    )]
2332    pub restart_window: Option<Duration>,
2333
2334    /// Static children. Empty for `SimpleOneForOne` (children added
2335    /// dynamically); required for the other three strategies.
2336    #[serde(default)]
2337    pub children: Vec<ChildSpec>,
2338}
2339
2340const fn default_max_restarts() -> u32 {
2341    // Route the private serde-`#[serde(default = "…")]` helper through
2342    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
2343    // `pub const` rather than the raw `5` literal — one source of truth
2344    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
2345    // default across the two production consumers that currently
2346    // dispatch on it (this helper via `#[serde(default = "…")]` on
2347    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
2348    // impl at line 962). Pinned by
2349    // `default_max_restarts_helper_routes_through_lifted_default` +
2350    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
2351    // in the tests module; peer of the sibling caixa-core
2352    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
2353    // that now routes its author-omitted `:max-restarts` arm through
2354    // the same lifted constant.
2355    SUPERVISOR_MAX_RESTARTS_DEFAULT
2356}
2357
2358/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
2359/// count default for the `:supervisor :max-restarts` axis — the
2360/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
2361/// Erlang's worker-supervisor default, extracted as a typed `pub const`
2362/// so every substrate-side consumer that resolves "what
2363/// [`SupervisorSpec::max_restarts`] value does an author-omitted
2364/// `:max-restarts` slot degrade onto?" reaches for exactly one
2365/// substrate-primitive `u32`.
2366///
2367/// The `:max-restarts` default axis has two production consumers on the
2368/// substrate side today (both prior to this lift folded onto raw `5`
2369/// literals with no compile-time link back to a shared truth): the
2370/// serde-`#[serde(default = "default_max_restarts")]` helper on
2371/// [`SupervisorSpec::max_restarts`] that every author-omitted
2372/// `:supervisor :max-restarts` slot lands in past the derive-macro's
2373/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
2374/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
2375/// the composed [`SupervisorSpec`] altitude reaches through
2376/// (`feira app graph`, the future wasm-operator's per-supervisor
2377/// restart-intensity counter, the future M4
2378/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2379/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
2380/// A pair of open-coded `5`s across two files that expressed no
2381/// compile-time link back to the shared OTP-canonical default — a
2382/// future rebrand of the default (a tightening to Elixir's
2383/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
2384/// the operator pins through a future
2385/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
2386/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2387/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
2388/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
2389/// per-child-cohort roadmap lands) would have had to be threaded
2390/// through both open-coded copies in lockstep or the wire-format
2391/// author-omitted arm and the view-construction author-omitted arm
2392/// would silently disagree on which restart-budget an omitted
2393/// `:max-restarts` resolves to (an author writing `:supervisor
2394/// (:max-restarts ())` would round-trip through serde with the new
2395/// default while `supervisor_view` silently continued to compose the
2396/// stale `5`, or vice versa), a two-consumer split at the composition
2397/// boundary far from the source `caixa.lisp` with no field naming the
2398/// default-drift root cause. Lifting the resolution rule to a typed
2399/// `pub const` on the substrate primitive means every downstream
2400/// consumer of the per-Supervisor default-restart-budget-count surface
2401/// reaches for exactly one substrate-primitive `u32` — the resolver's
2402/// accepted value migrates as a unit on any future axis change.
2403///
2404/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2405/// worker-supervisor default (the closest canonical OTP-shape
2406/// production reference the substrate carries, matching the sibling
2407/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
2408/// this constant with on the paired sliding-window axis). Two orders of
2409/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
2410/// (the upper bracket on the same axis, sibling of this lower default;
2411/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
2412/// axis and now share one accessor discipline on the substrate) and
2413/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
2414/// restart floor — the "one restart, then escalate" default is
2415/// deliberately loose enough to absorb a short burst of transient
2416/// child failures without escalating past the supervisor's parent
2417/// while remaining tight enough to trip the `MaxIntensity / Period`
2418/// ratio's escalation on a genuinely-stuck child within the sibling
2419/// `60s` sliding window.
2420///
2421/// Lifted as a typed `pub const` so the bound has exactly one source
2422/// of truth — the serde-side wire-format author-omitted arm at
2423/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
2424/// struct-literal default field, and the caixa-core
2425/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
2426/// arm all read from one place. Same shape every other typed default
2427/// in this crate carries (the sibling
2428/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
2429/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
2430/// sibling `:restart-window` axis, and the peer
2431/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2432/// per-renderer defaults on the caixa-flux / caixa-helm rendering
2433/// axes).
2434pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
2435
2436/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
2437/// validated [`SupervisorSpec::max_restarts`] past
2438/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
2439///
2440/// The typed field is `u32` (the zero-floor arm
2441/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
2442/// so a programmatic struct literal
2443/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
2444/// author-surface form (`:max-restarts 4294967295` or any
2445/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
2446/// cleanly through serde — a structurally unbounded `u32` ceiling. The
2447/// runtime substrate consuming the value (Erlang/OTP's
2448/// `MaxIntensity / Period` ratio, the future wasm-operator's
2449/// per-supervisor restart-intensity counter, the M4
2450/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
2451/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
2452/// escalation threshold is structurally so high that no realistic
2453/// restarts-per-`:restart-window` traffic shape can reach it, the
2454/// supervisor never escalates to its parent, and a bad child can loop
2455/// inside the window indefinitely with the parent supervisor structurally
2456/// never receiving the "this subtree has exceeded its restart budget"
2457/// signal the typed slot is meant to express — the canonical
2458/// "supervisor intensity declared, no escalation" footgun, exactly the
2459/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
2460/// on the `:politicas :circuit-breaker :max-failures` axis (both are
2461/// "trip the next-higher protection layer after N events in a rolling
2462/// window" counters with identical degenerate-at-the-high-end shape).
2463///
2464/// The `1000` ceiling matches the sibling
2465/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
2466/// peer — same "events-per-window trip threshold" semantics, same `u32`
2467/// type, same no-op-at-the-high-end failure mode) so the M4
2468/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
2469/// and the future wasm-operator's per-supervisor restart-intensity
2470/// counter reach for either field knowing the value is in `1..=1000`
2471/// without re-validating at the reconciler layer. The cap sits two
2472/// orders of magnitude above every documented Erlang/OTP production
2473/// playbook recommendation (Learn You Some Erlang's
2474/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
2475/// `max_restarts: 3` default, OTP's `supervisor` callback module
2476/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
2477/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
2478/// default) and below the clearly-pathological "effectively no
2479/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
2480/// author can plausibly want at hyperscale (a long-running supervisor
2481/// over a very-flaky pool tolerating thousands of transient restarts
2482/// before escalating), but a hard wall above which the typed policy is
2483/// structurally a no-op carried verbatim on every emitted child-restart
2484/// reconciliation contract.
2485///
2486/// Lifted as a typed `pub const` so the bound has exactly one source of
2487/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2488/// materializer's admission webhook and the wasm-operator-side
2489/// per-supervisor restart-intensity reconciler read from one place. Same
2490/// shape every other typed upper bound in this crate carries
2491/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2492/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2493/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2494/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2495/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2496/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2497pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
2498
2499/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
2500/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
2501/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2502/// (inclusive on both ends, integer-millisecond magnitudes by the
2503/// canonical-form gate immediately preceding).
2504///
2505/// The typed field is `Option<Duration>` (the zero-floor arm
2506/// [`SupervisorError::RestartWindowZero`] already rejects
2507/// `Some(Duration::ZERO)`, and the canonical-form arm
2508/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
2509/// sub-millisecond residue), so a programmatic struct literal
2510/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
2511/// .. }` — 24h) and the equivalent author-surface form
2512/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
2513/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
2514/// cleanly through serde — a structurally unbounded `Duration` ceiling.
2515/// A `:restart-window` value far above the documented Erlang/OTP
2516/// `MaxIntensity / Period` production-playbook band (Learn You Some
2517/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
2518/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
2519/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
2520/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
2521/// degenerates the supervisor's restart-intensity counter into a
2522/// lifetime counter: the rolling failure-counting window is structurally
2523/// so long that transient restarts are never forgotten, so the
2524/// `MaxIntensity / Period` ratio degenerates from "trip the parent
2525/// supervisor when the child has exceeded its restart budget *within
2526/// the recent window*" to "trip the parent when the child has exceeded
2527/// its restart budget *over its lifetime*" — every transient restart
2528/// counts against the budget forever, the supervisor's reset semantic
2529/// never reaches the child, and the typed `:restart-window` slot
2530/// becomes a no-op rolling window carried on every emitted hierarchical
2531/// reconciliation contract. The canonical
2532/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
2533/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
2534/// `:politicas :circuit-breaker :window` axis with identical shape (both
2535/// are "rolling failure-counting window with a per-`Period` reset" Duration
2536/// axes whose lifetime-counter degenerate at the high end is the same
2537/// "the reset semantic never fires" CSE invariant violation).
2538///
2539/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
2540/// the shared duration codec emits (`"<n>h"` for any integer-hour
2541/// magnitude) — every value in the canonical authoring form's
2542/// `<integer><unit>` grammar at or below this cap renders to a clean
2543/// canonical string — and matches the three sibling typed-`Duration`
2544/// caps already lifted to this surface
2545/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2546/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
2547/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
2548/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
2549/// per-supervisor `:supervisor :restart-window` — now share a single
2550/// uniform top edge at the codec's largest emitted unit so the next
2551/// typed-slot wiring (the future wasm-operator's per-supervisor
2552/// `MaxIntensity / Period` reconciler, the M4
2553/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2554/// webhook, the `caixa-operator`'s hierarchical reconciliation
2555/// scheduler) reaches for any of the four knowing the value is in
2556/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
2557/// two orders of magnitude above every documented Erlang/OTP / Elixir /
2558/// Riak Core / RabbitMQ production-playbook recommendation band
2559/// (`5s..=300s`) and below the clearly-pathological "rolling window
2560/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
2561/// a value the author can plausibly want for a very-low-traffic
2562/// long-tail failure-restart window over a hyperscale-flaky child pool,
2563/// but a hard wall above which the rolling-window contract is
2564/// structurally a lifetime-counter contract.
2565///
2566/// Lifted as a typed `pub const` so the bound has exactly one source
2567/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2568/// materializer's admission webhook, the wasm-operator-side
2569/// per-supervisor `MaxIntensity / Period` reconciler, and the
2570/// `caixa-operator`'s hierarchical reconciliation scheduler all read
2571/// from one place. Same shape every other typed upper bound in this
2572/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
2573/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2574/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2575/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2576/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2577/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2578/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
2579/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2580/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2581pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
2582
2583/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
2584/// default for the `:supervisor :restart-window` axis — the canonical
2585/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
2586/// worker-supervisor default, extracted as a typed `pub const` so every
2587/// substrate-side consumer that resolves "what
2588/// [`SupervisorSpec::restart_window`] value does an author-omitted
2589/// `:restart-window` slot degrade onto?" reaches for exactly one
2590/// substrate-primitive [`Duration`].
2591///
2592/// The `:restart-window` default axis has one production consumer on the
2593/// substrate side today: the [`Default for SupervisorSpec`] impl's
2594/// struct-literal `restart_window` field, which prior to this lift folded
2595/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
2596/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
2597/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
2598/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
2599/// *not* fall back to this default on the sibling `:restart-window` axis
2600/// — an author-omitted `:supervisor :restart-window` composes to
2601/// `restart_window: None` (the shared codec's soft-swallow shape),
2602/// keeping author-declared intent ("no reset — never escalate on rolling
2603/// window") distinct from the [`Default for SupervisorSpec`] "canonical
2604/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
2605/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
2606/// default was split across two files with no compile-time link between
2607/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
2608/// `MaxIntensity` half at the substrate primitive while the `Period`
2609/// half rode as an open-coded literal at the composition site, so a
2610/// future coherent rebrand of the paired canonical (a tightening to
2611/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
2612/// per-cluster overlay the operator pins through a future
2613/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
2614/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2615/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
2616/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
2617/// roadmap lands) would have had to migrate the `MaxIntensity` half
2618/// through the lifted constant and the `Period` half through a raw
2619/// literal in lockstep or the two halves of the same OTP-canonical
2620/// default would silently drift out of pairing. Lifting the resolution
2621/// rule to a typed `pub const` on the substrate primitive means the
2622/// paired OTP-canonical default migrates as one unit on any future
2623/// axis change.
2624///
2625/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2626/// worker-supervisor default (the closest canonical OTP-shape
2627/// production reference the substrate carries, matching the paired
2628/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
2629/// constant is the `Period` denominator of on the same
2630/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
2631/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
2632/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
2633/// this lower default; both are typed [`Duration`] const bounds on the
2634/// `:supervisor :restart-window` axis and now share one accessor
2635/// discipline on the substrate) and above the OTP-`supervisor`
2636/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
2637/// rolling window" default is deliberately loose enough to absorb a
2638/// short burst of transient child failures without escalating past the
2639/// supervisor's parent while remaining tight enough for the paired
2640/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
2641/// stuck child within a human-scale observation window.
2642///
2643/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2644/// exactly one source of truth on each half — the sibling
2645/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
2646/// `Period` `60s` half now share the same substrate-primitive lift
2647/// discipline. Same shape every other typed default in this crate
2648/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
2649/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
2650/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
2651/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
2652/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
2653/// caixa-flux / caixa-helm rendering axes).
2654pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
2655
2656/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
2657/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
2658/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
2659/// worker-supervisor default, extracted as a typed `pub const` so every
2660/// substrate-side consumer that resolves "what
2661/// [`SupervisorSpec::estrategia`] variant does an author-omitted
2662/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
2663/// primitive [`RestartStrategy`].
2664///
2665/// The `:estrategia` default axis has three production consumers on the
2666/// substrate side today: the [`Default for RestartStrategy`] impl's
2667/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
2668/// `estrategia` field, and the
2669/// [`crate::manifest::Caixa::supervisor_view`] fold's
2670/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
2671/// collapse arm — three entry points onto the same OTP-canonical
2672/// `one_for_one` value that prior to this lift folded onto a raw
2673/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
2674/// implicit `RestartStrategy::default()` routes at the sibling consumers,
2675/// with no compile-time link back to the paired
2676/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
2677/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
2678/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
2679/// triple was split across three altitudes with no compile-time link
2680/// between the halves: the `MaxIntensity` half rode through the lifted
2681/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
2682/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2683/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
2684/// discriminator at the [`Default for RestartStrategy`] impl, so a future
2685/// coherent rebrand of the triple (Elixir's `{:one_for_one,
2686/// max_restarts: 3, max_seconds: 5}` — same strategy, different
2687/// intensity/period; an OTP `rest_for_one` widening once the substrate
2688/// discovers startup-order-coupled child cohorts as the more common
2689/// worker-supervisor default; a per-cluster overlay the operator pins
2690/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
2691/// §III.2 supervision-canary roadmap acknowledges) would have had to
2692/// migrate the `MaxIntensity` + `Period` halves through the lifted
2693/// constants and the `one_for_one` half through an open-coded arm in
2694/// lockstep or the three halves of the same OTP-canonical default would
2695/// silently drift out of pairing. Lifting the resolution rule to a typed
2696/// `pub const` on the substrate primitive means the paired OTP-canonical
2697/// worker-supervisor default migrates as one unit on any future axis
2698/// change.
2699///
2700/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
2701/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
2702/// closest canonical OTP-shape production reference the substrate
2703/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
2704/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2705/// `60s` `Period` half). The `one_for_one` strategy — restart only the
2706/// failed child, leaving siblings untouched — is the default for tree-of-
2707/// independent-workers use cases the substrate's [`RestartStrategy`]
2708/// discriminator's own docstring already carries as the default arm; it
2709/// composes with the `{5, 60}` restart-intensity ratio to name the same
2710/// substrate-canonical "canonical worker-supervisor" shape the paired
2711/// halves close on their respective axes.
2712///
2713/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2714/// exactly one source of truth on each of its three halves — the sibling
2715/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
2716/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
2717/// this `one_for_one` strategy half now share the same substrate-
2718/// primitive lift discipline. Same shape every other typed default in
2719/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
2720/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
2721/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
2722/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
2723/// upper caps on the paired sibling axes, and the peer
2724/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2725/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
2726pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
2727
2728/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
2729/// default for the `:children :restart` axis — the OTP `permanent`
2730/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
2731/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
2732/// `pub const` so every substrate-side consumer that resolves "what
2733/// [`ChildSpec::restart`] variant does an author-omitted `:children
2734/// :restart` slot degrade onto?" reaches for exactly one substrate-
2735/// primitive [`RestartPolicy`].
2736///
2737/// Completes the OTP-shape supervisor-tree default set at the substrate
2738/// primitive. The per-`:supervisor` axis already carries all three of its
2739/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2740/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
2741/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2742/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
2743/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
2744/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
2745/// the M2 `:supervisor` slot family. The split mattered because the two
2746/// axes resolve *together* on every author-omitted supervisor: a
2747/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
2748/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
2749/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
2750/// `permanent` through an open-coded enum arm, so a future coherent
2751/// rebrand of the OTP-shape default set (an Elixir-shaped
2752/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
2753/// per-cluster overlay the operator pins through the MESH-COMPOSITION
2754/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
2755/// once the substrate discovers clean-completion-aware children as the
2756/// more common child shape) would have had to migrate three halves
2757/// through typed constants and the fourth through a raw enum arm in
2758/// lockstep or the supervisor-level and child-level defaults would
2759/// silently drift apart.
2760///
2761/// The `:children :restart` default axis has two production consumers on
2762/// the substrate side today: the [`Default for RestartPolicy`] impl's
2763/// return arm, and the serde-side `#[serde(default)]` on
2764/// [`ChildSpec::restart`] that resolves an author-omitted `:children
2765/// :restart` slot through that same impl. Both now key off this one
2766/// substrate primitive, so the future wasm-operator's per-child post-exit
2767/// restart-decision branch, the future M4
2768/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2769/// admission webhook, and the `caixa-operator`'s hierarchical
2770/// reconciliation scheduler's per-child fan-out all reach for one typed
2771/// identifier when they resolve an omitted per-child restart posture.
2772///
2773/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
2774/// worker-child restart type — always restart the child regardless of how
2775/// it died, the canonical posture for long-running services that must
2776/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2777/// `one_for_one` tree-of-independent-workers strategy this constant pairs
2778/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
2779/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
2780/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
2781/// [`RestartPolicy::Temporary`] — never restart) express deliberate
2782/// one-shot / clean-completion-aware postures an author declares
2783/// explicitly, never a posture an omitted slot should silently assume.
2784pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
2785
2786/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
2787/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
2788/// `pub const fn` constructor rather than a struct-literal cascade over
2789/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
2790/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2791/// lifted consts — one source of truth for the Erlang/OTP-canonical
2792/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
2793/// paths every downstream consumer already reaches through (the
2794/// hand-authored-until-now [`Default::default`] the
2795/// `..SupervisorSpec::default()` struct-update-syntax on every
2796/// one-axis-under-test fixture in this crate's test module rests on,
2797/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
2798/// every `const`-context consumer reaches through).
2799///
2800/// Extends the [`Default`]-through-const-ctor fold discipline the
2801/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
2802/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
2803/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
2804/// and [`crate::BehaviorSpec`]
2805/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
2806/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
2807/// typed-slot spec family — extended here onto the M2 supervisor-slot
2808/// [`SupervisorSpec`] whose canonical baseline is not "everything
2809/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
2810/// supervisor triple. The `empty()` peer's naming did not fit
2811/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
2812/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
2813/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
2814/// the sibling `Option`-only slots fold to), so this peer is named
2815/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
2816/// existing per-arm pin tests
2817/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
2818/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
2819/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2820/// already reach for. Pinned load-bearing by
2821/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
2822/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
2823/// [`PartialEq`], sharpening the sibling
2824/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
2825/// pins from a per-field lift into a whole-struct one-source-of-truth
2826/// pin — the derived-until-now [`Default::default`] and the
2827/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
2828/// construction, not by coincidence).
2829impl Default for SupervisorSpec {
2830    #[inline]
2831    fn default() -> Self {
2832        Self::otp_canonical()
2833    }
2834}
2835
2836impl SupervisorSpec {
2837    /// `const`-context peer of the [`Default for SupervisorSpec`]
2838    /// impl (which routes through this constructor) — returns the
2839    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
2840    /// baseline this crate reaches for in every fixture-builder
2841    /// `..SupervisorSpec::default()` struct-update expression and
2842    /// every downstream `SupervisorSpec::default()` seed.
2843    ///
2844    /// Each field routes through the same substrate-canonical
2845    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
2846    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
2847    /// per-arm pin tests
2848    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
2849    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
2850    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2851    /// already assert, so a future coherent rebrand of the OTP-canonical
2852    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
2853    /// cluster overlay via a future `:restart-window-overrides` slot, a
2854    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
2855    /// absorption roadmap acknowledges) migrates through three typed
2856    /// constants in lockstep, and the paired [`Default`] impl inherits
2857    /// every future extension by construction.
2858    ///
2859    /// `pub const fn` rather than the derived-style `Default::default`
2860    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
2861    /// [`Default::default`] is not `const` on stable Rust, and
2862    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
2863    /// every consumer through a [`Clone::clone`]. The `pub const fn`
2864    /// discipline lets `const`-context callers construct the OTP-
2865    /// canonical baseline at compile time without runtime dispatch on
2866    /// the derived [`Default::default`], the same posture the sibling
2867    /// [`crate::LimitsSpec::empty`] (9739971) /
2868    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
2869    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
2870    /// spec `pub const fn` constructors carry on the sibling
2871    /// "everything `None`" baseline axis.
2872    ///
2873    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
2874    /// of the derived-style [`Default`]" family — sibling of the
2875    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
2876    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
2877    /// baseline" trio, extended here onto the M2 supervisor-slot
2878    /// [`SupervisorSpec`] whose canonical baseline is not "everything
2879    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
2880    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
2881    /// than `empty()` to name the actual invariant the return value
2882    /// pins — the same phrasing already used in the per-arm pin tests
2883    /// on this file. Pinned load-bearing by
2884    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
2885    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
2886    #[must_use]
2887    pub const fn otp_canonical() -> Self {
2888        Self {
2889            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
2890            max_restarts: default_max_restarts(),
2891            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2892            children: Vec::new(),
2893        }
2894    }
2895
2896    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
2897    /// sibling-restart-strategy scalar accessor every consumer that
2898    /// dispatches on the supervisor's per-sibling restart-decision shape
2899    /// keys off — returns the author-declared `:supervisor :estrategia`
2900    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
2901    /// the typed slot's own [`RestartStrategy`] storage.
2902    ///
2903    /// The `:supervisor :estrategia` slot carries the closed-set
2904    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
2905    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
2906    /// [`RestartStrategy::OneForAll`] — restart every child on any child
2907    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
2908    /// [`RestartStrategy::RestForOne`] — restart the failed child and
2909    /// every child started after it, the Erlang/OTP `rest_for_one`
2910    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
2911    /// dynamic children of the same shape, the Erlang/OTP
2912    /// `simple_one_for_one` per-session default) that every downstream
2913    /// consumer of the Supervisor's per-sibling restart-decision fan-out
2914    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
2915    /// paired coherently with the sibling `:children` axis
2916    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
2917    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
2918    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
2919    /// downstream consumer that reads the strategy keys off this scalar
2920    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2921    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
2922    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
2923    /// `estrategia:` field, the future `feira app graph` per-Supervisor
2924    /// strategy print line, the future wasm-operator's per-supervisor
2925    /// sibling-restart-strategy branch, the future M4
2926    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
2927    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
2928    /// reconciliation scheduler's per-strategy fan-out).
2929    ///
2930    /// Prior to this lift the `.estrategia` field was accessed inline at
2931    /// two production sites in `caixa-core/src/supervisor.rs` — the
2932    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2933    /// `match self.estrategia { … }` partition dispatch, and the
2934    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
2935    /// carrier at `estrategia: self.estrategia` — two open-coded
2936    /// field-accesses that expressed no compile-time link back to the
2937    /// typed slot. A future extension of the `:supervisor :estrategia`
2938    /// axis to a richer author surface (a per-cluster strategy override
2939    /// the operator pins through a future `:supervisor :estrategia-overrides`
2940    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2941    /// acknowledges, a per-tenant strategy-alias table the M4 CR
2942    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
2943    /// derivation the future adaptive-supervision engine computes from
2944    /// child-failure-history topology, a per-child-cohort strategy split
2945    /// the future `RestForCohort` extension acknowledged by the
2946    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
2947    /// would have had to be threaded through every open-coded copy in
2948    /// lockstep — one consumer reading the raw variant while a peer read
2949    /// the operator-resolved variant would silently split the
2950    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
2951    /// the actual partition-dispatch input the empty-children refusal
2952    /// arm reached under, a two-consumer split at the validator far from
2953    /// the source `caixa.lisp` with no field naming the strategy-drift
2954    /// root cause. Lifting the resolution rule to a typed method on the
2955    /// substrate primitive means every downstream consumer of the
2956    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
2957    /// reaches for exactly one typed dispatch — the resolver's accept-set
2958    /// migrates as a unit on any future axis addition.
2959    ///
2960    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
2961    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
2962    /// per-`:placement` distribution-strategy axis — same "one typed
2963    /// dispatch on the substrate primitive, thin projections at each
2964    /// consumer" discipline extended onto the M2 supervisor-slot
2965    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
2966    /// scalar axis. The two typed axes (`Placement::estrategia` on the
2967    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
2968    /// Supervisor side) now share one accessor discipline for the shared
2969    /// substrate concept "a `Copy`-projected closed-set enum-arm
2970    /// discriminator that partitions the downstream renderer's per-arm
2971    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
2972    /// `SupervisorSpec` type — companion to the sibling per-`:children`
2973    /// [`crate::ChildSpec::nome`] (57c61d0) /
2974    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2975    /// scalar accessors on the sibling per-`:children` `String`-carry
2976    /// axes. Named `estrategia()` to match the storage field's name and
2977    /// the peer [`crate::Placement::estrategia`] method-name discipline
2978    /// verbatim; the accessor's identity name maps onto the canonical
2979    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
2980    /// docstring already carries.
2981    ///
2982    /// Declared `pub const fn` to close the M2 supervisor-slot
2983    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
2984    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
2985    /// (converted in this commit) `Copy`-composite-enum accessor, peer
2986    /// of the sibling M2 per-`:supervisor`
2987    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2988    /// already lifted, and mirror of the peer M3 mesh-slot
2989    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
2990    /// `Copy`-return `pub const fn` scalar accessor whose method-name
2991    /// discipline this accessor was authored to match. Every downstream
2992    /// substrate-side `const`-context consumer of the per-`:supervisor`
2993    /// sibling-restart-strategy scalar (a future module-scope `const
2994    /// _:() = assert!(matches!(sup.estrategia(),
2995    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
2996    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2997    /// admission-webhook `const fn` per-supervisor strategy-arm floor
2998    /// over a typed [`SupervisorSpec`], any future `const fn`
2999    /// supervisor-tree composer over the substrate primitive that fans
3000    /// on the sibling-restart-strategy at compile time) now reaches
3001    /// through the same typed dispatch on the substrate primitive at
3002    /// const-eval time as at runtime. A future non-`Copy`-return
3003    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
3004    /// migration once the substrate grows per-cluster strategy overlays
3005    /// the [`SupervisorSpec`] docstring already anticipates, a
3006    /// per-tenant strategy-alias table the M4 CR materializer resolves
3007    /// per-CR) that would drop the `const` qualifier fails the
3008    /// fail-before-pass-after pin
3009    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
3010    /// caixa-core build time rather than surfacing as a downstream
3011    /// consumer regression.
3012    #[must_use]
3013    pub const fn estrategia(&self) -> RestartStrategy {
3014        self.estrategia
3015    }
3016
3017    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
3018    /// `MaxIntensity` restart-budget scalar accessor every consumer that
3019    /// reads the supervisor's per-`:restart-window` restart-budget count
3020    /// keys off — returns the author-declared `:supervisor :max-restarts`
3021    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
3022    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
3023    /// borrow of `&self` past the call). Non-optional (the `u32` field
3024    /// carries the restart-budget count as a required axis with a
3025    /// [`default_max_restarts`]-supplied default; the zero-floor arm
3026    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
3027    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
3028    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
3029    ///
3030    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
3031    /// `MaxIntensity` restart-budget count that pairs with the sibling
3032    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
3033    /// restart-intensity ratio the supervisor trips its own escalation on
3034    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
3035    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
3036    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
3037    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
3038    /// upper-cap bracket at
3039    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
3040    /// wasm-operator's per-supervisor restart-intensity counter's
3041    /// budget-vs-count comparator, the future M4
3042    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3043    /// webhook, the `caixa-operator`'s hierarchical reconciliation
3044    /// scheduler's per-supervisor escalation-decision branch, every
3045    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
3046    /// offending count verbatim for `feira lint` rendering).
3047    ///
3048    /// Prior to this lift the `.max_restarts` field was accessed inline at
3049    /// one production site in `caixa-core/src/supervisor.rs` — the
3050    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
3051    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
3052    /// that expressed no compile-time link back to the typed slot. A
3053    /// future extension of the `:max-restarts` axis to a richer author
3054    /// surface (a per-cluster restart-budget override the operator pins
3055    /// through a future `:supervisor :max-restarts-overrides` slot the
3056    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
3057    /// a per-tenant restart-budget-alias table the M4 CR materializer
3058    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
3059    /// the future adaptive-supervision engine computes from child-failure-
3060    /// history topology, a promotion of the plain `u32` count to a richer
3061    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
3062    /// budget-partition slot comes into scope) would have had to be
3063    /// threaded through every open-coded copy in lockstep or the validate
3064    /// gate and the future M4 emit path would silently disagree on which
3065    /// restart-budget count a given supervisor resolves to — an author's
3066    /// `:max-restarts 5` would satisfy validate while the emit path
3067    /// silently read a drifted other value (a `:max-restarts 10000`
3068    /// no-op supervisor at the emit boundary would carry the author's
3069    /// declared `5` verbatim in `feira lint` output while the future
3070    /// wasm-operator's restart-intensity counter operated under the
3071    /// drifted count), a two-consumer split at the validator far from the
3072    /// source `caixa.lisp` with no field naming the restart-budget-drift
3073    /// root cause. Lifting the resolution rule to a typed method on the
3074    /// substrate primitive means every downstream consumer of the
3075    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
3076    /// for exactly one typed dispatch — the resolver's accept-set migrates
3077    /// as a unit on any future axis addition.
3078    ///
3079    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
3080    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
3081    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
3082    /// outlier-detection trip-threshold axis — same "one typed dispatch on
3083    /// the substrate primitive, thin projections at each consumer"
3084    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
3085    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
3086    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
3087    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
3088    /// one accessor discipline for the shared substrate concept "a
3089    /// `Copy`-projected required `u32` count that trips the next-higher
3090    /// protection layer after N events in a rolling window" — both are
3091    /// counters with identical degenerate-at-the-high-end shape and share
3092    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
3093    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
3094    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
3095    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
3096    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
3097    /// the storage field's name verbatim and the peer
3098    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
3099    /// accessor's identity maps onto the canonical OTP-shape supervision
3100    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
3101    /// already carries.
3102    #[must_use]
3103    pub const fn max_restarts(&self) -> u32 {
3104        self.max_restarts
3105    }
3106
3107    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
3108    /// `Period` sliding-window scalar accessor every consumer of the
3109    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
3110    /// keys off — returns the author-declared `:supervisor :restart-window`
3111    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
3112    /// the typed slot's own `Option<Duration>` storage (`Duration` is
3113    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
3114    /// value; no borrow of `&self` past the call). `None` when the slot is
3115    /// absent (the canonical "never reset — every restart across the
3116    /// supervisor's lifetime counts against the sibling `:max-restarts`
3117    /// budget" sentinel the field's own docstring names and the peer
3118    /// `validate_accepts_none_restart_window` pin locks in on the
3119    /// [`SupervisorSpec::validate`] entry-side).
3120    ///
3121    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
3122    /// `Period` sliding-observation-interval that pairs with the sibling
3123    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
3124    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
3125    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
3126    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
3127    /// default). The typed slot's `Option<Duration>` accept-set —
3128    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
3129    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
3130    /// `Period > 0`; a zero period either trips on the first failure or
3131    /// never trips depending on operator interpretation, neither of which
3132    /// is the author's intent — omit the slot to express "no reset";
3133    /// carry a positive duration to express the sliding window),
3134    /// integer-millisecond canonical form enforced through
3135    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
3136    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
3137    /// future wasm-operator's per-supervisor restart-intensity counter
3138    /// quantizes at milliseconds), upper-bounded by
3139    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
3140    /// supervisor rolling window any operationally-reachable supervisor
3141    /// can honor without spanning multiple scheduler epochs the
3142    /// hierarchical-reconciliation scheduler treats as independent) —
3143    /// maps onto the future wasm-operator (M3) per-supervisor
3144    /// restart-intensity counter's rolling-observation-interval, the
3145    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3146    /// per-`spec.restartWindow` admission webhook, and the sibling
3147    /// `duration_codec`-serialized wire scalar every downstream consumer
3148    /// of the supervisor's per-`:supervisor` restart-intensity denominator
3149    /// keys off.
3150    ///
3151    /// Prior to this lift the `.restart_window` field was accessed inline
3152    /// at one production site in `caixa-core/src/supervisor.rs` — the
3153    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
3154    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
3155    /// open-coded field-access that expressed no compile-time link back to
3156    /// the typed slot. A future extension of the `:restart-window` axis to
3157    /// a richer author surface (a per-cluster restart-window override the
3158    /// operator pins through a future `:supervisor :restart-window-overrides`
3159    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3160    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
3161    /// materializer resolves per-CR, a per-supervisor dynamic
3162    /// restart-window derivation the future adaptive-supervision engine
3163    /// computes from child-failure-history topology, a promotion of the
3164    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
3165    /// pair once Erlang/OTP's per-child-cohort observation-interval-
3166    /// partition slot comes into scope) would have had to be threaded
3167    /// through every open-coded copy in lockstep or the validate gate and
3168    /// the future M4 emit path would silently disagree on which
3169    /// restart-window a given supervisor resolves to — an author's
3170    /// `:restart-window "60s"` would satisfy validate while the emit path
3171    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
3172    /// authored slot at the emit boundary would carry the author's
3173    /// declared window verbatim in `feira lint` output while the future
3174    /// wasm-operator's restart-intensity counter operated under a
3175    /// drifted window, or vice versa: an author's `:restart-window ()`
3176    /// would carry the "never reset" sentinel through validate while the
3177    /// emit path silently substituted a default sliding window), a
3178    /// two-consumer split at the validator far from the source
3179    /// `caixa.lisp` with no field naming the restart-window-drift root
3180    /// cause. Lifting the resolution rule to a typed method on the
3181    /// substrate primitive means every downstream consumer of the
3182    /// Supervisor's per-`:supervisor` restart-intensity-denominator
3183    /// surface reaches for exactly one typed dispatch — the resolver's
3184    /// accept-set migrates as a unit on any future axis addition.
3185    ///
3186    /// Third `Copy`-return accessor on the M2 supervisor-slot
3187    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
3188    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
3189    /// payload rather than a `Copy`-scalar, and the per-`:children`
3190    /// [`crate::ChildSpec::nome`] (57c61d0) /
3191    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3192    /// scalar accessors already close the per-element `String`-carry
3193    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
3194    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
3195    /// per-outermost-call wall-clock-deadline axis and the peer M3
3196    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
3197    /// accessor on the `:politicas` slot's per-call-deadline axis — all
3198    /// three share the shared substrate concept "a `Copy`-projected
3199    /// optional `Duration` that carries a positive integer-millisecond
3200    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
3201    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
3202    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
3203    /// bracket-helper the three axes each route through. Named
3204    /// `restart_window()` to match the storage field's name verbatim and
3205    /// the peer [`crate::LimitsSpec::wall_clock`] /
3206    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
3207    /// accessor's identity maps onto the canonical OTP-shape supervision
3208    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
3209    /// already carries.
3210    #[must_use]
3211    pub const fn restart_window(&self) -> Option<Duration> {
3212        self.restart_window
3213    }
3214
3215    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
3216    /// static-child-list slice accessor every consumer that walks the
3217    /// supervisor's declared child set keys off — returns the author-
3218    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
3219    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
3220    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
3221    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
3222    /// through). Non-optional: an empty slice is the load-bearing
3223    /// "author declared `:children ()`" sentinel every consumer of the
3224    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
3225    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
3226    /// three strategies require a non-empty slice — the paired
3227    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
3228    /// [`SupervisorError::NoChildren`] refusal cascade pins the
3229    /// partition on both arms).
3230    ///
3231    /// The `:supervisor :children` slot carries the OTP-shaped static
3232    /// child list the supervisor materializes one ComputeUnit per
3233    /// entry from — the Erlang/OTP `supervisor:init/1`'s
3234    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
3235    /// through the tatara-lisp `:children` author surface onto a typed
3236    /// `Vec<ChildSpec>` whose per-element `(nome(),
3237    /// versao_requirement(), restart)` triple the per-child
3238    /// [`SupervisorSpec::validate`] loop already gates through the
3239    /// lifted [`ChildSpec::nome`] (57c61d0) /
3240    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
3241    /// Every downstream consumer that fans on the static child list
3242    /// keys off this slice (the [`SupervisorSpec::validate`]
3243    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
3244    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
3245    /// per-child DNS-1123 / semver-requirement / duplicate-detection
3246    /// fan-out loop, every future wasm-operator (M3) per-supervisor
3247    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
3248    /// materialization loop, the future M4
3249    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3250    /// admission-webhook fan-out, the future `feira app graph`
3251    /// per-supervisor tree-print traversal).
3252    ///
3253    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
3254    /// inline at three production sites in `caixa-core/src/supervisor.rs`
3255    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
3256    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
3257    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
3258    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
3259    /// validate loop's `for child in &self.children` traversal head —
3260    /// three open-coded field-accesses that expressed no compile-time
3261    /// link back to the typed slot. A future extension of the
3262    /// `:supervisor :children` axis to a richer author surface (a
3263    /// per-cluster child-set overlay the operator pins through a future
3264    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
3265    /// supervision-canary roadmap acknowledges, a per-tenant
3266    /// child-set-alias table the M4 CR materializer resolves per-CR,
3267    /// a per-supervisor dynamic-child derivation the future adaptive-
3268    /// supervision engine computes from child-failure-history topology,
3269    /// a promotion of the plain `Vec<ChildSpec>` to a richer
3270    /// `{static, dynamic}` partition once Erlang/OTP's
3271    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
3272    /// would have had to be threaded through all three open-coded copies
3273    /// in lockstep or one consumer would silently disagree with the
3274    /// peers on which child-set a given supervisor resolves to — the
3275    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
3276    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
3277    /// would silently split the partition-dispatch's two-arm coherence
3278    /// (a supervisor that satisfies neither arm's precondition, or that
3279    /// satisfies both, at the cost of the paired
3280    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
3281    /// silently drifting from the per-child validate loop's actual
3282    /// traversal input), a three-consumer split at the validator far
3283    /// from the source `caixa.lisp` with no field naming the
3284    /// child-set-drift root cause. Lifting the resolution rule to a
3285    /// typed method on the substrate primitive means every downstream
3286    /// consumer of the Supervisor's per-`:supervisor` static-child-list
3287    /// surface reaches for exactly one typed dispatch — the resolver's
3288    /// accept-set migrates as a unit on any future axis addition.
3289    ///
3290    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
3291    /// — the seed for the same "one typed dispatch on the substrate
3292    /// primitive, thin projections at each consumer" discipline the
3293    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
3294    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
3295    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
3296    /// onto the first `Vec`-carry axis on the substrate. The four peer
3297    /// `Vec`-carry axes still unlifted at the time of this seed —
3298    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
3299    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
3300    /// (`Vec<Membro>` per-Aplicacao member list),
3301    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
3302    /// per-Aplicacao WIT-typed edge list),
3303    /// [`crate::UpgradeFromEntry::instructions`]
3304    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
3305    /// — inherit this accessor's discipline as future compounding runs
3306    /// migrate their consumers onto the shared slice-return shape.
3307    /// Fourth (and final) accessor on the M2 supervisor-slot
3308    /// `SupervisorSpec` type, sibling to the three `Copy`-return
3309    /// [`SupervisorSpec::estrategia`] (eafb619) /
3310    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
3311    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
3312    /// the last unlifted per-`:supervisor` field axis (the
3313    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
3314    /// per-`:supervisor` reader now routes through a typed dispatch on
3315    /// the substrate primitive. Named `children()` to match the storage
3316    /// field's name verbatim and the tatara-lisp author-surface term
3317    /// (`:children`) the field's own docstring already carries; the
3318    /// accessor's identity maps onto the canonical OTP-shape
3319    /// supervision vocabulary the [`SupervisorSpec::children`] field's
3320    /// docstring already reaches for ("Static children ..."). Returns
3321    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
3322    /// consumer of the child list treats it as a read-only sequence —
3323    /// the slice-view is the narrowest borrow that supports every
3324    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
3325    /// index, `.len()`) without leaking the backing `Vec`'s
3326    /// grow/push/reserve surface that no consumer of the typed view
3327    /// reaches for (the storage-side `Vec` remains reachable through
3328    /// the `pub children` field for the mutation-carrying
3329    /// `Caixa::supervisor_view` fold-in path in
3330    /// `manifest.rs:supervisor_view`).
3331    #[must_use]
3332    pub const fn children(&self) -> &[ChildSpec] {
3333        self.children.as_slice()
3334    }
3335
3336    /// Validate the supervisor's typed shape — strategy ↔ children
3337    /// invariants, max_restarts > 0, restart_window > 0 when set,
3338    /// per-child non-empty + duplicate-free names.
3339    ///
3340    /// Mirrors the value-shape discipline applied to every other
3341    /// typed slot:
3342    ///
3343    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
3344    ///     same "0 means the opposite of what you think" footgun
3345    ///     closed for `:politicas :timeout` (Envoy interprets a zero
3346    ///     timeout as `infinite`), `:politicas :circuit-breaker
3347    ///     :window`, and `:limits :wall-clock`. The
3348    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
3349    ///     `supervisor` requires `Period > 0`; a zero period either
3350    ///     trips on the first failure or never trips depending on
3351    ///     operator interpretation, neither of which is the
3352    ///     author's intent. Omit `:restart-window` to express "no
3353    ///     reset"; carry a positive duration to express the window.
3354    ///   - duplicate `:children` `:caixa` names are the same
3355    ///     graph-node-set / multiset distinction closed for
3356    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
3357    ///     and `:entrada :paths` (eb3456d). Two children with the
3358    ///     same `:caixa` materialize as two ComputeUnits with the
3359    ///     same name in the cluster's HelmRelease values, one
3360    ///     silently overwriting the other. Erlang/OTP's
3361    ///     `child_spec.id` is required-unique per supervisor;
3362    ///     pleme-io enforces the same set-not-multiset shape on
3363    ///     `:caixa` (the load-bearing identity in our renderer).
3364    pub fn validate(&self) -> Result<(), SupervisorError> {
3365        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
3366        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3367        // error carrier's `estrategia:` field through the lifted
3368        // [`SupervisorSpec::estrategia`] accessor rather than the raw
3369        // `self.estrategia` field access — the two production consumers
3370        // of the per-`:supervisor` sibling-restart-strategy scalar now
3371        // key off exactly one typed dispatch on the substrate primitive,
3372        // so any future rebrand on the axis (a per-cluster strategy
3373        // override the operator pins through a future `:supervisor
3374        // :estrategia-overrides` slot, a per-tenant strategy-alias table
3375        // the M4 CR materializer resolves per-CR) migrates as a single
3376        // caixa-core edit rather than a coordinated rewrite of the two
3377        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
3378        // (921fe1b) four-consumer migration on the per-`:placement`
3379        // distribution-strategy axis.
3380        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
3381        // dispatch's paired `.is_empty()` cross-slot refusal probes
3382        // (the `SimpleOneForOne`-arm
3383        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
3384        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3385        // refusal) through the lifted [`SupervisorSpec::children`]
3386        // slice-return accessor rather than the raw `self.children`
3387        // field access — the two paired production consumers of the
3388        // per-`:supervisor` static-child-list scalar-shape now key off
3389        // exactly one typed dispatch on the substrate primitive, so any
3390        // future rebrand on the axis (a per-cluster child-set overlay
3391        // the operator pins through a future `:supervisor
3392        // :children-overrides` slot, a per-tenant child-set-alias table
3393        // the M4 CR materializer resolves per-CR) migrates as a single
3394        // caixa-core edit rather than a coordinated rewrite of the
3395        // paired arms — first slice-return migration on any typed slot,
3396        // seed for the peer per-`:placement :clusters`,
3397        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
3398        // :instructions` `Vec`-carry axes.
3399        match self.estrategia() {
3400            RestartStrategy::SimpleOneForOne => {
3401                // SimpleOneForOne: children added at runtime. Static
3402                // list must be empty (one shape declared elsewhere).
3403                if !self.children().is_empty() {
3404                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
3405                }
3406            }
3407            _ => {
3408                if self.children().is_empty() {
3409                    return Err(SupervisorError::no_children(self.estrategia()));
3410                }
3411            }
3412        }
3413        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
3414        // axis. See [`crate::render::require_positive_bounded_u32`] for
3415        // the ordering discipline (zero-floor arm strictly precedes cap
3416        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
3417        // diagnostic with its counter-axis remediation directly named,
3418        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
3419        // cap-arm miss). Until this bracket landed the top edge ran all
3420        // the way to `u32::MAX` and a struct-literal
3421        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
3422        // equivalent author-surface `:max-restarts 100000` /
3423        // `:max-restarts 4294967295` typo landing in the slot) silently
3424        // passed validate. The runtime substrate consuming the value
3425        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
3426        // wasm-operator's per-supervisor restart-intensity counter, the
3427        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3428        // admission webhook) then turned a typed `:max-restarts`
3429        // policy into a no-op supervisor: the escalation threshold is
3430        // structurally so high that no realistic
3431        // restarts-per-`:restart-window` traffic shape can reach it,
3432        // the supervisor never escalates to its parent, and a bad
3433        // child can loop inside the window indefinitely with the
3434        // parent supervisor structurally never receiving the "this
3435        // subtree has exceeded its restart budget" signal the typed
3436        // slot is meant to express. The bracket set is
3437        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
3438        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
3439        // the sibling `:politicas :circuit-breaker :max-failures` axis:
3440        // both are "trip the next-higher protection layer after N
3441        // events in a rolling window" counters with identical
3442        // degenerate-at-the-high-end shape and now share one canonical
3443        // bracket helper. The bracket precedes the sibling
3444        // `:restart-window` zero-floor / canonical-millisecond arms so
3445        // an over-cap `max_restarts` paired with a structurally invalid
3446        // window surfaces the bracket diagnostic first, mirroring the
3447        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
3448        // ordering on the peer `:politicas :circuit-breaker` slot.
3449        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
3450        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
3451        // accessor rather than the raw `self.max_restarts` field access —
3452        // the one production consumer of the per-`:supervisor`
3453        // restart-budget-count scalar now keys off exactly one typed
3454        // dispatch on the substrate primitive, so any future rebrand on
3455        // the axis (a per-cluster restart-budget override the operator
3456        // pins through a future `:supervisor :max-restarts-overrides`
3457        // slot, a per-tenant restart-budget-alias table the M4 CR
3458        // materializer resolves per-CR) migrates as a single caixa-core
3459        // edit rather than a coordinated rewrite — sibling of the peer M3
3460        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
3461        // the per-`:politicas :circuit-breaker :max-failures` axis.
3462        crate::render::require_positive_bounded_u32(
3463            self.max_restarts(),
3464            SUPERVISOR_MAX_RESTARTS_MAX,
3465            || SupervisorError::ZeroMaxRestarts,
3466            SupervisorError::max_restarts_exceeds_cap,
3467        )?;
3468        // Route the [`SupervisorSpec::validate`] `:restart-window`
3469        // zero-floor + integer-millisecond canonical-form + upper-cap
3470        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
3471        // accessor rather than the raw `self.restart_window` field access —
3472        // the one production consumer of the per-`:supervisor`
3473        // restart-intensity-denominator scalar now keys off exactly one
3474        // typed dispatch on the substrate primitive, so any future rebrand
3475        // on the axis (a per-cluster restart-window override the operator
3476        // pins through a future `:supervisor :restart-window-overrides`
3477        // slot, a per-tenant restart-window-alias table the M4 CR
3478        // materializer resolves per-CR) migrates as a single caixa-core
3479        // edit rather than a coordinated rewrite — sibling of the peer M2
3480        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
3481        // on the per-`:limits :wall-clock` axis and the peer M3
3482        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
3483        // per-`:politicas :timeout` axis.
3484        if let Some(w) = self.restart_window() {
3485            // Zero-floor + integer-millisecond canonical-form +
3486            // upper-cap bracket on the typed `:restart-window` axis.
3487            // See
3488            // [`crate::render::require_positive_canonical_bounded_duration`]
3489            // for the full three-arm ordering discipline (zero-floor
3490            // strictly precedes canonical-form so `Duration::ZERO`
3491            // surfaces the self-locating `RestartWindowZero`
3492            // diagnostic; canonical-form strictly precedes the cap arm
3493            // so a sub-millisecond above-cap value surfaces the more
3494            // fundamental round-trip-shape diagnostic first) and the
3495            // three peer typed-`Duration` sites that share this
3496            // canonical bracket ([`crate::MeshPolicy::timeout`],
3497            // [`crate::CircuitBreaker::window`],
3498            // [`crate::LimitsSpec::wall_clock`]). Every validated
3499            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3500            // (1ms..=1h), integer-millisecond granularity.
3501            crate::render::require_positive_canonical_bounded_duration(
3502                w,
3503                SUPERVISOR_RESTART_WINDOW_MAX,
3504                || SupervisorError::RestartWindowZero,
3505                SupervisorError::restart_window_not_canonical,
3506                SupervisorError::restart_window_exceeds_cap,
3507            )?;
3508        }
3509        // Route the per-child DNS-1123 / semver-requirement / duplicate-
3510        // detection fan-out loop through the lifted named per-slot gate
3511        // [`SupervisorSpec::validate_children`] rather than an inline
3512        // three-per-child cascade — every future consumer that wants to
3513        // re-check only the `:children` slot's per-entry axes (the M4
3514        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3515        // admission webhook re-validating one added/renamed child, the
3516        // future wasm-operator's per-child dynamic-add re-validator on
3517        // the `SimpleOneForOne` runtime-add path once dynamic-children
3518        // graduate to a typed slot, a future partial re-validator on a
3519        // per-`:children`-entry patch) reaches every per-entry axis
3520        // through one dispatch rather than re-inlining the three-arm
3521        // cascade in lockstep with `validate` or paying the peer
3522        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
3523        // reach one entry check. Sibling of the peer M3 mesh-slot
3524        // per-slot gate family (`validate_membros` — the exact peer on
3525        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
3526        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
3527        // `validate_placement`; `validate_politicas` routing through
3528        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
3529        // per-slot gate discipline now spans both the M3 mesh-slot
3530        // family and the M2 `:children` per-child-cascade axis on one
3531        // shape: one named per-slot gate per typed per-entry loop.
3532        self.validate_children()?;
3533        Ok(())
3534    }
3535
3536    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
3537    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
3538    /// gate, and duplicate-`:caixa` dedup arm into one call every
3539    /// consumer that wants to re-validate one `:children` entry (or the
3540    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
3541    /// admits reaches through.
3542    ///
3543    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
3544    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
3545    /// three-per-entry shape (DNS-1123 name + semver-requirement +
3546    /// duplicate-`:caixa` dedup), lifted to one named substrate
3547    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3548    /// materializer's admission webhook re-checking one added or renamed
3549    /// child, the future wasm-operator's per-child dynamic-add
3550    /// re-validator on the `SimpleOneForOne` runtime-add path once
3551    /// dynamic-children graduate to a typed slot, a future partial
3552    /// re-validator on a per-`:children`-entry patch — each reaches the
3553    /// three per-entry axes through this one dispatch rather than
3554    /// re-inlining the three-arm cascade in lockstep with `validate`
3555    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
3556    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
3557    /// reach one entry check.
3558    ///
3559    /// Self-contained on `&self` — resolves its own dedup `HashSet`
3560    /// through [`SupervisorSpec::children`] rather than borrowing one
3561    /// threaded down from `validate`, the same posture the peer M3
3562    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
3563    /// [`crate::AplicacaoSpec::validate_contratos`],
3564    /// [`crate::AplicacaoSpec::validate_entrada`],
3565    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
3566    /// consumer that reaches this gate directly (without first calling
3567    /// `validate`) still runs the full per-child cascade — pinned by
3568    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3569    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3570    /// + `validate_children_is_self_contained_on_children_slot`.
3571    ///
3572    /// The three per-entry arms run in the same canonical order the
3573    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
3574    /// the diagnostic every author-declared per-`:children` entry surfaces
3575    /// through `validate` is byte-equal to the diagnostic this gate
3576    /// surfaces when called directly — the equivalence-pin pair
3577    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3578    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3579    /// asserts the two altitudes discriminate the same set on every
3580    /// per-entry-covered input.
3581    pub fn validate_children(&self) -> Result<(), SupervisorError> {
3582        let mut seen = std::collections::HashSet::new();
3583        for child in self.children() {
3584            // Every emitted cluster artifact's `metadata.name` for a
3585            // supervised child derives from this `:children :caixa` value
3586            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
3587            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
3588            // label value on every child's pod identity, and the per-
3589            // child K8s [`Service`][svc] `metadata.name` the future
3590            // wasm-operator (M3) provisions for inter-child supervision
3591            // tree wiring. Each apiserver-side schema on each landing
3592            // site enforces the DNS-1123 label rule on admission; a
3593            // structurally invalid child name (`"Worker"`, `"my_worker"`,
3594            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
3595            // UUID-shaped mistaken-identity slug) silently passes the
3596            // prior empty-/duplicate-only gate and the failure surfaces
3597            // at `kubectl apply` time as a `metadata.name: Invalid value`
3598            // rejection, far from the source caixa.lisp, with no field
3599            // naming the offending `:children` entry. Lifting the gate
3600            // to caixa-build time mirrors the `:membros :caixa` value-
3601            // shape trajectory (3f9d7a0) and the `:placement :clusters`
3602            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
3603            // identifier axis — the supervisor tree's child names —
3604            // through the lifted
3605            // [`crate::render::require_valid_dns_1123_label`] gate the
3606            // seven peer name axes (`:membros :caixa`, `:placement
3607            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
3608            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
3609            // route through, so drift between the eight axes' accepted
3610            // DNS-1123-label sets is structurally impossible.
3611            //
3612            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
3613            crate::render::require_valid_dns_1123_label(
3614                child.nome(),
3615                || SupervisorError::EmptyChildName,
3616                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
3617            )?;
3618            // The author surface for `:children :versao` is the same
3619            // Cargo-shaped semver requirement string `:deps :versao` and
3620            // `:membros :versao` carry — and the lacre pipeline resolves
3621            // all three axes through the same
3622            // [`crate::version::parse_requirement`] entry-point. The
3623            // shared [`crate::render::require_valid_versao_requirement`]
3624            // helper brackets the empty-first + parse cascade both peer
3625            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
3626            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
3627            // :versao`) route through, so drift between the three axes'
3628            // accepted requirement sets is structurally impossible and
3629            // the parse-side no-op the empty-first arm closes (semver's
3630            // empty parse yields an implicit `*`) lives in exactly one
3631            // predicate. Every `ChildSpec::versao` past validate is
3632            // round-trippable through [`crate::parse_requirement`]
3633            // without re-checking at the resolver layer, and the three
3634            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
3635            // are now structurally equivalent by construction.
3636            crate::render::require_valid_versao_requirement(
3637                child.versao_requirement(),
3638                || SupervisorError::empty_child_version(child.nome()),
3639                |reason| {
3640                    SupervisorError::child_versao_invalid(
3641                        child.nome(),
3642                        child.versao_requirement(),
3643                        reason,
3644                    )
3645                },
3646            )?;
3647            crate::render::insert_first_seen(&mut seen, child.nome(), || {
3648                SupervisorError::duplicate_child_caixa(child.nome())
3649            })?;
3650        }
3651        Ok(())
3652    }
3653}
3654
3655/// Cross-slot coherence gate on the supervision tree: no
3656/// `:children :caixa` entry may name the supervisor's own `:nome`.
3657///
3658/// A supervisor that lists itself as a child is a degenerate self-parent
3659/// — the supervision tree is a DAG rooted at the supervisor (OTP child
3660/// specs reference *distinct* child processes; a supervisor is never its
3661/// own child), and the wasm-operator's hierarchical reconciliation would
3662/// otherwise be handed a node that is its own parent: a one-node cycle it
3663/// either rejects far from the source `caixa.lisp` or recurses on. Because
3664/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
3665/// lacre closure root), a child whose `:caixa` equals the supervisor's
3666/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
3667///
3668/// Lives outside [`SupervisorSpec::validate`] because the typed view
3669/// carries the children but not the parent `:nome`; mirrors the
3670/// cross-slot precedence gate `validate_upgrade_from_against_versao`
3671/// (which likewise reads one slot against another at the
3672/// [`crate::layout`] wire-up site) and the mesh self-edge gate
3673/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
3674/// node to itself is structurally not a tree/mesh edge" discipline, here
3675/// on the supervision-tree axis.
3676pub fn validate_no_self_supervision(
3677    children: &[ChildSpec],
3678    parent_nome: &str,
3679) -> Result<(), SupervisorError> {
3680    for child in children {
3681        if child.nome() == parent_nome {
3682            return Err(SupervisorError::child_supervises_self(parent_nome));
3683        }
3684    }
3685    Ok(())
3686}
3687
3688#[derive(Debug, Error, PartialEq, Eq)]
3689pub enum SupervisorError {
3690    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
3691    NoChildren { estrategia: RestartStrategy },
3692    #[error(
3693        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
3694    )]
3695    SimpleOneForOneWithStaticChildren,
3696    #[error(":max-restarts must be > 0")]
3697    ZeroMaxRestarts,
3698    #[error(
3699        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
3700         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
3701         restart-intensity policy into a no-op supervisor: the escalation threshold is \
3702         structurally so high that no realistic restarts-per-:restart-window traffic shape \
3703         can reach it, so the supervisor never escalates to its parent and a bad child can \
3704         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
3705         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
3706         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3707         materializer's admission webhook) emits a `:max-restarts` declaration that is \
3708         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
3709         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
3710         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
3711         band) or restructure the supervision tree (split the flaky child into its own \
3712         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
3713    )]
3714    MaxRestartsExceedsCap { max_restarts: u32 },
3715    #[error(
3716        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
3717         requires Period > 0; a zero window either trips on the first failure or \
3718         never trips depending on operator interpretation. Omit :restart-window to \
3719         express `never reset`; carry a positive duration to express the window."
3720    )]
3721    RestartWindowZero,
3722    #[error(
3723        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
3724         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
3725         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
3726         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
3727         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
3728    )]
3729    RestartWindowNotCanonical { window: Duration },
3730    #[error(
3731        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
3732         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
3733         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
3734         failure-counting window is structurally so long that transient restarts are never \
3735         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
3736         when the child has exceeded its restart budget within the recent window` to `trip the \
3737         parent when the child has exceeded its restart budget over its lifetime`, and the \
3738         supervisor's reset semantic never reaches the child — every typed-slot consumer \
3739         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
3740         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3741         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
3742         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
3743         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
3744         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
3745         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
3746         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
3747         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
3748         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
3749         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
3750         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
3751         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
3752         hiding it behind a rolling-window declaration the cap arm rejects)"
3753    )]
3754    RestartWindowExceedsCap { window: Duration },
3755    #[error("child entry has empty :caixa name")]
3756    EmptyChildName,
3757    #[error(
3758        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
3759         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
3760         name / label value the child name lands in — the per-child \
3761         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
3762         label value, and the future wasm-operator per-child Service `metadata.name` \
3763         — each apiserver-side schema rejects names that don't match; use a \
3764         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
3765    )]
3766    ChildCaixaInvalid { caixa: String, reason: String },
3767    #[error("child {caixa:?} has empty :versao constraint")]
3768    EmptyChildVersion { caixa: String },
3769    #[error(
3770        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
3771         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
3772         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
3773         `:membros :versao` carry; the lacre pipeline resolves all three \
3774         through the same parser)"
3775    )]
3776    ChildVersaoInvalid {
3777        caixa: String,
3778        versao: String,
3779        reason: String,
3780    },
3781    #[error(
3782        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
3783         child_spec.id per supervisor; duplicate children materialize as duplicate \
3784         ComputeUnits in the rendered chart, one silently overwriting the other)"
3785    )]
3786    DuplicateChildCaixa { caixa: String },
3787    #[error(
3788        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
3789         never its own child (the supervision tree is a DAG rooted at the supervisor; \
3790         OTP child specs reference distinct child processes). Since every :nome is a \
3791         globally-unique substrate identity, a child naming the supervisor's own :nome \
3792         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
3793         self-referential :children entry or rename it to the actual child caixa."
3794    )]
3795    ChildSupervisesSelf { caixa: String },
3796}
3797
3798// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
3799// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
3800// and [`validate_no_self_supervision`] onto one substrate primitive per
3801// typed variant — the sibling on `SupervisorError` of the four uniform-shape
3802// `LayoutError`-envelope constructor families the peer
3803// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
3804// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
3805// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
3806// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
3807// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
3808// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
3809// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
3810// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
3811// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
3812// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
3813// variants on `{ de, para }`) already at that discipline on the peer
3814// `AplicacaoError` envelopes.
3815//
3816// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
3817// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
3818// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
3819// self-supervision arm) opened the identical
3820// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
3821// the exact "same block re-inlined at every consumer" shape the PRIME
3822// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
3823// `AplicacaoError` families each closed on their sibling envelopes. The
3824// three variants share one `{ caixa: String }` shape, so the fold routes
3825// each wire-up site through one dispatch per typed variant.
3826//
3827// The macro below generates one static constructor per variant of shape
3828// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
3829// collapses onto one dispatch:
3830// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
3831// struct-literal on the same `&str` fixture. The uniform one-field
3832// construction (`caixa: caixa.to_string()`) is spelled once — inside the
3833// macro — rather than at every wire-up site. Every constructor is
3834// `#[must_use]` so a caller who mistakenly discards the constructed error
3835// trips a compile warning at the wire-up site.
3836//
3837// Every future consumer that wants to construct one of these three
3838// variants outside `SupervisorSpec::validate_children` /
3839// `validate_no_self_supervision` — a deferred
3840// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3841// webhook re-checking one added/renamed child, a future
3842// `feira validate --supervisor` per-caixa admission verb, a per-child
3843// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
3844// once dynamic-children graduate to a typed slot, a per-Supervisor
3845// overlay resolver rejecting a duplicate/self-supervising child against
3846// a cluster-local snapshot — now reaches each variant through one call
3847// rather than re-inlining the three-line struct-literal in lockstep
3848// with the three in-crate wire-up sites.
3849macro_rules! supervisor_caixa_only_ctors {
3850    ($($ctor:ident => $variant:ident),* $(,)?) => {
3851        impl SupervisorError {
3852            $(
3853                #[doc = concat!(
3854                    "Construct a [`SupervisorError::",
3855                    stringify!($variant),
3856                    "`] naming the offending `:children :caixa` (or ",
3857                    "supervisor `:nome`, on the self-supervision arm). ",
3858                    "Folds the uniform `Self::",
3859                    stringify!($variant),
3860                    " { caixa: caixa.to_string() }` one-field ",
3861                    "struct-literal onto one substrate primitive so ",
3862                    "every [`SupervisorSpec::validate_children`] / ",
3863                    "[`validate_no_self_supervision`] wire-up on this ",
3864                    "variant reads through one dispatch rather than the ",
3865                    "pre-lift open-coded struct-literal block."
3866                )]
3867                #[must_use]
3868                pub fn $ctor(caixa: &str) -> Self {
3869                    Self::$variant { caixa: caixa.to_string() }
3870                }
3871            )*
3872        }
3873    };
3874}
3875
3876supervisor_caixa_only_ctors! {
3877    empty_child_version => EmptyChildVersion,
3878    duplicate_child_caixa => DuplicateChildCaixa,
3879    child_supervises_self => ChildSupervisesSelf,
3880}
3881
3882// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
3883// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
3884// one substrate primitive per typed variant — the M2 supervisor-side siblings
3885// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
3886// already lifted through the sibling
3887// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
3888// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
3889// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
3890// String }` two-slot shape the peer seven-variant
3891// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
3892// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
3893// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
3894// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
3895// variant carries the `{ caixa: String, versao: String, reason: String }`
3896// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
3897// carries on the same `:versao` value-shape.
3898//
3899// Each of the two wire-up sites opened the same closure-shaped
3900// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
3901// [versao: child.versao_requirement().to_string(),] reason }` block inside
3902// the paired [`crate::render::require_valid_dns_1123_label`] and
3903// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
3904// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
3905// as a bug, on the same altitude the peer `AplicacaoError` /
3906// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
3907// families already closed on their sibling envelopes.
3908//
3909// The two `#[must_use]` inherent constructors below fold each wire-up onto
3910// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
3911// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
3912// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
3913// The uniform per-field `.to_string()` / `.into()` construction is spelled
3914// once — inside each ctor body — rather than at every wire-up site. The
3915// `reason: impl Into<String>` bound accepts both `&str` literals and
3916// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
3917// diagnostic shape at the lift, matching the peer
3918// [`aplicacao_field_reason_ctors!`] and
3919// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
3920// sibling envelopes.
3921//
3922// Every future consumer that wants to construct one of these two variants
3923// outside `SupervisorSpec::validate_children` — a deferred
3924// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
3925// re-checking one added/renamed child's `:caixa` or `:versao`, a future
3926// `feira validate --supervisor` per-caixa admission verb, a per-child
3927// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
3928// dynamic-children graduate to a typed slot, a per-Supervisor overlay
3929// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
3930// cluster-local snapshot — now reaches each variant through one call rather
3931// than re-inlining the per-shape struct-literal block in lockstep with the
3932// two in-crate wire-up sites.
3933impl SupervisorError {
3934    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
3935    /// offending `:children :caixa` value under the given `reason`. Folds
3936    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
3937    /// reason: reason.into() }` two-slot struct-literal onto one substrate
3938    /// primitive so every wire-up on this variant reads through one
3939    /// dispatch, matching the peer
3940    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
3941    /// sibling `AplicacaoError { caixa: String, reason: String }`
3942    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
3943    /// outputs through the `impl Into<String>` bound.
3944    #[must_use]
3945    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
3946        Self::ChildCaixaInvalid {
3947            caixa: caixa.to_string(),
3948            reason: reason.into(),
3949        }
3950    }
3951
3952    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
3953    /// offending `:children :caixa` and its `:versao` requirement under
3954    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
3955    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
3956    /// reason.into() }` three-slot struct-literal onto one substrate
3957    /// primitive so every wire-up on this variant reads through one
3958    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
3959    /// { caixa, versao, reason }` three-slot axis on the peer
3960    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
3961    /// and `format!(…)` outputs through the `impl Into<String>` bound.
3962    #[must_use]
3963    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
3964        Self::ChildVersaoInvalid {
3965            caixa: caixa.to_string(),
3966            versao: versao.to_string(),
3967            reason: reason.into(),
3968        }
3969    }
3970}
3971
3972// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
3973// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
3974// three bracket-arms — one struct-literal at the `:children`-empty
3975// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
3976// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
3977// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
3978// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
3979// [`crate::render::require_positive_canonical_bounded_duration`]
3980// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
3981// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
3982// primitive per typed variant, matching the sibling
3983// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
3984// variants on the same `{ <field>: Duration | u32 }` shape) at that
3985// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
3986// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
3987// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
3988// wire-up site through one dispatch per typed variant without a runtime-
3989// work delta.
3990//
3991// Each of the four wire-up sites opened the identical
3992// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
3993// exact "same block re-inlined at every consumer" shape the PRIME
3994// DIRECTIVE names as a bug, on the same altitude the peer
3995// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
3996// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
3997// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
3998// the fold routes each wire-up site through one dispatch per typed
3999// variant.
4000//
4001// The macro below generates one static constructor per variant of shape
4002// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
4003// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
4004// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
4005// fixture — as a direct call at the [`SupervisorSpec::validate`]
4006// `:children`-empty refusal, or as a bare function pointer in the
4007// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
4008// [`crate::render::require_positive_bounded_u32`] /
4009// [`crate::render::require_positive_canonical_bounded_duration`] gate
4010// carries — rather than the pre-lift open-coded one-line closure over
4011// the same one-field struct-literal. `const fn` preserves the `Copy`-
4012// pass-through's zero-runtime-work property verbatim. Every constructor
4013// is `#[must_use]` so a caller who mistakenly discards the constructed
4014// error trips a compile warning at the wire-up site.
4015//
4016// Every future consumer that wants to construct one of these four
4017// variants outside `SupervisorSpec::validate` — a deferred
4018// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4019// webhook re-checking one edited `:estrategia` / `:max-restarts` /
4020// `:restart-window` slot against the cap + canonical-form cascade, a
4021// future `feira validate --supervisor` per-caixa admission verb re-
4022// running the shape gates on demand, a per-Supervisor overlay resolver
4023// rejecting an author-supplied slot against a cluster-local snapshot —
4024// now reaches each variant through one call rather than re-inlining the
4025// per-shape struct-literal block in lockstep with the four in-crate
4026// wire-up sites.
4027macro_rules! supervisor_scalar_ctors {
4028    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
4029        impl SupervisorError {
4030            $(
4031                #[doc = concat!(
4032                    "Construct a [`SupervisorError::",
4033                    stringify!($variant),
4034                    "`] naming the offending per-`:supervisor` `",
4035                    stringify!($field),
4036                    "` scalar. Folds the uniform `Self::",
4037                    stringify!($variant),
4038                    " { ",
4039                    stringify!($field),
4040                    " }` one-field `Copy`-pass-through struct-literal onto ",
4041                    "one substrate primitive so every per-axis wire-up on ",
4042                    "this variant reads through one dispatch — as a direct ",
4043                    "call (`SupervisorError::",
4044                    stringify!($ctor),
4045                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
4046                    "the same `Copy`-`",
4047                    stringify!($ty),
4048                    "` fixture) or as a bare function pointer in the ",
4049                    "`impl FnOnce(",
4050                    stringify!($ty),
4051                    ") -> SupervisorError` bracket-closure slot every ",
4052                    "`crate::render::require_positive_bounded_*` / ",
4053                    "`crate::render::require_positive_canonical_bounded_*` ",
4054                    "gate carries — rather than the pre-lift open-coded ",
4055                    "one-line closure over the same one-field struct-",
4056                    "literal. `const fn` preserves the `Copy`-pass-through's ",
4057                    "zero-runtime-work property verbatim."
4058                )]
4059                #[must_use]
4060                pub const fn $ctor($field: $ty) -> Self {
4061                    Self::$variant { $field }
4062                }
4063            )*
4064        }
4065    };
4066}
4067
4068supervisor_scalar_ctors! {
4069    no_children => NoChildren { estrategia: RestartStrategy },
4070    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
4071    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
4072    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
4073}
4074
4075/// Shared duration string codec for the typed slots that take a
4076/// duration (`restart_window`, `MeshPolicy::timeout`,
4077/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
4078/// reuse it without duplicating the parser.
4079pub mod duration_codec {
4080    use super::Duration;
4081    use serde::{Deserializer, Serializer};
4082
4083    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
4084        // Route through the canonical [`crate::render::serialize_option_via_str`]
4085        // — the substrate-side single-owner primitive for the forward
4086        // arm of the typed-magnitude codec family. See its docstring
4087        // for the full sibling roster.
4088        crate::render::serialize_option_via_str(v, s, render)
4089    }
4090
4091    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
4092        // Route through the canonical [`crate::render::deserialize_option_via_str`]
4093        // — the substrate-side single-owner primitive for the reverse
4094        // arm of the typed-magnitude codec family. See its docstring
4095        // for the full sibling roster.
4096        crate::render::deserialize_option_via_str(d, parse)
4097    }
4098
4099    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
4100        // Paired whitespace-rejection arm — same canonical-form
4101        // render-determinism discipline as the peer
4102        // `limits::parse_byte_size` / `limits::parse_duration` /
4103        // `limits::parse_millicores` /
4104        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
4105        // byte-scan closes the WhatWG-conformant whitespace bytes
4106        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
4107        // `char::is_whitespace` scan closes the strictly-complementary
4108        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
4109        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
4110        // codepoints) that `str::trim` at parse entry silently strips.
4111        // Either drift class would round-trip through `render` to a
4112        // *different* canonical form on next emit — breaking the
4113        // THEORY.md Part V render-determinism contract on three typed-
4114        // duration slots at once (`:supervisor :restart-window`,
4115        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
4116        // via the shared codec.
4117        //
4118        // Routed through the lifted [`crate::render::reject_whitespace`]
4119        // primitive — the substrate-side single-owner paired-arm gate
4120        // every typed-magnitude codec in caixa-core shares.
4121        crate::render::reject_whitespace::<String, _, _>(
4122            s,
4123            |b| {
4124                format!(
4125                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4126                 authoring form for the typed duration slots routed through this shared codec \
4127                 (`:supervisor :restart-window`, `:politicas :timeout`, \
4128                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4129                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
4130                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
4131                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
4132                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
4133                 Part V render-determinism contract every typed slot carries. Strip every \
4134                 whitespace byte (write `\"30s\"` verbatim)"
4135                )
4136            },
4137            |ch| {
4138                format!(
4139                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
4140                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
4141                 duration slots routed through this shared codec (`:supervisor \
4142                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
4143                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
4144                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
4145                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
4146                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
4147                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
4148                 `White_Space` property, strictly wider than the ASCII byte set) silently \
4149                 strips it at parse entry, and the value round-trips through `render` to \
4150                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
4151                 the THEORY.md Part V render-determinism contract every typed slot \
4152                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
4153                 verbatim with only ASCII bytes)",
4154                    cp = ch as u32
4155                )
4156            },
4157        )?;
4158        let s = s.trim();
4159        // Routed through the lifted
4160        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
4161        // the single-owner split every ASCII-alphabetic-unit typed-
4162        // magnitude codec in caixa-core (`limits::parse_byte_size` /
4163        // `limits::parse_duration` / this shared duration codec) shares.
4164        // See its docstring for the full sibling roster on the same
4165        // primitive altitude.
4166        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
4167        let num_trim = num_part.trim();
4168        // The canonical authoring form for every typed slot routed
4169        // through this shared codec — `:supervisor :restart-window`,
4170        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
4171        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
4172        // non-negative integer with no decimal point and no leading
4173        // sign, so the parser's accepted set must match for
4174        // serialize/deserialize to round-trip without canonical-form
4175        // drift. Until this gate landed the parser accepted any
4176        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
4177        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
4178        // tripped the value to a *different* canonical string on the
4179        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
4180        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
4181        // — breaking the THEORY.md Part V render-determinism contract
4182        // on three typed slots at once. Same canonical-form discipline
4183        // `crate::limits::parse_duration` (818dd38, the immediate
4184        // predecessor on the peer `:limits :wall-clock` codec) applies;
4185        // this gate lifts the discipline onto the shared codec that
4186        // backs the remaining three typed-duration slots in caixa-core.
4187        //
4188        // Strict canonical form: every byte of the magnitude is an
4189        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4190        // inputs the gate distinguishes "non-canonical-but-numeric"
4191        // (parses as f64 or i64 — surfaced with a self-locating
4192        // diagnostic naming the canonical authoring form, the
4193        // round-trip drift each rejected shape would produce on first
4194        // serialize, and the canonical-form remediation) from
4195        // "garbage" (parses as neither — surfaced with the existing
4196        // narrower "bad duration magnitude" wording so its diagnostic
4197        // shape remains stable for the parser-shape footgun case).
4198        // The pre-existing `num < 0.0` arm is now unreachable — the
4199        // digit-only gate strictly precedes magnitude parsing, and a
4200        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
4201        // non-canonical-but-numeric branch with the `-30` named
4202        // verbatim in the diagnostic rather than the prior
4203        // value-laundered "negative duration in \"-30s\"" wording.
4204        //
4205        // Routed through the lifted
4206        // [`crate::render::is_digit_only_magnitude`] predicate — the
4207        // same source of truth the four peer typed-magnitude codec
4208        // sites share.
4209        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
4210        if !digit_only {
4211            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
4212            if numeric {
4213                return Err(format!(
4214                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
4215                     canonical authoring form for the typed duration slots routed through \
4216                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4217                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4218                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
4219                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
4220                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
4221                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
4222                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
4223                     THEORY.md Part V render-determinism contract every typed slot carries. \
4224                     Pick an integer magnitude in the unit that divides cleanly (write \
4225                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
4226                ));
4227            }
4228            return Err(format!("bad duration magnitude in {s:?}"));
4229        }
4230        // Leading-zero arm — peer with the `rate_limit_codec` leading-
4231        // zero arm (4f46830) on the same canonical-form render-
4232        // determinism axis. The digit-only gate accepts `"030s"`,
4233        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
4234        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
4235        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
4236        // *different* canonical string on the next emit, breaking the
4237        // THEORY.md Part V render-determinism contract the same way
4238        // `"+30s"` did before the leading-`+` arm landed. The single-
4239        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
4240        // losslessly through `render` (`render(Duration::ZERO)` emits
4241        // `"0s"`) — the downstream semantic-zero gates (e.g.
4242        // `SupervisorError::ZeroRestartWindow` on
4243        // `:supervisor :restart-window`,
4244        // `AplicacaoError::PolicyTimeoutZero` /
4245        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
4246        // duration slots) refuse zero-magnitude authoring at the typed-
4247        // validate layer above, so the single-byte `"0"` stays in the
4248        // accepted set at this codec layer and the diagnostic
4249        // partitioning between canonical-form drift (this arm) and
4250        // semantic-zero (the downstream gates) remains stable.
4251        // Peer with the future leading-zero arms on the two remaining
4252        // typed-magnitude codecs the trajectory acknowledges:
4253        // `limits::parse_duration` backing `:limits :wall-clock`,
4254        // `limits::parse_byte_size` backing `:limits :memory` — each
4255        // carries the same canonical-form-drift class today; this
4256        // gate lands the discipline on the shared duration codec
4257        // first because the `rate_limit_codec` predecessor on the
4258        // same canonical-form-drift axis is the closest peer on the
4259        // trajectory.
4260        //
4261        // Routed through the lifted
4262        // [`crate::render::is_leading_zero_padded_magnitude`]
4263        // predicate — the same source of truth the four peer
4264        // typed-magnitude codec sites share.
4265        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
4266            return Err(format!(
4267                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
4268                 canonical authoring form for the typed duration slots routed through \
4269                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4270                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4271                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
4272                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
4273                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
4274                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
4275                 serialize — breaking the THEORY.md Part V render-determinism contract \
4276                 every typed slot carries. Strip the leading zeros (write \
4277                 `\"30s\"` instead of `\"030s\"`)"
4278            ));
4279        }
4280        // The digit-only gate guarantees every byte is `[0-9]`, and
4281        // the leading-zero arm above guarantees the magnitude is
4282        // either the single byte `"0"` or starts with `[1-9]`, so
4283        // the only way `u64::from_str` can fail here is overflow (the
4284        // magnitude exceeds `u64::MAX`). Surface that with an
4285        // overflow-shaped wording so the diagnostic names the offending
4286        // magnitude verbatim rather than collapsing onto the
4287        // non-canonical arm. The codec now operates on `u64` end-to-end
4288        // — every accepted magnitude is integer-exact; no f64 mantissa
4289        // drift between author-supplied magnitude and the consumer's
4290        // `Duration` value. Same shape `crate::limits::parse_duration`
4291        // (818dd38) carries on the peer `:limits :wall-clock` axis.
4292        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
4293            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
4294        })?;
4295        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
4296        // unit-arm dispatch through the canonical
4297        // [`crate::render::duration_from_integer_magnitude_and_unit`]
4298        // primitive — the substrate-side single-owner unit-dispatch
4299        // table every typed-duration codec in caixa-core routes
4300        // through (peer: `crate::limits::parse_duration` backing
4301        // `:limits :wall-clock`). Every unit conversion is integer-
4302        // exact for an integer magnitude; overflow surfaces via the
4303        // typed `DurationUnitError::Overflow { multiplier }`
4304        // discriminant so this arm reconstructs the pre-lift
4305        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
4306        // wording verbatim from `num` / `unit_trim` / the returned
4307        // `multiplier`, and the unknown-unit arm reconstructs the
4308        // pre-lift `"unknown duration unit \"<other>\""` wording from
4309        // the caller-scoped `unit_trim`. Load-bearing pinned by
4310        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
4311        let unit_trim = unit.trim();
4312        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
4313            |e| match e {
4314                crate::render::DurationUnitError::Overflow { multiplier } => format!(
4315                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
4316                ),
4317                crate::render::DurationUnitError::UnknownUnit => {
4318                    format!("unknown duration unit {unit_trim:?}")
4319                }
4320            },
4321        )?;
4322        Ok(dur)
4323    }
4324
4325    /// Render a [`Duration`] in the canonical pleme-io duration string
4326    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
4327    /// caixa typed-duration slot serializes to and the same form K8s
4328    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
4329    /// EnvoyConfig per-route timeouts both expect (an integer
4330    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
4331    /// `+`). Lifted to `pub` so caixa-side renderers
4332    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
4333    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
4334    /// emitter, the future caixa-otel collector pipeline emitter) can
4335    /// consume the same canonical formatter without re-inlining the
4336    /// magnitude/unit decision tree (and inheriting the same drift
4337    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
4338    /// downstream apply-time parsing in non-obvious ways).
4339    pub fn render(d: Duration) -> String {
4340        let total_ms = d.as_millis();
4341        if total_ms == 0 {
4342            return "0s".into();
4343        }
4344        if total_ms.is_multiple_of(3600 * 1000) {
4345            return format!("{}h", total_ms / (3600 * 1000));
4346        }
4347        if total_ms.is_multiple_of(60 * 1000) {
4348            return format!("{}m", total_ms / (60 * 1000));
4349        }
4350        if total_ms.is_multiple_of(1000) {
4351            return format!("{}s", total_ms / 1000);
4352        }
4353        format!("{total_ms}ms")
4354    }
4355
4356    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
4357    ///
4358    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
4359    /// largest divisor unit, so any sub-millisecond residue
4360    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
4361    /// §V.2.7 render-determinism contract:
4362    ///
4363    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
4364    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
4365    ///     `1_000_000` ns ≠ original `1_500_000` ns;
4366    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
4367    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
4368    ///     on every typed-`Duration` slot then rejects on re-validate.
4369    ///
4370    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
4371    /// the codec's round-trippable accepted set lives in exactly one place —
4372    /// every typed-`Duration` slot that routes through this shared codec
4373    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
4374    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
4375    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
4376    /// every typed-`Duration` slot whose own codec shares the same
4377    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
4378    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
4379    /// pair) calls this predicate from its `validate()` to bracket the
4380    /// accepted set against the codec's accepted set, structurally. Drift
4381    /// between the codec's granularity and any typed slot's accepted set is
4382    /// then a single-source-of-truth edit at this predicate rather than a
4383    /// silent round-trip break the next consumer discovers at apply time.
4384    ///
4385    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
4386    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
4387    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
4388    /// family — same "typed-slot's valid set matches its codec's accepted
4389    /// set, structurally" discipline carried at the codec layer.
4390    #[must_use]
4391    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
4392        d.subsec_nanos().is_multiple_of(1_000_000)
4393    }
4394}
4395
4396/// Required-Duration variant for fields that aren't Option<Duration>.
4397pub mod duration_codec_required {
4398    use super::Duration;
4399    use serde::{Deserialize, Deserializer, Serializer};
4400
4401    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
4402        s.serialize_str(&super::duration_codec::render(*v))
4403    }
4404
4405    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
4406        let s = String::deserialize(d)?;
4407        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
4408    }
4409}
4410
4411#[cfg(test)]
4412mod tests {
4413    use super::*;
4414
4415    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
4416        ChildSpec {
4417            caixa: name.into(),
4418            versao: ver.into(),
4419            restart,
4420        }
4421    }
4422
4423    #[test]
4424    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
4425        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
4426        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
4427        // posture. Each accessor projects the per-`:children :caixa`
4428        // / per-`:children :versao` [`String`] storage through the
4429        // `pub const fn` [`String::as_str`] (const-stable since Rust
4430        // 1.87, well within the workspace MSRV) — any future
4431        // accidental downgrade to non-`const` fails the corresponding
4432        // `<name>_via_const_fn` wrapper at caixa-core build time with
4433        // E0015 (`cannot call non-const method`), strictly stronger
4434        // than a runtime `assert!`. Sibling of the peer
4435        // per-M2/M3/universal-axis `String → &str` scalar-accessor
4436        // family pins on the sibling `const`-eval-surface passes
4437        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
4438        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
4439        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
4440        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
4441        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
4442        // [`crate::aplicacao::Entrada::destination`] at the M3
4443        // ingress axis,
4444        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
4445        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
4446        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
4447        // axis, and the per-`:contratos`
4448        // [`crate::aplicacao::WitContract::source`] /
4449        // [`crate::aplicacao::WitContract::destination`] /
4450        // [`crate::aplicacao::WitContract::world_ref`] trio the
4451        // sibling pin at 279823b already anchors).
4452        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
4453            c.nome()
4454        }
4455        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
4456            c.versao_requirement()
4457        }
4458        for (caixa, versao) in [
4459            ("worker-a", "^0.1"),
4460            ("worker-b", "~0.2.3"),
4461            ("collector", "*"),
4462        ] {
4463            let c = child(caixa, versao, RestartPolicy::Permanent);
4464            assert_eq!(nome_via_const_fn(&c), c.nome());
4465            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
4466            assert_eq!(c.nome(), caixa);
4467            assert_eq!(c.versao_requirement(), versao);
4468        }
4469    }
4470
4471    #[test]
4472    fn supervisor_children_slice_return_accessor_is_const_fn() {
4473        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
4474        // `const`-eval-surface posture. The accessor destructures the
4475        // per-`:children` `Vec<ChildSpec>` storage through the
4476        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
4477        // 1.66, well within the workspace MSRV) — any future
4478        // accidental downgrade to non-`const` fails
4479        // `children_via_const_fn` at caixa-core build time with E0015
4480        // (`cannot call non-const method`), strictly stronger than a
4481        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
4482        // `Vec → &[T]` slice-return accessor family pin
4483        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
4484        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
4485        // per-`:membros` / per-`:contratos` slice-return axes, and of
4486        // the peer M2 upgrade-appup axis pin
4487        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
4488        // on the per-`:upgrade-from :instructions` slice-return axis.
4489        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
4490            s.children()
4491        }
4492        // Sweep both the empty-children (leaf-supervisor with no
4493        // static children — the `SimpleOneForOne` dynamic-child
4494        // arm's canonical shape) and the populated-children
4495        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
4496        // arm's canonical shape) axes so the accessor carries a
4497        // const-dispatch pin on both arms.
4498        let s_empty = SupervisorSpec {
4499            estrategia: RestartStrategy::SimpleOneForOne,
4500            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4501            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4502            children: vec![],
4503        };
4504        assert!(children_via_const_fn(&s_empty).is_empty());
4505        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
4506        let s_full = SupervisorSpec {
4507            estrategia: RestartStrategy::OneForOne,
4508            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4509            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4510            children: vec![
4511                child("worker-a", "^0.1", RestartPolicy::Permanent),
4512                child("worker-b", "~0.2.3", RestartPolicy::Transient),
4513                child("collector", "*", RestartPolicy::Temporary),
4514            ],
4515        };
4516        assert_eq!(children_via_const_fn(&s_full).len(), 3);
4517        assert_eq!(children_via_const_fn(&s_full), s_full.children());
4518    }
4519
4520    #[test]
4521    fn default_has_one_for_one_and_5_restarts_in_60s() {
4522        let s = SupervisorSpec::default();
4523        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
4524        assert_eq!(s.max_restarts, 5);
4525        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
4526        assert!(s.children.is_empty());
4527    }
4528
4529    #[test]
4530    fn validate_one_for_one_requires_children() {
4531        let mut s = SupervisorSpec::default();
4532        s.children = vec![];
4533        assert!(matches!(
4534            s.validate().unwrap_err(),
4535            SupervisorError::NoChildren { .. }
4536        ));
4537        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
4538        s.validate().unwrap();
4539    }
4540
4541    #[test]
4542    fn validate_simple_one_for_one_forbids_static_children() {
4543        let mut s = SupervisorSpec {
4544            estrategia: RestartStrategy::SimpleOneForOne,
4545            ..SupervisorSpec::default()
4546        };
4547        s.children
4548            .push(child("w", "^0.1", RestartPolicy::Permanent));
4549        assert_eq!(
4550            s.validate().unwrap_err(),
4551            SupervisorError::SimpleOneForOneWithStaticChildren
4552        );
4553        s.children.clear();
4554        s.validate().unwrap();
4555    }
4556
4557    #[test]
4558    fn validate_rejects_zero_max_restarts() {
4559        let s = SupervisorSpec {
4560            max_restarts: 0,
4561            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4562            ..SupervisorSpec::default()
4563        };
4564        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
4565    }
4566
4567    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
4568    //
4569    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
4570    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
4571    // `:supervisor :max-restarts` axis — both fields are "trip the
4572    // next-higher protection layer after N events in a rolling window"
4573    // counters with identical degenerate-at-the-high-end shape, so the
4574    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
4575    // exactly as it lies in `1..=1000` on the breaker side.
4576
4577    #[test]
4578    fn validate_rejects_max_restarts_above_cap() {
4579        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
4580        // 1` is structurally one past the cap and silently passed
4581        // validate on every pre-gate codebase because the typed slot's
4582        // only check was the zero-floor arm. The no-op-supervisor vector
4583        // only surfaced at the runtime substrate (Erlang/OTP
4584        // MaxIntensity/Period ratio, the future wasm-operator's
4585        // per-supervisor restart-intensity counter) far from the source
4586        // caixa.lisp with no field naming the offending supervisor.
4587        let s = SupervisorSpec {
4588            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4589            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4590            ..SupervisorSpec::default()
4591        };
4592        assert_eq!(
4593            s.validate().unwrap_err(),
4594            SupervisorError::MaxRestartsExceedsCap {
4595                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4596            }
4597        );
4598    }
4599
4600    #[test]
4601    fn validate_rejects_max_restarts_far_above_cap() {
4602        // The `u32::MAX` worst case — the four-billion-restart
4603        // threshold a typo (`:max-restarts 4294967295`) or a
4604        // struct-literal copy-paste lands in the slot. Pin the cap
4605        // arm's coverage explicitly across the full `u32` overflow so
4606        // a future relaxation that drops the upper bound surfaces
4607        // here. Same shape every other typed-cap arm on this surface
4608        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
4609        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
4610        let s = SupervisorSpec {
4611            max_restarts: u32::MAX,
4612            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4613            ..SupervisorSpec::default()
4614        };
4615        assert_eq!(
4616            s.validate().unwrap_err(),
4617            SupervisorError::MaxRestartsExceedsCap {
4618                max_restarts: u32::MAX,
4619            }
4620        );
4621    }
4622
4623    #[test]
4624    fn validate_accepts_max_restarts_at_cap() {
4625        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
4626        // must validate. The cap is inclusive on the top edge,
4627        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
4628        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
4629        // discipline on the sibling capped axes. Pin the boundary
4630        // explicitly so a future off-by-one tightening
4631        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
4632        // here as a test failure rather than a silent contract
4633        // narrowing.
4634        let s = SupervisorSpec {
4635            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
4636            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4637            ..SupervisorSpec::default()
4638        };
4639        s.validate()
4640            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
4641    }
4642
4643    #[test]
4644    fn validate_accepts_max_restarts_typical_values() {
4645        // The documented production-playbook band positive-control
4646        // sweep — every value Erlang/OTP / Elixir / Riak Core /
4647        // RabbitMQ recommend (1..=100) must pass, plus a sweep
4648        // through the hyperscale band (200, 500, 1000) the cap
4649        // accepts. Pin the inclusive validated set explicitly so a
4650        // future tightening of the ceiling surfaces here.
4651        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
4652            let s = SupervisorSpec {
4653                max_restarts: n,
4654                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4655                ..SupervisorSpec::default()
4656            };
4657            s.validate()
4658                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
4659        }
4660    }
4661
4662    #[test]
4663    fn zero_max_restarts_takes_precedence_over_cap() {
4664        // The cross-arm ordering pin: `0` is structurally outside
4665        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
4666        // (cap), but the zero-floor diagnostic is the more
4667        // self-locating one (it directly names the counter-axis
4668        // remediation), so the validate gate must fire on zero first.
4669        // Same shape every other zero-then-shape ordering on this
4670        // surface uses (PolicyRetriesZero then
4671        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
4672        // PolicyBreakerMaxFailuresExceedsCap).
4673        let s = SupervisorSpec {
4674            max_restarts: 0,
4675            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4676            ..SupervisorSpec::default()
4677        };
4678        assert_eq!(
4679            s.validate().unwrap_err(),
4680            SupervisorError::ZeroMaxRestarts,
4681            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
4682        );
4683    }
4684
4685    #[test]
4686    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
4687        // The cross-arm ordering pin between the cap and the sibling
4688        // `:restart-window` gates (zero-window, canonical-window). A
4689        // supervisor carrying both an over-cap `max_restarts` AND a
4690        // structurally invalid window (zero, sub-ms) must surface the
4691        // cap diagnostic first — the cap arm is wired immediately
4692        // after the zero-restart arm and strictly before the window
4693        // arms, so the offending value the diagnostic names matches
4694        // the order the author would discover the gates by reading
4695        // top-to-bottom through `SupervisorSpec::validate`. Pin the
4696        // order so a future refactor that reorders the arms surfaces
4697        // here as a test failure rather than a silent diagnostic
4698        // regression. Peer of
4699        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
4700        // on the sibling `:politicas :circuit-breaker` slot.
4701        let s = SupervisorSpec {
4702            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4703            restart_window: Some(Duration::ZERO),
4704            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4705            ..SupervisorSpec::default()
4706        };
4707        assert_eq!(
4708            s.validate().unwrap_err(),
4709            SupervisorError::MaxRestartsExceedsCap {
4710                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4711            },
4712            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4713        );
4714    }
4715
4716    #[test]
4717    fn max_restarts_cap_diagnostic_carries_offending_value() {
4718        // The diagnostic-shape pin: the offending `u32` is carried
4719        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
4720        // variant so the surfaced error message names the value the
4721        // author wrote (`":supervisor :max-restarts (50000) exceeds the
4722        // supervisor-policy ceiling …"`), not just the cap. Same
4723        // self-locating diagnostic shape every other typed-cap arm on
4724        // this surface carries
4725        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
4726        // the offending failure count verbatim,
4727        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
4728        // retries count verbatim).
4729        let s = SupervisorSpec {
4730            max_restarts: 50_000,
4731            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4732            ..SupervisorSpec::default()
4733        };
4734        let err = s.validate().unwrap_err();
4735        assert!(
4736            matches!(
4737                err,
4738                SupervisorError::MaxRestartsExceedsCap {
4739                    max_restarts: 50_000
4740                }
4741            ),
4742            "got {err:?}"
4743        );
4744        let msg = err.to_string();
4745        assert!(
4746            msg.contains("50000"),
4747            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
4748        );
4749    }
4750
4751    #[test]
4752    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
4753        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
4754        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
4755        // half of Learn You Some Erlang's worker-supervisor default,
4756        // sibling of the `60s` `Period` half that the paired
4757        // [`Default for SupervisorSpec`] impl already pins on the
4758        // sibling `restart_window` axis. Pinning the literal here
4759        // surfaces a future rebrand (a tightening to Elixir's `3`,
4760        // a widening to a per-cluster overlay the operator pins
4761        // through a future `:max-restarts-overrides` slot) as a
4762        // deliberate test edit, not a silent contract migration.
4763        // Peer of the sibling
4764        // [`supervisor_max_restarts_cap_pins_canonical_value`]
4765        // upper-bracket pin on the same axis.
4766        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
4767    }
4768
4769    #[test]
4770    fn default_max_restarts_helper_routes_through_lifted_default() {
4771        // Composition pin: the private `default_max_restarts()`
4772        // serde-`#[serde(default = "…")]` helper on
4773        // [`SupervisorSpec::max_restarts`] must route through the
4774        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4775        // typed `pub const` rather than a raw `5` literal. Prior to
4776        // the lift the helper carried an inline `5` with no compile-
4777        // time link back to the shared default, so the wire-format
4778        // author-omitted arm and the caixa-core
4779        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
4780        // arm could silently split on any future default rebrand.
4781        // Byte-parity against the lifted constant closes the split.
4782        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
4783    }
4784
4785    #[test]
4786    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
4787        // Composition pin: the [`Default for SupervisorSpec`] impl's
4788        // struct-literal `max_restarts` field must route through the
4789        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4790        // typed `pub const` (via the private helper this test's
4791        // sibling `default_max_restarts_helper_routes_through_lifted_default`
4792        // already pins onto the constant). Structurally: every
4793        // `SupervisorSpec::default()` call must yield a
4794        // `max_restarts` field byte-equal to the lifted constant
4795        // (the two paired defaults — the serde-side wire-format arm
4796        // and the struct-literal default arm — cannot silently split
4797        // on any future default rebrand). Peer of the sibling
4798        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
4799        // — this pin closes the byte-parity arm on the two paired
4800        // altitude entry points onto the shared substrate constant.
4801        assert_eq!(
4802            SupervisorSpec::default().max_restarts(),
4803            SUPERVISOR_MAX_RESTARTS_DEFAULT,
4804        );
4805    }
4806
4807    #[test]
4808    fn supervisor_restart_window_default_pins_otp_canonical_value() {
4809        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
4810        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
4811        // Learn You Some Erlang's worker-supervisor default, paired
4812        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
4813        // `MaxIntensity` half this constant is the sliding-window
4814        // denominator of on the same `MaxIntensity / Period`
4815        // restart-intensity ratio. Pinning the literal here surfaces a
4816        // future coherent rebrand of the paired default (Elixir's
4817        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
4818        // the operator pins through a future
4819        // `:restart-window-overrides` slot) as a deliberate test edit,
4820        // not a silent contract migration. Peer of the sibling
4821        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
4822        // paired-half pin on the same OTP-canonical default and the
4823        // [`supervisor_restart_window_cap_pins_canonical_value`]
4824        // upper-bracket pin on the same axis.
4825        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
4826    }
4827
4828    #[test]
4829    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
4830        // Composition pin: the [`Default for SupervisorSpec`] impl's
4831        // struct-literal `restart_window` field must route through the
4832        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4833        // typed `pub const` rather than a raw
4834        // `Duration::from_secs(60)` literal. Prior to this lift the
4835        // paired `{intensity, 5, 60}` OTP-canonical default was split
4836        // across two altitudes with no compile-time link between the
4837        // halves — the `MaxIntensity` half rode through the lifted
4838        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
4839        // `Period` half rode as an open-coded literal at the
4840        // composition site, so a future coherent rebrand of the paired
4841        // canonical would have had to migrate one half through the
4842        // constant and the other through a raw literal in lockstep.
4843        // Byte-parity against the lifted constant on the `Period` half
4844        // closes the split — the paired OTP-canonical default now
4845        // migrates as one unit on any future axis change. Peer of the
4846        // sibling
4847        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4848        // byte-parity pin on the paired `MaxIntensity` half.
4849        assert_eq!(
4850            SupervisorSpec::default().restart_window(),
4851            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4852        );
4853    }
4854
4855    #[test]
4856    fn supervisor_estrategia_default_pins_otp_canonical_value() {
4857        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
4858        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
4859        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
4860        // canonical default, paired with the sibling
4861        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
4862        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
4863        // this constant is the strategy discriminator of on the same
4864        // OTP-canonical worker-supervisor default. Pinning the arm here
4865        // surfaces a future coherent rebrand of the paired triple (Elixir's
4866        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
4867        // intensity/period axes leaving this strategy arm untouched, an OTP
4868        // `rest_for_one` widening once the substrate discovers startup-
4869        // order-coupled child cohorts as the more common worker-supervisor
4870        // shape, a per-cluster overlay the operator pins through a future
4871        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
4872        // supervision-canary roadmap acknowledges) as a deliberate test
4873        // edit, not a silent contract migration. Peer of the sibling
4874        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
4875        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4876        // paired-half pins on the same OTP-canonical default.
4877        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
4878    }
4879
4880    #[test]
4881    fn restart_strategy_default_routes_through_lifted_default() {
4882        // Composition pin: the [`Default for RestartStrategy`] impl's
4883        // return arm must route through the substrate-canonical
4884        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
4885        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
4886        // an inline `Self::OneForOne` with no compile-time link back to
4887        // the shared OTP-canonical `one_for_one` strategy the paired
4888        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
4889        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
4890        // `.unwrap_or_default()` (now
4891        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
4892        // so a future rebrand of the OTP-canonical strategy default (an
4893        // OTP `rest_for_one` widening once the substrate discovers
4894        // startup-order-coupled child cohorts as the more common worker-
4895        // supervisor shape, a per-cluster overlay the operator pins
4896        // through a future `:estrategia-overrides` slot) would have had to
4897        // be threaded through the `Default` impl and the two peer routes
4898        // in lockstep or the three consumers would silently split. Byte-
4899        // parity against the lifted constant closes the split. Peer of
4900        // the sibling
4901        // [`default_max_restarts_helper_routes_through_lifted_default`] +
4902        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4903        // composition pins on the paired `MaxIntensity` + `Period` halves.
4904        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
4905    }
4906
4907    #[test]
4908    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
4909        // Composition pin: the [`Default for SupervisorSpec`] impl's
4910        // struct-literal `estrategia` field must route through the
4911        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
4912        // `pub const` (either directly, or via the
4913        // [`RestartStrategy::default`] impl that the sibling
4914        // `restart_strategy_default_routes_through_lifted_default` pin
4915        // already routes onto the constant). Structurally: every
4916        // `SupervisorSpec::default()` call must yield an `estrategia`
4917        // field byte-equal to the lifted constant (the three paired
4918        // defaults — the [`Default for RestartStrategy`] impl arm, the
4919        // struct-literal default arm here, and the
4920        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
4921        // silently split on any future default rebrand). Peer of the
4922        // sibling
4923        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4924        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4925        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
4926        // of the same `SupervisorSpec::default()` composed altitude.
4927        assert_eq!(
4928            SupervisorSpec::default().estrategia(),
4929            SUPERVISOR_ESTRATEGIA_DEFAULT,
4930        );
4931    }
4932
4933    #[test]
4934    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
4935        // Composition pin: the [`Default for SupervisorSpec`] impl must
4936        // route through the substrate-canonical
4937        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
4938        // rather than a re-hand-authored struct-literal cascade. Sharpens
4939        // the sibling per-arm
4940        // `supervisor_spec_default_*_routes_through_lifted_default` pins
4941        // from a per-field lift into a whole-struct one-source-of-truth
4942        // pin — the derived-until-now [`Default::default`] and the
4943        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
4944        // construction, not by coincidence.
4945        //
4946        // A future extension of the OTP-canonical baseline (a fifth
4947        // `restart_intensity` field the Erlang/OTP `#supervisor` record
4948        // grows, a per-child-cohort split of the `restart_window` /
4949        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
4950        // CR materializer's admission-time overlay pass) reaches both
4951        // paths through exactly one edit on
4952        // [`SupervisorSpec::otp_canonical`] — the derived path could
4953        // silently disagree with the constructor's shape on any new
4954        // field whose [`Default::default`] resolves to a different arm
4955        // than the OTP-canonical baseline the constructor names, while
4956        // this delegated impl reaches the constructor directly and
4957        // picks up every future extension by construction.
4958        //
4959        // Fourth peer on the M2 / M3 typed-slot-spec
4960        // [`Default`]-through-const-ctor fold family — sibling of the
4961        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
4962        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
4963        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
4964        // (91641a4), and [`crate::BehaviorSpec`]
4965        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
4966        // per-`Option`-only-typed-slot folds — extended here onto the
4967        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
4968        // is not "everything `None`" but the Erlang/OTP-canonical
4969        // `{one_for_one, 5, 60}` worker-supervisor triple.
4970        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
4971    }
4972
4973    #[test]
4974    fn supervisor_spec_otp_canonical_byte_equals_default() {
4975        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
4976        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
4977        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
4978        // pin already asserts against the [`Default::default`] path.
4979        // Sharpens the pair-invariant into a per-constructor pin so a
4980        // future extension of [`SupervisorSpec`] with a fifth field
4981        // whose OTP-canonical shape is non-`Default::default`-equivalent
4982        // trips at caixa-core test time rather than at a downstream
4983        // consumer that composed [`SupervisorSpec::otp_canonical`] with
4984        // [`SupervisorSpec::validate`] as its "canonical baseline
4985        // seed".
4986        let canonical = SupervisorSpec::otp_canonical();
4987        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
4988        assert_eq!(canonical.max_restarts, 5);
4989        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
4990        assert!(canonical.children.is_empty());
4991    }
4992
4993    #[test]
4994    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
4995        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
4996        // remain callable from a `const`-bound position so downstream
4997        // `const`-context callers wanting a canonical OTP-baseline seed
4998        // can construct one at compile time without runtime dispatch on
4999        // the derived [`Default::default`]. Peer of the sibling
5000        // `pub const fn` [`crate::LimitsSpec::empty`] /
5001        // [`crate::aplicacao::MeshPolicy::empty`] /
5002        // [`crate::BehaviorSpec::empty`] constructors on the sibling
5003        // typed-slot-spec `pub const fn` axis. If a future edit breaks
5004        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
5005        // (a non-`const` field-default helper, a non-`const`-stable
5006        // container type promotion), this evaluation fails at
5007        // build time on this file rather than at a downstream
5008        // `const`-context call site.
5009        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
5010        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
5011        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
5012        assert_eq!(
5013            CANONICAL.restart_window,
5014            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5015        );
5016        assert!(CANONICAL.children.is_empty());
5017    }
5018
5019    #[test]
5020    fn supervisor_child_restart_default_pins_otp_canonical_value() {
5021        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
5022        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
5023        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
5024        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
5025        // half of the same OTP-shape supervisor-tree default set whose
5026        // per-`:supervisor` halves the sibling
5027        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
5028        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
5029        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
5030        // arm here surfaces a future rebrand of the per-child default (an
5031        // OTP-`transient` widening once the substrate discovers clean-
5032        // completion-aware children as the more common child shape, a
5033        // per-cluster overlay the operator pins through a future
5034        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
5035        // supervision-canary roadmap acknowledges) as a deliberate test
5036        // edit, not a silent contract migration. Peer of the sibling
5037        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
5038        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
5039        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5040        // value pins on the per-`:supervisor` halves.
5041        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
5042    }
5043
5044    #[test]
5045    fn restart_policy_default_routes_through_lifted_default() {
5046        // Composition pin: the [`Default for RestartPolicy`] impl's return
5047        // arm must route through the substrate-canonical
5048        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
5049        // than a raw `Self::Permanent` arm. Prior to the lift the impl
5050        // carried an inline `Self::Permanent` with no compile-time link
5051        // back to the OTP-shape supervisor-tree default set whose three
5052        // per-`:supervisor` halves already rode through lifted constants
5053        // — so a future coherent rebrand of the set would have had to
5054        // migrate three halves through typed constants and this fourth
5055        // through a raw enum arm in lockstep or the supervisor-level and
5056        // child-level defaults would silently drift apart. Byte-parity
5057        // against the lifted constant closes the split. Peer of the
5058        // sibling
5059        // [`restart_strategy_default_routes_through_lifted_default`]
5060        // composition pin on the per-`:supervisor` `:estrategia` axis.
5061        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
5062    }
5063
5064    #[test]
5065    fn child_spec_serde_default_restart_routes_through_lifted_default() {
5066        // Composition pin: the serde-side `#[serde(default)]` on
5067        // [`ChildSpec::restart`] — the wire-format author-omitted
5068        // `:children :restart` arm — must resolve onto the substrate-
5069        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
5070        // (via the [`Default for RestartPolicy`] impl the sibling
5071        // `restart_policy_default_routes_through_lifted_default` pin
5072        // already routes onto the constant). Structurally: a `ChildSpec`
5073        // deserialized from a payload that omits the `restart` key must
5074        // yield a `restart` field byte-equal to the lifted constant, so
5075        // the wire-format author-omitted arm and the
5076        // [`RestartPolicy::default`] impl arm cannot silently split on any
5077        // future default rebrand. Peer of the sibling
5078        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
5079        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5080        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5081        // byte-parity pins on the per-`:supervisor` halves of the same
5082        // author-omitted-slot resolution surface.
5083        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
5084            .expect("ChildSpec must deserialize with the restart key omitted");
5085        assert_eq!(
5086            omitted.restart(),
5087            SUPERVISOR_CHILD_RESTART_DEFAULT,
5088            "an author-omitted :children :restart slot must degrade onto \
5089             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
5090             {:?}, expected {:?})",
5091            omitted.restart(),
5092            SUPERVISOR_CHILD_RESTART_DEFAULT,
5093        );
5094    }
5095
5096    #[test]
5097    fn supervisor_max_restarts_cap_pins_canonical_value() {
5098        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
5099        // 1000 — the same ceiling the peer
5100        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
5101        // `:politicas :circuit-breaker :max-failures` axis (both are
5102        // "trip the next-higher protection layer after N events in a
5103        // rolling window" counters with identical
5104        // degenerate-at-the-high-end shape; uniform top edge so the
5105        // M4 CR materializers and the wasm-operator reconciler reach
5106        // for either field knowing the value is in `1..=1000`). Two
5107        // orders of magnitude above every documented Erlang/OTP /
5108        // Elixir / Riak Core / RabbitMQ production-playbook
5109        // recommendation band and below the clearly-pathological
5110        // "effectively no escalation" floor (10_000, 100_000,
5111        // u32::MAX). Pinning the literal value here surfaces a future
5112        // drift (a relaxation to 10_000, a tightening to 100) as a
5113        // deliberate test edit, not a silent contract narrowing.
5114        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
5115    }
5116
5117    #[test]
5118    fn validate_rejects_empty_child_name() {
5119        let s = SupervisorSpec {
5120            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5121            ..SupervisorSpec::default()
5122        };
5123        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
5124    }
5125
5126    #[test]
5127    fn validate_rejects_empty_child_version() {
5128        let s = SupervisorSpec {
5129            children: vec![child("w", "", RestartPolicy::Permanent)],
5130            ..SupervisorSpec::default()
5131        };
5132        assert!(matches!(
5133            s.validate().unwrap_err(),
5134            SupervisorError::EmptyChildVersion { .. }
5135        ));
5136    }
5137
5138    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
5139
5140    #[test]
5141    fn validate_rejects_invalid_child_versao_requirement() {
5142        // The fail-before-pass-after pin: a non-empty but malformed
5143        // semver requirement (`"^bad-version"`) silently passed
5144        // `validate()` on every pre-gate codebase because the prior
5145        // shape only refused the empty string. The parse failure
5146        // surfaced far downstream at lacre-resolve time with a
5147        // `semver::Error` that didn't name which `:children` entry
5148        // carried the typo. The new gate moves the check to caixa-build
5149        // time at the source caixa.lisp — the third `:versao` typed
5150        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
5151        // structural parity.
5152        let s = SupervisorSpec {
5153            children: vec![
5154                child("worker", "^0.1", RestartPolicy::Permanent),
5155                child("cache", "^bad-version", RestartPolicy::Transient),
5156            ],
5157            ..SupervisorSpec::default()
5158        };
5159        let err = s.validate().unwrap_err();
5160        assert!(
5161            matches!(
5162                err,
5163                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5164                    if caixa == "cache" && versao == "^bad-version"
5165            ),
5166            "got {err:?}"
5167        );
5168    }
5169
5170    #[test]
5171    fn validate_rejects_child_versao_with_double_caret_typo() {
5172        // `"^^0.1"` is the canonical doubled-caret typo — looks
5173        // Cargo-shaped on first glance but fails the parser because
5174        // semver doesn't accept stacked operators. Pin this
5175        // adjacent-shape footgun explicitly so a future relaxation that
5176        // accepts "looks-canonical-but-isn't" forms surfaces here.
5177        let s = SupervisorSpec {
5178            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
5179            ..SupervisorSpec::default()
5180        };
5181        let err = s.validate().unwrap_err();
5182        assert!(
5183            matches!(
5184                err,
5185                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5186                    if caixa == "worker" && versao == "^^0.1"
5187            ),
5188            "got {err:?}"
5189        );
5190    }
5191
5192    #[test]
5193    fn validate_rejects_child_versao_with_v_prefixed_tag() {
5194        // `"v0.1"` is the canonical "git-tag-shape leaking into the
5195        // semver requirement slot" typo — an author copies the
5196        // publish-side git-tag string verbatim into `:versao`, but
5197        // Cargo's semver parser rejects the leading `v`. Same
5198        // adjacent-shape footgun pinned for `:membros :versao`
5199        // (9888b13).
5200        let s = SupervisorSpec {
5201            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
5202            ..SupervisorSpec::default()
5203        };
5204        let err = s.validate().unwrap_err();
5205        assert!(
5206            matches!(
5207                err,
5208                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5209                    if caixa == "worker" && versao == "v0.1"
5210            ),
5211            "got {err:?}"
5212        );
5213    }
5214
5215    #[test]
5216    fn validate_accepts_canonical_child_versao_forms() {
5217        // The Cargo-shaped requirement forms `:deps :versao` and
5218        // `:membros :versao` already accept via
5219        // `crate::parse_requirement` must pass the children gate
5220        // without re-validating at the resolver layer. Pin every leg so
5221        // a future tightening of the canonical set surfaces here as a
5222        // test failure.
5223        for form in [
5224            "^0.1",      // caret — minor-range pin (the most common shape)
5225            "~0.1.2",    // tilde — patch-range pin
5226            "0.1.0",     // exact — single-version pin
5227            "*",         // wildcard — any version (semver::VersionReq::STAR)
5228            ">=0.1, <2", // multi-range — comma-separated comparators
5229        ] {
5230            let s = SupervisorSpec {
5231                children: vec![child("worker", form, RestartPolicy::Permanent)],
5232                ..SupervisorSpec::default()
5233            };
5234            s.validate()
5235                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5236        }
5237    }
5238
5239    #[test]
5240    fn child_versao_empty_takes_precedence_over_invalid() {
5241        // Order pin: the existing `EmptyChildVersion` diagnostic (which
5242        // doesn't try to parse) fires before the new
5243        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
5244        // `:versao` keeps its narrower error message —
5245        // `parse_requirement` would also reject `""`, but the
5246        // empty-string arm is the more self-locating diagnostic for the
5247        // author. Same ordering discipline as
5248        // `membro_versao_empty_takes_precedence_over_invalid` in
5249        // aplicacao.rs.
5250        let s = SupervisorSpec {
5251            children: vec![child("worker", "", RestartPolicy::Permanent)],
5252            ..SupervisorSpec::default()
5253        };
5254        let err = s.validate().unwrap_err();
5255        assert!(
5256            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
5257            "got {err:?}"
5258        );
5259    }
5260
5261    #[test]
5262    fn child_versao_invalid_fires_before_duplicate_check() {
5263        // Order pin: a malformed requirement on a non-duplicate entry
5264        // surfaces *its own* diagnostic (which names the offending
5265        // `:versao` string), even when a later entry would otherwise
5266        // collapse onto an earlier name. The per-entry shape gate runs
5267        // inline before the duplicate-key insert — parallel to
5268        // `membro_versao_invalid_fires_before_duplicate_check` in
5269        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
5270        let s = SupervisorSpec {
5271            children: vec![
5272                child("worker", "^bad", RestartPolicy::Permanent),
5273                child("cache", "^0.1", RestartPolicy::Transient),
5274                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5275            ],
5276            ..SupervisorSpec::default()
5277        };
5278        let err = s.validate().unwrap_err();
5279        assert!(
5280            matches!(
5281                err,
5282                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
5283            ),
5284            "got {err:?}"
5285        );
5286    }
5287
5288    #[test]
5289    fn child_versao_invalid_diagnostic_carries_offending_versao() {
5290        // The diagnostic-shape pin: the error names the offending
5291        // `:versao` value verbatim so the author can grep their
5292        // caixa.lisp without re-running the build, and carries a
5293        // non-empty `reason` from `semver::VersionReq::parse` so the
5294        // parser's own wording flows through to the diagnostic.
5295        let s = SupervisorSpec {
5296            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
5297            ..SupervisorSpec::default()
5298        };
5299        let err = s.validate().unwrap_err();
5300        let SupervisorError::ChildVersaoInvalid {
5301            caixa,
5302            versao,
5303            reason,
5304        } = err
5305        else {
5306            panic!("expected ChildVersaoInvalid, got other variant");
5307        };
5308        assert_eq!(caixa, "worker");
5309        assert_eq!(versao, "not-a-req");
5310        assert!(
5311            !reason.is_empty(),
5312            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
5313        );
5314    }
5315
5316    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
5317
5318    #[test]
5319    fn validate_rejects_child_caixa_with_uppercase() {
5320        // The canonical "I copied the Servico's display name verbatim"
5321        // typo — child caixa names are lowercase per K8s DNS-1123 label
5322        // rule. The diagnostic names the offending name and suggests the
5323        // lower-cased fix in one edit, mirroring the
5324        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
5325        let s = SupervisorSpec {
5326            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
5327            ..SupervisorSpec::default()
5328        };
5329        let err = s.validate().unwrap_err();
5330        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5331            panic!("expected ChildCaixaInvalid, got other variant");
5332        };
5333        assert_eq!(caixa, "Worker");
5334        assert!(
5335            reason.contains("uppercase"),
5336            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
5337        );
5338        assert!(
5339            reason.contains("\"worker\""),
5340            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
5341        );
5342    }
5343
5344    #[test]
5345    fn validate_rejects_child_caixa_with_underscore() {
5346        // The canonical "I'm thinking of a Python module / Postgres
5347        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
5348        // label schema. K8s rejects `metadata.name: my_worker` at
5349        // admission time with an opaque `field is invalid` (no source-
5350        // citing diagnostic). The gate moves it to caixa-build time.
5351        let s = SupervisorSpec {
5352            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
5353            ..SupervisorSpec::default()
5354        };
5355        let err = s.validate().unwrap_err();
5356        assert!(
5357            matches!(
5358                err,
5359                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5360                    if caixa == "my_worker" && reason.contains('_')
5361            ),
5362            "got {err:?}"
5363        );
5364    }
5365
5366    #[test]
5367    fn validate_rejects_child_caixa_with_dot() {
5368        // A `:children :caixa` entry is a single DNS-1123 label, not a
5369        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
5370        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
5371        // (3f9d7a0) on the peer name axis.
5372        let s = SupervisorSpec {
5373            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
5374            ..SupervisorSpec::default()
5375        };
5376        let err = s.validate().unwrap_err();
5377        assert!(
5378            matches!(
5379                err,
5380                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5381                    if caixa == "team.worker" && reason.contains('.')
5382            ),
5383            "got {err:?}"
5384        );
5385    }
5386
5387    #[test]
5388    fn validate_rejects_child_caixa_with_leading_hyphen() {
5389        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
5390        // with an alphanumeric. The K8s apiserver rejects `-worker`
5391        // outright; the renderer would emit a `metadata.name: "-worker"`
5392        // that fails admission far from the source caixa.lisp.
5393        let s = SupervisorSpec {
5394            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
5395            ..SupervisorSpec::default()
5396        };
5397        let err = s.validate().unwrap_err();
5398        assert!(
5399            matches!(
5400                err,
5401                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5402                    if caixa == "-worker" && reason.contains("start and end")
5403            ),
5404            "got {err:?}"
5405        );
5406    }
5407
5408    #[test]
5409    fn validate_rejects_child_caixa_with_trailing_hyphen() {
5410        // The symmetric arm of the boundary rule. Pin separately so
5411        // both ends of the label are covered against a future relaxation
5412        // that only checks one boundary.
5413        let s = SupervisorSpec {
5414            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
5415            ..SupervisorSpec::default()
5416        };
5417        let err = s.validate().unwrap_err();
5418        assert!(
5419            matches!(
5420                err,
5421                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5422                    if caixa == "worker-"
5423            ),
5424            "got {err:?}"
5425        );
5426    }
5427
5428    #[test]
5429    fn validate_rejects_child_caixa_with_unicode() {
5430        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
5431        // (`xn--…`) by the author before it reaches K8s. The byte-by-
5432        // byte ASCII validity check rejects multi-byte UTF-8 sequences
5433        // by the first byte that fails the `[a-z0-9-]` predicate.
5434        let s = SupervisorSpec {
5435            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
5436            ..SupervisorSpec::default()
5437        };
5438        let err = s.validate().unwrap_err();
5439        assert!(
5440            matches!(
5441                err,
5442                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5443                    if caixa == "café"
5444            ),
5445            "got {err:?}"
5446        );
5447    }
5448
5449    #[test]
5450    fn validate_rejects_child_caixa_with_whitespace() {
5451        // Whitespace is the canonical "I pasted from a sketch / doc"
5452        // footgun. The apiserver rejects every `metadata.name` value
5453        // carrying whitespace; pin the gate fires at the right boundary.
5454        let s = SupervisorSpec {
5455            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
5456            ..SupervisorSpec::default()
5457        };
5458        let err = s.validate().unwrap_err();
5459        assert!(
5460            matches!(
5461                err,
5462                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5463                    if caixa == "my worker"
5464            ),
5465            "got {err:?}"
5466        );
5467    }
5468
5469    #[test]
5470    fn validate_rejects_child_caixa_too_long() {
5471        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
5472        // 63 bytes; the K8s apiserver rejects every `metadata.name`
5473        // axis over the limit at admission time. The diagnostic names
5474        // both the cap and the actual length so the author can shorten
5475        // in one edit, mirroring `rejects_membro_caixa_too_long`
5476        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
5477        let too_long = "a".repeat(64);
5478        let s = SupervisorSpec {
5479            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
5480            ..SupervisorSpec::default()
5481        };
5482        let err = s.validate().unwrap_err();
5483        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5484            panic!("expected ChildCaixaInvalid, got other variant");
5485        };
5486        assert_eq!(caixa, too_long);
5487        assert!(
5488            reason.contains("63"),
5489            "diagnostic must name the 63-byte cap (got: {reason:?})"
5490        );
5491        assert!(
5492            reason.contains("64"),
5493            "diagnostic must name the actual length (got: {reason:?})"
5494        );
5495    }
5496
5497    #[test]
5498    fn child_caixa_max_length_validates() {
5499        // The 63-byte boundary control pin — exactly-at-the-cap is
5500        // accepted, mirroring `membro_caixa_max_length_validates`
5501        // (3f9d7a0) and `placement_cluster_max_length_validates`
5502        // (6cbb900). Pinned separately so a future off-by-one tightening
5503        // surfaces here.
5504        let max_label = "a".repeat(63);
5505        let s = SupervisorSpec {
5506            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
5507            ..SupervisorSpec::default()
5508        };
5509        s.validate().unwrap();
5510    }
5511
5512    #[test]
5513    fn validate_accepts_canonical_child_caixa_forms() {
5514        // The realistic shapes a supervised child's `:caixa` carries —
5515        // single-word `worker`, version-suffixed `cache-v2`, single-char
5516        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
5517        // `payment-retry`, all-digit `0`. Pin every leg so a future
5518        // tightening (e.g. requiring a leading lowercase letter) surfaces
5519        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
5520        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
5521        // (6cbb900).
5522        for form in [
5523            "worker",
5524            "cache-v2",
5525            "a",
5526            "db",
5527            "2-pool",
5528            "payment-retry",
5529            "0",
5530        ] {
5531            let s = SupervisorSpec {
5532                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
5533                ..SupervisorSpec::default()
5534            };
5535            s.validate()
5536                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5537        }
5538    }
5539
5540    #[test]
5541    fn child_caixa_empty_takes_precedence_over_invalid() {
5542        // Order pin: the existing `EmptyChildName` diagnostic (which
5543        // doesn't try to parse the DNS-1123 shape) fires before the new
5544        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
5545        // its narrower error message — `is_dns_1123_label` would reject
5546        // the empty string too (boundary check on the first byte), but
5547        // the empty-string arm is the more self-locating diagnostic for
5548        // the author. Same ordering discipline as
5549        // `membro_caixa_empty_takes_precedence_over_invalid` in
5550        // aplicacao.rs.
5551        let s = SupervisorSpec {
5552            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5553            ..SupervisorSpec::default()
5554        };
5555        let err = s.validate().unwrap_err();
5556        assert_eq!(err, SupervisorError::EmptyChildName);
5557    }
5558
5559    #[test]
5560    fn child_caixa_invalid_fires_before_versao_check() {
5561        // Order pin: the per-axis shape gate runs inline before the
5562        // per-entry versao check, so a malformed `:caixa` on an entry
5563        // whose `:versao` would also fail surfaces the more self-
5564        // locating name-axis diagnostic first. Parallel to
5565        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
5566        // and `placement_cluster_invalid_fires_before_duplicate_check`
5567        // (6cbb900).
5568        let s = SupervisorSpec {
5569            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
5570            ..SupervisorSpec::default()
5571        };
5572        let err = s.validate().unwrap_err();
5573        assert!(
5574            matches!(
5575                err,
5576                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
5577            ),
5578            "got {err:?}"
5579        );
5580    }
5581
5582    #[test]
5583    fn child_caixa_invalid_fires_before_duplicate_check() {
5584        // Order pin: a malformed name on a non-duplicate entry surfaces
5585        // its own diagnostic, even when a later entry would otherwise
5586        // collapse onto an earlier name. The per-entry shape gate runs
5587        // inline before the duplicate-key HashSet insert, mirroring
5588        // `placement_cluster_invalid_fires_before_duplicate_check`
5589        // (6cbb900).
5590        let s = SupervisorSpec {
5591            children: vec![
5592                child("Worker", "^0.1", RestartPolicy::Permanent),
5593                child("cache", "^0.1", RestartPolicy::Transient),
5594                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5595            ],
5596            ..SupervisorSpec::default()
5597        };
5598        let err = s.validate().unwrap_err();
5599        assert!(
5600            matches!(
5601                err,
5602                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
5603            ),
5604            "got {err:?}"
5605        );
5606    }
5607
5608    #[test]
5609    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
5610        // The diagnostic-shape pin: the error names the offending
5611        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
5612        // the author can grep their caixa.lisp without re-running the
5613        // build. Mirrors the diagnostic-shape sweep on every prior
5614        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
5615        let s = SupervisorSpec {
5616            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
5617            ..SupervisorSpec::default()
5618        };
5619        let err = s.validate().unwrap_err();
5620        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5621            panic!("expected ChildCaixaInvalid, got other variant");
5622        };
5623        assert_eq!(caixa, "My_Worker");
5624        assert!(
5625            !reason.is_empty(),
5626            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
5627        );
5628    }
5629
5630    // ── value-shape: zero restart_window + duplicate child names ──────────
5631
5632    #[test]
5633    fn validate_accepts_none_restart_window() {
5634        // Omitted `:restart-window` is the "never reset" sentinel —
5635        // valid by design. Mirrors :limits axes where None = unbounded.
5636        let s = SupervisorSpec {
5637            restart_window: None,
5638            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5639            ..SupervisorSpec::default()
5640        };
5641        s.validate().unwrap();
5642    }
5643
5644    #[test]
5645    fn validate_rejects_zero_restart_window() {
5646        // Same "0 means the opposite of what you think" footgun closed
5647        // for :politicas :timeout (Envoy treats 0s as infinite) and
5648        // :limits :wall-clock (wasmtime traps before the call starts).
5649        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
5650        let s = SupervisorSpec {
5651            restart_window: Some(Duration::ZERO),
5652            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5653            ..SupervisorSpec::default()
5654        };
5655        assert_eq!(
5656            s.validate().unwrap_err(),
5657            SupervisorError::RestartWindowZero
5658        );
5659    }
5660
5661    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
5662    //
5663    // The fourth (and last) typed-`Duration` axis in caixa-core to get
5664    // the integer-millisecond canonical-form gate — peer with
5665    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
5666    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
5667    // path is already gated at the shared codec layer (see
5668    // `restart_window_serde_rejects_fractional_seconds`); this arm
5669    // closes the programmatic-struct-literal path the codec gate can't
5670    // see.
5671
5672    #[test]
5673    fn validate_rejects_sub_millisecond_restart_window() {
5674        // The fail-before-pass-after pin: a programmatic
5675        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
5676        // `validate` on every pre-gate codebase, then truncated to
5677        // `as_millis() == 1` on first serialize — the shared codec
5678        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
5679        // 1_000_000 ns, the typed `restart_window` no longer matches
5680        // its rendered form.
5681        let s = SupervisorSpec {
5682            restart_window: Some(Duration::from_micros(1500)),
5683            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5684            ..SupervisorSpec::default()
5685        };
5686        match s.validate().unwrap_err() {
5687            SupervisorError::RestartWindowNotCanonical { window } => {
5688                assert_eq!(window, Duration::from_micros(1500));
5689            }
5690            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5691        }
5692    }
5693
5694    #[test]
5695    fn validate_rejects_one_nanosecond_restart_window() {
5696        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
5697        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
5698        // so the shared codec emits the literal `"0s"` — the next
5699        // serde round-trip would parse back to `Duration::ZERO`, which
5700        // the `RestartWindowZero` arm then rejects on re-validate. The
5701        // canonical-form gate at this layer surfaces a self-locating
5702        // diagnostic naming the offending Duration verbatim rather
5703        // than a downstream `RestartWindowZero` whose remediation
5704        // points at omitting the slot.
5705        let s = SupervisorSpec {
5706            restart_window: Some(Duration::from_nanos(1)),
5707            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5708            ..SupervisorSpec::default()
5709        };
5710        match s.validate().unwrap_err() {
5711            SupervisorError::RestartWindowNotCanonical { window } => {
5712                assert_eq!(window, Duration::from_nanos(1));
5713            }
5714            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5715        }
5716    }
5717
5718    #[test]
5719    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
5720        // The 1-ns-past-1ms boundary case: a `Duration` carrying
5721        // 1_000_001 ns is structurally past the integer-ms granularity
5722        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
5723        // trip would truncate to `1ms` and the consumer would observe
5724        // a 1-ns drift on every emit. Same boundary the peer
5725        // `validate_rejects_nanosecond_past_canonical_boundary` test
5726        // in limits.rs pins for the `:limits :wall-clock` axis.
5727        let w = Duration::from_nanos(1_000_001);
5728        let s = SupervisorSpec {
5729            restart_window: Some(w),
5730            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5731            ..SupervisorSpec::default()
5732        };
5733        assert_eq!(
5734            s.validate().unwrap_err(),
5735            SupervisorError::RestartWindowNotCanonical { window: w }
5736        );
5737    }
5738
5739    #[test]
5740    fn validate_accepts_integer_millisecond_restart_window_values() {
5741        // The positive-control sweep: every `Duration` the shared
5742        // codec can round-trip losslessly — the canonical
5743        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
5744        // pair emits and accepts — passes `validate` without
5745        // surfacing the new canonical-form arm. Mirrors
5746        // `validate_accepts_integer_millisecond_wall_clock_values` on
5747        // the sibling `:limits :wall-clock` axis.
5748        for w in [
5749            Duration::from_millis(1),
5750            Duration::from_millis(500),
5751            Duration::from_millis(1500),
5752            Duration::from_secs(1),
5753            Duration::from_secs(30),
5754            Duration::from_secs(60),
5755            Duration::from_secs(120),
5756            Duration::from_secs(3600),
5757        ] {
5758            let s = SupervisorSpec {
5759                restart_window: Some(w),
5760                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5761                ..SupervisorSpec::default()
5762            };
5763            s.validate()
5764                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
5765        }
5766    }
5767
5768    #[test]
5769    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
5770        // Cross-arm ordering pin: `Duration::ZERO` has
5771        // `subsec_nanos() == 0` and would otherwise pass the
5772        // canonical-form arm — the zero-floor arm must fire first so
5773        // the more self-locating `RestartWindowZero` diagnostic (with
5774        // its omit-axis remediation directly named) leads. Same
5775        // posture every peer zero-then-shape gate uses
5776        // (`WallClockZero` → `WallClockNotCanonical`,
5777        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
5778        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
5779        let s = SupervisorSpec {
5780            restart_window: Some(Duration::ZERO),
5781            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5782            ..SupervisorSpec::default()
5783        };
5784        assert_eq!(
5785            s.validate().unwrap_err(),
5786            SupervisorError::RestartWindowZero
5787        );
5788    }
5789
5790    #[test]
5791    fn restart_window_canonical_diagnostic_carries_offending_duration() {
5792        // Diagnostic-shape pin: the canonical-form arm names the
5793        // offending `Duration` verbatim so the author's grep lands on
5794        // the field's value, not a generic "duration not canonical"
5795        // message. Same shape every other typed-canonical-form arm
5796        // on this surface carries (`WallClockNotCanonical` carries
5797        // the offending `Duration` verbatim,
5798        // `PolicyTimeoutNotCanonical` carries the offending
5799        // `Duration` verbatim).
5800        let w = Duration::from_micros(500);
5801        let s = SupervisorSpec {
5802            restart_window: Some(w),
5803            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5804            ..SupervisorSpec::default()
5805        };
5806        let err = s.validate().unwrap_err();
5807        let msg = err.to_string();
5808        assert!(
5809            msg.contains("500"),
5810            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
5811        );
5812        assert!(
5813            msg.contains("sub-millisecond"),
5814            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
5815        );
5816    }
5817
5818    #[test]
5819    fn restart_window_validated_value_round_trips_through_codec() {
5820        // The structural property the canonical-ms gate enforces:
5821        // every `SupervisorSpec::restart_window` past
5822        // `SupervisorSpec::validate` round-trips losslessly through
5823        // the shared duration codec (serialize → string →
5824        // deserialize → equal value). Pin this end-to-end so a future
5825        // change to either side (the validate gate's accepted
5826        // granularity, the codec's parse/render unit set) that breaks
5827        // the alignment surfaces here. Peer of
5828        // `wall_clock_validated_value_round_trips_through_codec` on
5829        // the sibling `:limits :wall-clock` axis.
5830        for w in [
5831            Duration::from_millis(1),
5832            Duration::from_millis(1500),
5833            Duration::from_secs(30),
5834            Duration::from_secs(3600),
5835        ] {
5836            let s = SupervisorSpec {
5837                restart_window: Some(w),
5838                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5839                ..SupervisorSpec::default()
5840            };
5841            s.validate().unwrap();
5842            let json = serde_json::to_string(&s).unwrap();
5843            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5844            assert_eq!(back.restart_window, Some(w));
5845        }
5846    }
5847
5848    // ── value-shape: upper cap on :restart-window ─────────────────────────
5849    //
5850    // The fourth (and last) typed-`Duration` axis in caixa-core to get
5851    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
5852    // `:politicas :timeout` (2e8ee7e), and `:politicas
5853    // :circuit-breaker :window` (379a814). Brackets the typed
5854    // `:restart-window` axis structurally: every validated value lies
5855    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
5856    // granularity, closing the
5857    // rolling-window-degenerates-to-lifetime-counter footgun the prior
5858    // zero-floor-and-canonical-form-only checks left open.
5859
5860    #[test]
5861    fn validate_rejects_restart_window_above_cap() {
5862        // The fail-before-pass-after pin: 3601s = 1h + 1s is
5863        // structurally one canonical-tick past the
5864        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
5865        // integer-millisecond magnitude the canonical-form arm above
5866        // accepts cleanly, that the shared duration codec round-trips
5867        // losslessly as `"3601s"`, and that silently passed validate on
5868        // every pre-gate codebase because the typed slot's only checks
5869        // were the zero-floor and canonical-form arms. The runtime
5870        // substrate consuming the value (Erlang/OTP's MaxIntensity/
5871        // Period reconciler, the future wasm-operator's per-supervisor
5872        // restart-intensity counter) reaches for a `Duration` so long
5873        // no realistic restart-recovery pattern resets the counter,
5874        // far from the source caixa.lisp.
5875        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5876        let s = SupervisorSpec {
5877            restart_window: Some(w),
5878            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5879            ..SupervisorSpec::default()
5880        };
5881        assert_eq!(
5882            s.validate().unwrap_err(),
5883            SupervisorError::RestartWindowExceedsCap { window: w }
5884        );
5885    }
5886
5887    #[test]
5888    fn validate_rejects_restart_window_one_millisecond_above_cap() {
5889        // Boundary case: exactly 1ms past the cap (the granularity the
5890        // canonical-form gate enforces). Catches a future "strictly
5891        // less than" half-measure and pins the diagnostic to name the
5892        // offending `Duration` verbatim. Peer of
5893        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
5894        // `rejects_policy_timeout_one_millisecond_above_cap` /
5895        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
5896        // on the sibling typed-`Duration` axes' top edges.
5897        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
5898        let s = SupervisorSpec {
5899            restart_window: Some(w),
5900            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5901            ..SupervisorSpec::default()
5902        };
5903        assert_eq!(
5904            s.validate().unwrap_err(),
5905            SupervisorError::RestartWindowExceedsCap { window: w }
5906        );
5907    }
5908
5909    #[test]
5910    fn validate_rejects_restart_window_far_above_cap() {
5911        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
5912        // `(:restart-window "7d")`, or any "I want a lifetime counter
5913        // but wrote a `<integer>h` magnitude anyway" typo — values the
5914        // canonical-form arm accepts as integer-millisecond magnitudes,
5915        // the codec round-trips losslessly through serde, but the
5916        // operator's `MaxIntensity / Period` reconciler cannot honor
5917        // as a meaningful rolling window. Until this gate landed
5918        // validate accepted them. Pin the common above-cap values (24h,
5919        // 7d, ~11.5d) so a future relaxation that drops the upper bound
5920        // surfaces here.
5921        for w in [
5922            Duration::from_secs(86_400),    // 24h
5923            Duration::from_secs(604_800),   // 7d
5924            Duration::from_secs(1_000_000), // ~11.5 days
5925        ] {
5926            let s = SupervisorSpec {
5927                restart_window: Some(w),
5928                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5929                ..SupervisorSpec::default()
5930            };
5931            assert_eq!(
5932                s.validate().unwrap_err(),
5933                SupervisorError::RestartWindowExceedsCap { window: w }
5934            );
5935        }
5936    }
5937
5938    #[test]
5939    fn validate_accepts_restart_window_at_cap() {
5940        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
5941        // (1h) — must validate. The cap is inclusive on the top edge,
5942        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
5943        // [`crate::POLICY_TIMEOUT_MAX`] /
5944        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
5945        // capped axes. Pin the boundary explicitly so a future
5946        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
5947        // instead of `>`) surfaces here as a test failure rather than a
5948        // silent contract narrowing.
5949        let s = SupervisorSpec {
5950            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5951            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5952            ..SupervisorSpec::default()
5953        };
5954        s.validate()
5955            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
5956    }
5957
5958    #[test]
5959    fn validate_accepts_restart_window_typical_values() {
5960        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
5961        // per-supervisor production-playbook band positive-control
5962        // sweep — every value Learn You Some Erlang's `{intensity, 5,
5963        // 60}` worker-supervisor `Period = 60s` default, Elixir's
5964        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
5965        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
5966        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
5967        // default recommend (5s..=300s) must pass, plus a sweep
5968        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
5969        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
5970        // on the sibling `:limits :wall-clock` axis.
5971        for w in [
5972            Duration::from_millis(1),
5973            Duration::from_millis(500),
5974            Duration::from_secs(1),
5975            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
5976            Duration::from_secs(10), // Riak Core lower
5977            Duration::from_secs(30),
5978            Duration::from_secs(60),  // Learn You Some Erlang default
5979            Duration::from_secs(120), // OTP supervisor MaxT typical
5980            Duration::from_secs(300), // Riak Core upper
5981            Duration::from_secs(900), // 15m
5982            Duration::from_secs(1800),
5983            Duration::from_secs(3600), // exactly 1h, the cap
5984        ] {
5985            let s = SupervisorSpec {
5986                restart_window: Some(w),
5987                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5988                ..SupervisorSpec::default()
5989            };
5990            s.validate()
5991                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
5992        }
5993    }
5994
5995    #[test]
5996    fn restart_window_zero_takes_precedence_over_cap() {
5997        // The cross-arm ordering pin: `Duration::ZERO` is structurally
5998        // outside both `>= 1ms` (zero-floor) and `<=
5999        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
6000        // diagnostic is the more self-locating one (it directly names
6001        // the omit-axis remediation), so the validate gate must fire
6002        // on zero first. Same shape every other zero-then-cap ordering
6003        // on this surface uses (`WallClockZero` then
6004        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
6005        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
6006        // `PolicyBreakerWindowExceedsCap`).
6007        let s = SupervisorSpec {
6008            restart_window: Some(Duration::ZERO),
6009            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6010            ..SupervisorSpec::default()
6011        };
6012        assert_eq!(
6013            s.validate().unwrap_err(),
6014            SupervisorError::RestartWindowZero,
6015            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
6016        );
6017    }
6018
6019    #[test]
6020    fn restart_window_canonical_takes_precedence_over_cap() {
6021        // The cross-arm ordering pin: a `Duration` that is *both*
6022        // sub-millisecond (non-canonical-form) and structurally above
6023        // the cap surfaces the canonical-form diagnostic first,
6024        // because the round-trip-shape break is the more fundamental
6025        // issue (the value can't even round-trip through the codec,
6026        // so the cap diagnostic naming `1ms..=1h` would be misleading
6027        // — there's no integer-ms form of the offending value). Pin
6028        // the order so a future refactor that reorders the arms
6029        // surfaces here as a test failure rather than a silent
6030        // diagnostic regression. Peer of
6031        // `wall_clock_canonical_takes_precedence_over_cap` /
6032        // `policy_timeout_canonical_takes_precedence_over_cap`.
6033        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
6034        let s = SupervisorSpec {
6035            restart_window: Some(w),
6036            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6037            ..SupervisorSpec::default()
6038        };
6039        assert_eq!(
6040            s.validate().unwrap_err(),
6041            SupervisorError::RestartWindowNotCanonical { window: w },
6042            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
6043        );
6044    }
6045
6046    #[test]
6047    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
6048        // The cross-arm ordering pin between the `:max-restarts` cap
6049        // and the sibling `:restart-window` cap. A supervisor carrying
6050        // both an over-cap `max_restarts` AND an over-cap window must
6051        // surface the `MaxRestartsExceedsCap` diagnostic first — the
6052        // cap arm is wired immediately after the zero-restart arm and
6053        // strictly before every window-axis arm (zero / canonical /
6054        // cap), so the offending value the diagnostic names matches
6055        // the order the author would discover the gates by reading
6056        // top-to-bottom through `SupervisorSpec::validate`. Pin the
6057        // order so a future refactor that reorders the arms surfaces
6058        // here as a test failure rather than a silent diagnostic
6059        // regression. Peer of
6060        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
6061        // on the sibling zero / canonical window arms.
6062        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6063        let s = SupervisorSpec {
6064            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6065            restart_window: Some(w),
6066            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6067            ..SupervisorSpec::default()
6068        };
6069        assert_eq!(
6070            s.validate().unwrap_err(),
6071            SupervisorError::MaxRestartsExceedsCap {
6072                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6073            },
6074            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
6075        );
6076    }
6077
6078    #[test]
6079    fn restart_window_cap_diagnostic_carries_offending_value() {
6080        // The diagnostic-shape pin: the offending `Duration` is
6081        // carried verbatim into the
6082        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
6083        // surfaced error message names the value the author wrote,
6084        // not just the cap. Same self-locating diagnostic shape every
6085        // other typed-cap arm on this surface carries
6086        // (`WallClockExceedsCap` carries the offending `Duration`
6087        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
6088        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
6089        // the offending `Duration` verbatim).
6090        let w = Duration::from_secs(7200); // 2h
6091        let s = SupervisorSpec {
6092            restart_window: Some(w),
6093            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6094            ..SupervisorSpec::default()
6095        };
6096        let err = s.validate().unwrap_err();
6097        assert!(
6098            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
6099            "got {err:?}"
6100        );
6101        let msg = err.to_string();
6102        assert!(
6103            msg.contains("7200"),
6104            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
6105        );
6106    }
6107
6108    #[test]
6109    fn supervisor_restart_window_cap_pins_canonical_value() {
6110        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
6111        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
6112        // shared duration codec emits as a clean canonical string
6113        // (`"<n>h"`). Pinning the literal value here surfaces a future
6114        // drift (a relaxation to 24h, a tightening to 5m) as a
6115        // deliberate test edit, not a silent contract narrowing.
6116        //
6117        // The four typed-`Duration` caps on the validation surface
6118        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
6119        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
6120        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
6121        // single uniform top edge at the codec's largest emitted unit
6122        // — a structural-property invariant the equality assertions
6123        // here enshrine, so a future drift on any of the four
6124        // surfaces as a deliberate test edit. Same shape every other
6125        // typed-cap value pin uses
6126        // (`wall_clock_cap_pins_canonical_value`,
6127        // `policy_timeout_cap_pins_canonical_value`,
6128        // `circuit_breaker_window_cap_pins_canonical_value`).
6129        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
6130        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
6131        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
6132        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
6133        assert_eq!(
6134            SUPERVISOR_RESTART_WINDOW_MAX,
6135            crate::POLICY_BREAKER_WINDOW_MAX
6136        );
6137    }
6138
6139    #[test]
6140    fn restart_window_cap_value_round_trips_through_codec() {
6141        // The codec round-trip property the cap arm preserves: the
6142        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
6143        // through the shared duration codec — every value at the cap
6144        // serializes to the canonical `"1h"` form and parses back
6145        // identically. Pin the round-trip so a future change to the
6146        // codec's unit set or to the cap's magnitude that breaks the
6147        // round-trip property surfaces here. Peer of
6148        // `wall_clock_cap_value_round_trips_through_codec` on the
6149        // sibling `:limits :wall-clock` axis.
6150        let s = SupervisorSpec {
6151            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6152            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6153            ..SupervisorSpec::default()
6154        };
6155        s.validate().unwrap();
6156        let json = serde_json::to_string(&s).unwrap();
6157        assert!(
6158            json.contains("\"1h\""),
6159            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
6160        );
6161        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6162        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
6163    }
6164
6165    #[test]
6166    fn validate_rejects_duplicate_child_caixa() {
6167        // Two children with the same :caixa render to two ComputeUnits
6168        // with the same name in the cluster's HelmRelease values —
6169        // one silently overwrites the other. Erlang/OTP's child_spec.id
6170        // is required-unique per supervisor; same set-not-multiset
6171        // discipline applied here as for :membros / :placement
6172        // :clusters / :entrada :paths.
6173        let s = SupervisorSpec {
6174            children: vec![
6175                child("worker", "^0.1", RestartPolicy::Permanent),
6176                child("cache", "^0.1", RestartPolicy::Transient),
6177                child("worker", "^0.2", RestartPolicy::Permanent),
6178            ],
6179            ..SupervisorSpec::default()
6180        };
6181        let err = s.validate().unwrap_err();
6182        assert!(
6183            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
6184            "got {err:?}"
6185        );
6186    }
6187
6188    #[test]
6189    fn validate_duplicate_child_diagnostic_names_first_collision() {
6190        // Iteration walks the :children list in declaration order —
6191        // the diagnostic names the first repeat, deterministically,
6192        // even when multiple names duplicate.
6193        let s = SupervisorSpec {
6194            children: vec![
6195                child("a", "^0.1", RestartPolicy::Permanent),
6196                child("b", "^0.1", RestartPolicy::Permanent),
6197                child("a", "^0.1", RestartPolicy::Permanent),
6198                child("b", "^0.1", RestartPolicy::Permanent),
6199            ],
6200            ..SupervisorSpec::default()
6201        };
6202        let err = s.validate().unwrap_err();
6203        assert!(
6204            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
6205            "got {err:?}"
6206        );
6207    }
6208
6209    // ── self-supervision cross-slot gate ──────────────────────────
6210
6211    #[test]
6212    fn validate_no_self_supervision_rejects_self_referential_child() {
6213        // A supervisor whose `:children` lists its own `:nome` is a
6214        // one-node reconciliation cycle — rejected, naming the parent.
6215        let children = vec![
6216            child("worker", "^0.1", RestartPolicy::Permanent),
6217            child("orquestra", "^0.1", RestartPolicy::Permanent),
6218        ];
6219        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
6220        assert!(
6221            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
6222            "got {err:?}"
6223        );
6224    }
6225
6226    #[test]
6227    fn validate_no_self_supervision_accepts_distinct_children() {
6228        // Positive control: distinct child names (including a child that
6229        // is itself a supervisor — nested trees are valid OTP) pass.
6230        let children = vec![
6231            child("worker", "^0.1", RestartPolicy::Permanent),
6232            child("sub-tree", "^0.1", RestartPolicy::Permanent),
6233        ];
6234        validate_no_self_supervision(&children, "orquestra").unwrap();
6235    }
6236
6237    #[test]
6238    fn validate_no_self_supervision_empty_children_is_ok() {
6239        // SimpleOneForOne / no-static-children supervisors have nothing
6240        // to self-reference — the gate is vacuously satisfied.
6241        validate_no_self_supervision(&[], "orquestra").unwrap();
6242    }
6243
6244    #[test]
6245    fn validate_simple_one_for_one_skips_uniqueness_check() {
6246        // SimpleOneForOne supervisors carry no static children — the
6247        // duplicate-child loop never runs. A zero-window declaration
6248        // on a SimpleOneForOne supervisor still trips the window check
6249        // (window applies to dynamic children too).
6250        let s = SupervisorSpec {
6251            estrategia: RestartStrategy::SimpleOneForOne,
6252            restart_window: None,
6253            children: vec![],
6254            ..SupervisorSpec::default()
6255        };
6256        s.validate().unwrap();
6257        let s_zero = SupervisorSpec {
6258            estrategia: RestartStrategy::SimpleOneForOne,
6259            restart_window: Some(Duration::ZERO),
6260            children: vec![],
6261            ..SupervisorSpec::default()
6262        };
6263        assert_eq!(
6264            s_zero.validate().unwrap_err(),
6265            SupervisorError::RestartWindowZero
6266        );
6267    }
6268
6269    #[test]
6270    fn validate_zero_window_runs_after_max_restarts_check() {
6271        // Pin the order: max_restarts == 0 fires before
6272        // restart_window == 0s, so an author with both wrong sees the
6273        // counter-axis diagnostic first (matches the order in the
6274        // struct and in the doc comment).
6275        let s = SupervisorSpec {
6276            max_restarts: 0,
6277            restart_window: Some(Duration::ZERO),
6278            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6279            ..SupervisorSpec::default()
6280        };
6281        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
6282    }
6283
6284    #[test]
6285    fn round_trip_all_strategies() {
6286        for &strat in RestartStrategy::ALL {
6287            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
6288            // shape partition through the [`gen_platform::IsVariant`]
6289            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
6290            // predicate rather than the raw
6291            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
6292            // open-coded pattern-match — same closed-set-typed-enum
6293            // arm-discriminator dispatch discipline the sibling
6294            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
6295            // (915a934) extended onto its two paired positive / negated
6296            // `matches!` filter sites, and the sibling
6297            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
6298            // predicate convergence (766ec63) extended onto the M3 mesh-
6299            // slot per-`:placement` distribution-strategy `matches!`
6300            // discriminator axis. See the sibling
6301            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
6302            // fixture and the peer `manifest::tests::
6303            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
6304            // fixture — all three sites (the last unlifted
6305            // `matches!`-based arm-discriminator axis on the OTP-shape
6306            // supervisor sibling-restart-strategy closed-set typed enum,
6307            // acknowledged in 915a934's Prior-commits footnote as the
6308            // outstanding follow-up) now consult one typed dispatch on
6309            // the substrate primitive.
6310            let s = SupervisorSpec {
6311                estrategia: strat,
6312                children: if strat.is_simple_one_for_one() {
6313                    vec![]
6314                } else {
6315                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
6316                },
6317                ..SupervisorSpec::default()
6318            };
6319            let json = serde_json::to_string(&s).unwrap();
6320            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6321            assert_eq!(s, back);
6322        }
6323    }
6324
6325    #[test]
6326    fn round_trip_all_restart_policies() {
6327        for policy in [
6328            RestartPolicy::Permanent,
6329            RestartPolicy::Temporary,
6330            RestartPolicy::Transient,
6331        ] {
6332            let c = child("w", "^0.1", policy);
6333            let json = serde_json::to_string(&c).unwrap();
6334            let back: ChildSpec = serde_json::from_str(&json).unwrap();
6335            assert_eq!(c, back);
6336        }
6337    }
6338
6339    #[test]
6340    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
6341        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
6342        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
6343        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
6344        // is the only variant that satisfies `.is_simple_one_for_one()`;
6345        // every static-children-bearing arm (`OneForOne` / `OneForAll`
6346        // / `RestForOne`) returns `false`. This pin makes the partition
6347        // invariant load-bearing at caixa-core test time so a future
6348        // derive regression (a hole that returns `false` for
6349        // `SimpleOneForOne` too, or a byte-collision that flips a second
6350        // variant to `true`) trips here rather than laundering the arm
6351        // at the three test-fixture builder sites (a hole flips the
6352        // `SimpleOneForOne` fixture to carry a non-empty children list
6353        // and the subsequent `SupervisorSpec::validate` would refuse the
6354        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
6355        // a collision flips a peer strategy's fixture to carry an empty
6356        // children list and the subsequent `validate` would refuse with
6357        // [`SupervisorError::NoChildren`] — either way, the pin fires
6358        // here, at the derive site, rather than at the fixture-refusal
6359        // site far away). Peer of the sibling
6360        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
6361        // (915a934) pin on the M2 OTP-appup axis and the sibling
6362        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
6363        // pin on the M0 `:kind` axis.
6364        let cases: &[(RestartStrategy, bool)] = &[
6365            (RestartStrategy::OneForOne, false),
6366            (RestartStrategy::OneForAll, false),
6367            (RestartStrategy::RestForOne, false),
6368            (RestartStrategy::SimpleOneForOne, true),
6369        ];
6370        for (variant, expected) in cases {
6371            assert_eq!(
6372                variant.is_simple_one_for_one(),
6373                *expected,
6374                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
6375                 return {expected} (partition invariant on the \
6376                 IsVariant-derived arm-discriminator predicate — every \
6377                 test-fixture site that partitions the `:children` slot \
6378                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
6379                 off this typed dispatch, so a derive regression must \
6380                 surface here rather than at the fixture-refusal site)"
6381            );
6382        }
6383    }
6384
6385    #[test]
6386    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
6387        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
6388        // fixture-shape partition against the pre-lift
6389        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
6390        // pattern-match every test-fixture builder site previously
6391        // coupled to inline. Asserts the two projections agree byte-for-
6392        // byte on every arm of the enum, so a future derive regression
6393        // that flipped either predicate's arm-set would surface here at
6394        // caixa-core test time rather than at the three fixture-builder
6395        // sites (`supervisor::tests::round_trip_all_strategies`,
6396        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
6397        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
6398        // far from the derive site. Same peer-shape byte-identity pin
6399        // every sibling `IsVariant`-derive-routed convergence carries on
6400        // the substrate's closed-set typed-enum surface (peer of
6401        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
6402        // on the M2 OTP-appup axis).
6403        for &strat in RestartStrategy::ALL {
6404            let via_predicate = strat.is_simple_one_for_one();
6405            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
6406            assert_eq!(
6407                via_predicate, via_matches,
6408                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
6409                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
6410                 the pre-lift open-coded pattern and the \
6411                 IsVariant-derived predicate are the same axis, \
6412                 one typed dispatch"
6413            );
6414        }
6415    }
6416
6417    #[test]
6418    fn duration_codec_round_trip_canonical_units() {
6419        // Note the canonical-form rule: durations serialize to the
6420        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
6421        // "60s" — but the round-trip preserves the underlying Duration.
6422        let cases = [
6423            ("30s", Duration::from_secs(30)),
6424            ("5m", Duration::from_secs(300)),
6425            ("1h", Duration::from_secs(3600)),
6426            ("500ms", Duration::from_millis(500)),
6427        ];
6428        for (lit, dur) in cases {
6429            let s = SupervisorSpec {
6430                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6431                restart_window: Some(dur),
6432                ..SupervisorSpec::default()
6433            };
6434            let json = serde_json::to_string(&s).unwrap();
6435            assert!(
6436                json.contains(&format!("\"{lit}\"")),
6437                "expected \"{lit}\" in {json}"
6438            );
6439            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6440            assert_eq!(back.restart_window, Some(dur));
6441        }
6442    }
6443
6444    #[test]
6445    fn duration_canonicalizes_to_largest_unit() {
6446        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
6447        // typed Duration still equals 60s on the way back.
6448        let s = SupervisorSpec {
6449            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6450            restart_window: Some(Duration::from_secs(60)),
6451            ..SupervisorSpec::default()
6452        };
6453        let json = serde_json::to_string(&s).unwrap();
6454        assert!(json.contains("\"1m\""), "{json}");
6455        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6456        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
6457    }
6458
6459    #[test]
6460    fn three_child_one_for_one_validates() {
6461        let s = SupervisorSpec {
6462            estrategia: RestartStrategy::OneForOne,
6463            max_restarts: 5,
6464            restart_window: Some(Duration::from_secs(60)),
6465            children: vec![
6466                child("worker", "^0.1", RestartPolicy::Permanent),
6467                child("cache", "^0.1", RestartPolicy::Transient),
6468                child("scratch", "^0.1", RestartPolicy::Temporary),
6469            ],
6470        };
6471        s.validate().unwrap();
6472    }
6473
6474    #[test]
6475    fn json_uses_pascal_case_for_strategy_and_policy() {
6476        // Variant names are PascalCase by default in serde, matching
6477        // tatara-lisp's enum convention (`:estrategia OneForOne`).
6478        let c = child("w", "^0.1", RestartPolicy::Permanent);
6479        let json = serde_json::to_string(&c).unwrap();
6480        assert!(json.contains("\"Permanent\""));
6481        assert!(!json.contains("\"permanent\""));
6482
6483        let s = SupervisorSpec {
6484            estrategia: RestartStrategy::OneForOne,
6485            children: vec![c],
6486            ..SupervisorSpec::default()
6487        };
6488        let json = serde_json::to_string(&s).unwrap();
6489        assert!(json.contains("\"estrategia\":\"OneForOne\""));
6490    }
6491
6492    // ── shared duration codec: integer-magnitude canonical-form gate ──
6493    //
6494    // The gate lifts the discipline `crate::limits::parse_duration`
6495    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
6496    // the shared codec backing the remaining three typed-duration
6497    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
6498    // `:politicas :circuit-breaker :window`. Every magnitude `render`
6499    // emits is a non-negative integer with no decimal point and no
6500    // leading sign, so the codec's accepted set must match for
6501    // serialize/deserialize to round-trip without canonical-form
6502    // drift.
6503
6504    #[test]
6505    fn parse_accepts_integer_canonical_units() {
6506        // Pin the happy-path: every canonical author shape `render`
6507        // ever emits parses to the same `Duration` value, so the
6508        // codec's accepted set is at least a superset of its emitted
6509        // set on the canonical-unit axis.
6510        for (lit, dur) in [
6511            ("30s", Duration::from_secs(30)),
6512            ("500ms", Duration::from_millis(500)),
6513            ("2m", Duration::from_secs(120)),
6514            ("1h", Duration::from_secs(3600)),
6515            ("0s", Duration::ZERO),
6516        ] {
6517            assert_eq!(
6518                duration_codec::parse(lit).unwrap(),
6519                dur,
6520                "parse({lit:?}) should be {dur:?}"
6521            );
6522        }
6523    }
6524
6525    #[test]
6526    fn parse_accepts_bare_integer_as_seconds() {
6527        // The `"s" | ""` arm: a bare integer with no unit is read as
6528        // seconds. Pin this so the unit-empty form keeps parsing (it
6529        // renders to `"<n>s"` on serialize — that's a unit-choice
6530        // drift the integer-magnitude gate does NOT close, matching
6531        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
6532        // the peer `:limits :memory` codec).
6533        assert_eq!(
6534            duration_codec::parse("30").unwrap(),
6535            Duration::from_secs(30)
6536        );
6537    }
6538
6539    #[test]
6540    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
6541        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
6542        // on first serialize — DRIFT. The integer-magnitude gate names
6543        // the offending `"1.5"` verbatim and points at the canonical
6544        // remediation `"1500ms"`.
6545        let err = duration_codec::parse("1.5s").unwrap_err();
6546        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
6547        assert!(
6548            err.contains("not a non-negative integer"),
6549            "missing canonical-form reason in {err:?}"
6550        );
6551        assert!(
6552            err.contains("\"1500ms\""),
6553            "missing canonical-form remediation in {err:?}"
6554        );
6555    }
6556
6557    #[test]
6558    fn parse_rejects_decimal_shaped_integer_seconds() {
6559        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
6560        // `1s` exactly, so the round-trip looks correct — but the
6561        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
6562        // decimal-shape-with-integer-value form so author intent is
6563        // never silently rewritten.
6564        let err = duration_codec::parse("1.0s").unwrap_err();
6565        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
6566        assert!(
6567            err.contains("not a non-negative integer"),
6568            "missing canonical-form reason in {err:?}"
6569        );
6570    }
6571
6572    #[test]
6573    fn parse_rejects_half_unit_minute() {
6574        // `"0.5m"` is the unit-fraction footgun — author writes a
6575        // human-readable half-minute, serde silently rewrites to
6576        // `"30s"` on next emit. The gate names the offending
6577        // magnitude `"0.5"` and points at the integer-in-smaller-unit
6578        // form.
6579        let err = duration_codec::parse("0.5m").unwrap_err();
6580        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
6581        assert!(
6582            err.contains("\"30s\""),
6583            "missing canonical-form remediation in {err:?}"
6584        );
6585    }
6586
6587    #[test]
6588    fn parse_rejects_leading_plus_sign() {
6589        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
6590        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
6591        // cleanly to 30s and round-tripped to `"30s"` on next emit
6592        // (DRIFT). The digit-only gate closes the leading-sign class
6593        // first; the diagnostic names `"+30"` verbatim.
6594        let err = duration_codec::parse("+30s").unwrap_err();
6595        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
6596        assert!(
6597            err.contains("not a non-negative integer"),
6598            "missing canonical-form reason in {err:?}"
6599        );
6600    }
6601
6602    #[test]
6603    fn parse_rejects_leading_minus_sign() {
6604        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
6605        // rejected with `"negative duration in \"-30s\""`. Under the
6606        // integer-magnitude gate the diagnostic is unified — `-30` is
6607        // non-digit-only, f64-numeric, and surfaces with the canonical-
6608        // form reason (no leading `+` / `-` sign) naming the offending
6609        // `"-30"` verbatim. Same diagnostic shape as every other
6610        // rejected non-integer magnitude.
6611        let err = duration_codec::parse("-30s").unwrap_err();
6612        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
6613        assert!(
6614            err.contains("not a non-negative integer"),
6615            "missing canonical-form reason in {err:?}"
6616        );
6617    }
6618
6619    #[test]
6620    fn parse_garbage_still_falls_through_to_bad_magnitude() {
6621        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
6622        // through to the narrower "bad duration magnitude" arm — the
6623        // canonical-form diagnostic is reserved for the parser-shape
6624        // footgun case, not the "not a number at all" case. Same
6625        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
6626        // the peer `:limits :memory` codec.
6627        let err = duration_codec::parse("--1s").unwrap_err();
6628        assert!(
6629            err.contains("bad duration magnitude"),
6630            "expected bad-magnitude wording in {err:?}"
6631        );
6632    }
6633
6634    #[test]
6635    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
6636        // The accepted set is now closed under `u64`-exact integer
6637        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
6638        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
6639        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
6640        // possible. Pin the integer-exact arms across the four unit
6641        // suffixes so a future refactor that reaches back for f64
6642        // (`from_secs_f64`, `mul_f64`) surfaces here.
6643        assert_eq!(
6644            duration_codec::parse("3600s").unwrap(),
6645            Duration::from_secs(3600)
6646        );
6647        assert_eq!(
6648            duration_codec::parse("60m").unwrap(),
6649            Duration::from_secs(3600)
6650        );
6651        assert_eq!(
6652            duration_codec::parse("1h").unwrap(),
6653            Duration::from_secs(3600)
6654        );
6655        assert_eq!(
6656            duration_codec::parse("999ms").unwrap(),
6657            Duration::from_millis(999)
6658        );
6659    }
6660
6661    #[test]
6662    fn restart_window_serde_rejects_fractional_seconds() {
6663        // The shared codec backs `SupervisorSpec::restart_window`
6664        // (`with = "duration_codec"`) — so the gate applies on serde
6665        // deserialize for the typed Supervisor slot. A
6666        // `{"restartWindow":"1.5s"}` payload that previously round-
6667        // tripped to a different canonical string on next serialize
6668        // is now refused at deserialize with the integer-magnitude
6669        // diagnostic.
6670        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6671            "restartWindow":"1.5s",
6672            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6673        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6674        let msg = err.to_string();
6675        assert!(
6676            msg.contains("not a non-negative integer"),
6677            "expected integer-magnitude diagnostic in {msg:?}"
6678        );
6679        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
6680    }
6681
6682    #[test]
6683    fn restart_window_serde_rejects_leading_plus() {
6684        // The `u64::from_str` leading-`+` permissiveness gap that
6685        // motivated the digit-only gate (the `f64`-side accepted
6686        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
6687        // is now closed on the shared codec — surfaces as a structured
6688        // diagnostic at the serde layer for every typed-duration slot.
6689        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6690            "restartWindow":"+30s",
6691            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6692        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6693        let msg = err.to_string();
6694        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
6695        assert!(
6696            msg.contains("not a non-negative integer"),
6697            "missing canonical-form reason in {msg:?}"
6698        );
6699    }
6700
6701    #[test]
6702    fn parse_rejects_leading_zero_magnitude() {
6703        // `"030s"` is digit-only, so the existing non-digit-only / sign
6704        // / fractional arm doesn't catch it — `u64::from_str("030")`
6705        // returns `Ok(30)`, so before this gate `"030s"` parsed to
6706        // `Duration::from_secs(30)` and round-tripped through `render`
6707        // to `"30s"` — a *different* canonical string on the next emit,
6708        // breaking the THEORY.md Part V render-determinism contract
6709        // exactly the way `"+30s"` did before the leading-`+` arm
6710        // landed. Peer with the `rate_limit_codec` leading-zero arm
6711        // (4f46830) on the same canonical-form-drift axis.
6712        let err = duration_codec::parse("030s").unwrap_err();
6713        assert!(
6714            err.contains("non-canonical leading zero"),
6715            "expected leading-zero diagnostic in {err:?}"
6716        );
6717        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6718        assert!(
6719            err.contains("\"30s\""),
6720            "missing canonical-form remediation in {err:?}"
6721        );
6722        assert!(
6723            err.contains("THEORY.md"),
6724            "missing render-determinism citation in {err:?}"
6725        );
6726    }
6727
6728    #[test]
6729    fn parse_rejects_multi_digit_zero_magnitude() {
6730        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
6731        // digit-only, parse losslessly to `Duration::ZERO`, but render
6732        // back to `"0s"` (the single-byte canonical form) on the next
6733        // emit. The leading-zero arm refuses the drift class at the
6734        // codec layer; the semantic-zero gate downstream
6735        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
6736        // the single-byte canonical form `"0s"` separately on the
6737        // typed-validate layer.
6738        let err = duration_codec::parse("00s").unwrap_err();
6739        assert!(
6740            err.contains("non-canonical leading zero"),
6741            "expected leading-zero diagnostic in {err:?}"
6742        );
6743        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
6744    }
6745
6746    #[test]
6747    fn parse_rejects_leading_zero_per_hour_window() {
6748        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
6749        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
6750        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
6751        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
6752        // `h` / bare-integer-as-seconds) inherits the same gate.
6753        let err = duration_codec::parse("01h").unwrap_err();
6754        assert!(
6755            err.contains("non-canonical leading zero"),
6756            "expected leading-zero diagnostic in {err:?}"
6757        );
6758        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
6759    }
6760
6761    #[test]
6762    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
6763        // The `parse_accepts_bare_integer_as_seconds` happy-path
6764        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
6765        // multi-byte starts-with-`0`, parses losslessly to
6766        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
6767        // bare-integer surface accepts permissive unit-empty
6768        // shorthand but still must reject leading-zero padding.
6769        let err = duration_codec::parse("030").unwrap_err();
6770        assert!(
6771            err.contains("non-canonical leading zero"),
6772            "expected leading-zero diagnostic in {err:?}"
6773        );
6774        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6775    }
6776
6777    #[test]
6778    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
6779        // The codec-layer / typed-validate-layer boundary: `"0s"` /
6780        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
6781        // each round-trips losslessly through `render`
6782        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
6783        // accepts them. The downstream semantic-zero gates
6784        // (`SupervisorError::ZeroRestartWindow`,
6785        // `AplicacaoError::PolicyTimeoutZero`,
6786        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
6787        // zero-magnitude authoring at the typed-validate layer above,
6788        // peer with the `rate_limit_codec` codec-layer / typed-
6789        // validate-layer partition for `"0/s"`.
6790        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
6791        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
6792        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
6793    }
6794
6795    #[test]
6796    fn parse_accepts_canonical_magnitude_with_leading_one() {
6797        // The complementary boundary: a future tightening cannot
6798        // drift into rejecting valid canonical magnitudes that
6799        // happen to start with `1` (or any digit `[1-9]`). Pin
6800        // every canonical-unit suffix so the leading-zero arm
6801        // remains strictly narrower than the digit-only arm.
6802        assert_eq!(
6803            duration_codec::parse("100ms").unwrap(),
6804            Duration::from_millis(100)
6805        );
6806        assert_eq!(
6807            duration_codec::parse("100s").unwrap(),
6808            Duration::from_secs(100)
6809        );
6810        assert_eq!(
6811            duration_codec::parse("10m").unwrap(),
6812            Duration::from_secs(600)
6813        );
6814        assert_eq!(
6815            duration_codec::parse("10h").unwrap(),
6816            Duration::from_secs(36_000)
6817        );
6818    }
6819
6820    #[test]
6821    fn restart_window_serde_rejects_leading_zero() {
6822        // The shared codec backs `SupervisorSpec::restart_window`
6823        // (`with = "duration_codec"`) — so the leading-zero arm
6824        // applies on serde deserialize for the typed Supervisor slot.
6825        // A `{"restartWindow":"030s"}` payload that previously round-
6826        // tripped to a different canonical string on next serialize
6827        // is now refused at deserialize with the leading-zero
6828        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
6829        // / `restart_window_serde_rejects_fractional_seconds` on the
6830        // same canonical-form-drift axis.
6831        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6832            "restartWindow":"030s",
6833            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6834        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6835        let msg = err.to_string();
6836        assert!(
6837            msg.contains("non-canonical leading zero"),
6838            "expected leading-zero diagnostic in {msg:?}"
6839        );
6840        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
6841    }
6842
6843    #[test]
6844    fn parse_rejects_leading_whitespace() {
6845        // `" 30s"` — the canonical paste-from-aligned-doc /
6846        // paste-from-YAML-quoted-plain-scalar footgun. Before this
6847        // gate the top-level `s.trim()` at parse entry silently ate
6848        // the leading space and parsed the value to
6849        // `Duration::from_secs(30)`, which then round-tripped through
6850        // `render` to `"30s"` (a *different* canonical string on the
6851        // next emit) — the exact canonical-form-drift class the
6852        // leading-`+` / leading-zero arms already close, extended
6853        // to the whitespace-byte class. Peer with the sibling
6854        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
6855        // the M3 `:politicas` axis.
6856        let err = duration_codec::parse(" 30s").unwrap_err();
6857        assert!(
6858            err.contains("contains whitespace byte"),
6859            "expected whitespace diagnostic in {err:?}"
6860        );
6861        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6862        assert!(
6863            err.contains("THEORY.md"),
6864            "missing render-determinism contract citation in {err:?}"
6865        );
6866    }
6867
6868    #[test]
6869    fn parse_rejects_trailing_whitespace() {
6870        // `"30s "` — the canonical shell-history / trailing-space
6871        // paste footgun. Before this gate the top-level `s.trim()`
6872        // silently ate the trailing space and parsed to
6873        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
6874        // next emit — same canonical-form drift as the leading-space
6875        // sibling, closed on the same whitespace-byte arm.
6876        let err = duration_codec::parse("30s ").unwrap_err();
6877        assert!(
6878            err.contains("contains whitespace byte"),
6879            "expected whitespace diagnostic in {err:?}"
6880        );
6881        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6882    }
6883
6884    #[test]
6885    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
6886        // `"30 s"` — the canonical typographically-spaced author
6887        // shape (the same idiom every prose reference to a duration
6888        // renders as, mistakenly retained when the value is pasted
6889        // into a codec-shaped slot). Before this gate the per-part
6890        // `num_part.trim()` / `unit.trim()` calls silently ate the
6891        // whitespace between the magnitude and the unit and parsed
6892        // the value to `Duration::from_secs(30)`, round-tripping to
6893        // `"30s"` — the codec's *internal* whitespace-tolerance
6894        // vector, orthogonal to the leading / trailing surface but
6895        // the same canonical-form-drift class. Pins the arm as
6896        // strictly stronger than the pre-existing top-level
6897        // `s.trim()` behavior: it fires on whitespace anywhere in
6898        // the value, not just at the string boundary.
6899        let err = duration_codec::parse("30 s").unwrap_err();
6900        assert!(
6901            err.contains("contains whitespace byte"),
6902            "expected whitespace diagnostic in {err:?}"
6903        );
6904        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6905    }
6906
6907    #[test]
6908    fn parse_rejects_tab_byte() {
6909        // `"\t30s"` — the canonical paste-from-indented-doc /
6910        // paste-from-YAML-block-scalar footgun where a tab byte leads
6911        // the magnitude. Pins that the gate covers tab (`0x09`) as
6912        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
6913        // members and both would be silently swallowed by `s.trim()`
6914        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
6915        // space alone to the full ASCII-whitespace set (space `0x20`,
6916        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
6917        // the tab arm as a representative of the non-space members.
6918        let err = duration_codec::parse("\t30s").unwrap_err();
6919        assert!(
6920            err.contains("contains whitespace byte"),
6921            "expected whitespace diagnostic in {err:?}"
6922        );
6923        assert!(
6924            err.contains("0x09"),
6925            "missing offending tab byte in {err:?}"
6926        );
6927    }
6928
6929    #[test]
6930    fn restart_window_serde_rejects_whitespace() {
6931        // The shared codec backs `SupervisorSpec::restart_window`
6932        // (`with = "duration_codec"`) — so the whitespace arm
6933        // applies on serde deserialize for the typed Supervisor slot.
6934        // A `{"restartWindow":" 30s"}` payload that previously round-
6935        // tripped to a different canonical string on next serialize
6936        // is now refused at deserialize with the whitespace-byte
6937        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
6938        // / `restart_window_serde_rejects_leading_plus` /
6939        // `restart_window_serde_rejects_fractional_seconds` on the
6940        // same canonical-form-drift axis.
6941        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6942            "restartWindow":" 30s",
6943            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6944        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6945        let msg = err.to_string();
6946        assert!(
6947            msg.contains("contains whitespace byte"),
6948            "expected whitespace diagnostic in {msg:?}"
6949        );
6950        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
6951    }
6952
6953    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
6954    //
6955    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
6956    // duration codec — closes the strictly-complementary class the
6957    // byte-scan cannot see, through the lifted
6958    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
6959    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
6960    // and `:politicas :circuit-breaker :window` simultaneously via
6961    // this shared codec.
6962
6963    #[test]
6964    fn duration_codec_parse_rejects_leading_nbsp() {
6965        // NBSP prefix — the strictly-complementary drift class the
6966        // ASCII byte-scan cannot see. `str::trim` strips it silently
6967        // and the value drifts to `"30s"` on next serialize.
6968        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
6969        assert!(
6970            err.contains("non-ASCII Unicode whitespace character"),
6971            "expected non-ASCII whitespace diagnostic in {err:?}"
6972        );
6973        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
6974    }
6975
6976    #[test]
6977    fn duration_codec_parse_rejects_trailing_line_separator() {
6978        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
6979        // footgun.
6980        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
6981        assert!(
6982            err.contains("non-ASCII Unicode whitespace character"),
6983            "expected non-ASCII whitespace diagnostic in {err:?}"
6984        );
6985        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
6986    }
6987
6988    #[test]
6989    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
6990        // Positive-control pin: every ASCII-only canonical form the
6991        // renderer emits stays accepted through the new arm.
6992        assert_eq!(
6993            duration_codec::parse("30s").unwrap(),
6994            Duration::from_secs(30)
6995        );
6996        assert_eq!(
6997            duration_codec::parse("500ms").unwrap(),
6998            Duration::from_millis(500)
6999        );
7000        assert_eq!(
7001            duration_codec::parse("1h").unwrap(),
7002            Duration::from_secs(3600)
7003        );
7004    }
7005
7006    #[test]
7007    fn restart_window_serde_rejects_non_ascii_whitespace() {
7008        // The shared codec backs `SupervisorSpec::restart_window` — so
7009        // the new non-ASCII Unicode whitespace arm applies on serde
7010        // deserialize for the typed Supervisor slot. A
7011        // `{"restartWindow":" 30s"}` payload that previously
7012        // survived the ASCII byte-scan (only ASCII whitespace was
7013        // refused) is now refused at deserialize with the
7014        // non-ASCII-whitespace-and-codepoint diagnostic.
7015        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
7016            \"restartWindow\":\"\u{00A0}30s\",\
7017            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
7018        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7019        let msg = err.to_string();
7020        assert!(
7021            msg.contains("non-ASCII Unicode whitespace character"),
7022            "expected non-ASCII whitespace diagnostic in {msg:?}"
7023        );
7024        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
7025    }
7026
7027    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
7028
7029    #[test]
7030    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
7031        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
7032        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
7033        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
7034        // name the exact camelCase JSON keys the
7035        // `#[serde(rename_all = "camelCase")]` attribute on
7036        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
7037        // field carries `Some(_)` / non-empty) and pin that each canonical
7038        // byte-sequence appears verbatim in the JSON — a future accidental
7039        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
7040        // name flip at the derive attribute (any of which would silently
7041        // break every downstream JSON consumer that reaches for one of the
7042        // four consts via `Value::get(...)`) surfaces here as a build-time
7043        // test failure at `supervisor.rs`, not as an apply-time
7044        // `.get(<stale-canonical-const>)` returning `None` far from the
7045        // derive-attr drift's commit. Peer with the sibling
7046        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
7047        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
7048        // M2 typed-slot family established, extended here to close the
7049        // top-level Supervisor axis.
7050        let spec = SupervisorSpec {
7051            estrategia: RestartStrategy::OneForOne,
7052            max_restarts: 5,
7053            restart_window: Some(Duration::from_secs(60)),
7054            children: vec![ChildSpec {
7055                caixa: "w".into(),
7056                versao: "^0.1".into(),
7057                restart: RestartPolicy::Permanent,
7058            }],
7059        };
7060        let json = serde_json::to_string(&spec).unwrap();
7061        for key in [
7062            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7063            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7064            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7065            crate::render::SUPERVISOR_KEY_CHILDREN,
7066        ] {
7067            let quoted = format!("\"{key}\"");
7068            assert!(
7069                json.contains(&quoted),
7070                "serialized SupervisorSpec must carry the lifted \
7071                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
7072                 the JSON emission (got: {json})",
7073            );
7074        }
7075    }
7076
7077    #[test]
7078    fn supervisor_key_consts_are_pairwise_distinct() {
7079        // Cross-axis drift-detection pin: a future collapse of two
7080        // canonical top-level byte-strings onto the same value (e.g. an
7081        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
7082        // also read `"estrategia"`) would silently reroute every
7083        // downstream probe on one axis onto the sibling axis's overlay
7084        // entry and pass every propagation-probe test that expected only
7085        // the stale axis's value. Peer of the sibling four-way distinct
7086        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
7087        let all = [
7088            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7089            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7090            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7091            crate::render::SUPERVISOR_KEY_CHILDREN,
7092        ];
7093        for (i, a) in all.iter().enumerate() {
7094            for b in all.iter().skip(i + 1) {
7095                assert_ne!(
7096                    a, b,
7097                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
7098                     canonical byte-sequences — got `{a}` == `{b}`",
7099                );
7100            }
7101        }
7102    }
7103
7104    #[test]
7105    fn supervisor_key_consts_are_lower_camel_case_shape() {
7106        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
7107        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7108        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7109        // capital, no whitespace / dots) — the canonical shape the
7110        // `#[serde(rename_all = "camelCase")]` derive produces on
7111        // `SupervisorSpec`. A future flip to a non-camelCase attribute
7112        // at the derive surfaces both here (this test fails on the
7113        // stale-constant shape) and at
7114        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7115        // (that test fails on the mismatch between const and derive).
7116        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
7117        // (d8b8b4f) on the sibling M2 `:limits` axis.
7118        for key in [
7119            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7120            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7121            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7122            crate::render::SUPERVISOR_KEY_CHILDREN,
7123        ] {
7124            assert!(
7125                !key.is_empty(),
7126                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
7127            );
7128            let first = key.chars().next().unwrap();
7129            assert!(
7130                first.is_ascii_lowercase(),
7131                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
7132                 (got {key:?}, leads with {first:?})",
7133            );
7134            assert!(
7135                key.chars().all(|c| c.is_ascii_alphanumeric()),
7136                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
7137                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7138            );
7139        }
7140    }
7141
7142    #[test]
7143    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
7144        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
7145        // (camelCase JSON keys, no leading colon) must never collide
7146        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
7147        // consts (kebab-case author-facing labels with leading colon)
7148        // that sit next to them at `caixa_core::render`. Both families
7149        // cover the same four typed Supervisor slots on two distinct
7150        // axes (author-side kebab vs renderer-side camelCase);
7151        // collapsing either family onto the other's byte-shape would
7152        // silently reroute the render-side probe onto the author-facing
7153        // surface, or vice versa. Peer of the byte-distinctness
7154        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
7155        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
7156        let pairs = [
7157            (
7158                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7159                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
7160            ),
7161            (
7162                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7163                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
7164            ),
7165            (
7166                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7167                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
7168            ),
7169            (
7170                crate::render::SUPERVISOR_KEY_CHILDREN,
7171                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
7172            ),
7173        ];
7174        for (json_key, author_key) in pairs {
7175            assert_ne!(
7176                json_key, author_key,
7177                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
7178                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
7179                 got JSON `{json_key}` == author `{author_key}`",
7180            );
7181        }
7182    }
7183
7184    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
7185
7186    #[test]
7187    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
7188        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
7189        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
7190        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
7191        // keys the `#[serde(rename_all = "camelCase")]` attribute on
7192        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
7193        // pin that each canonical byte-sequence appears verbatim in the
7194        // JSON — a future accidental `rename_all = "snake_case"` /
7195        // `"kebab-case"` / verbatim-field-name flip at the derive
7196        // attribute (any of which would silently break every downstream
7197        // JSON consumer that reaches for one of the three consts via
7198        // `Value::get(...)`) surfaces here as a build-time test failure at
7199        // `supervisor.rs`, not as an apply-time
7200        // `.get(<stale-canonical-const>)` returning `None` far from the
7201        // derive-attr drift's commit. Peer with the enclosing
7202        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7203        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
7204        // discipline the SupervisorSpec top-level lift established,
7205        // extended here to the sibling per-`:children` entry `ChildSpec`
7206        // derive so the last M2 typed-struct sub-block
7207        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
7208        // surface without a lifted serde-key peer joins the substrate's
7209        // "one canonical byte-string per typed serialized-key axis"
7210        // discipline.
7211        let c = ChildSpec {
7212            caixa: "worker".into(),
7213            versao: "^0.1".into(),
7214            restart: RestartPolicy::Permanent,
7215        };
7216        let json = serde_json::to_string(&c).unwrap();
7217        for key in [
7218            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7219            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7220            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7221        ] {
7222            let quoted = format!("\"{key}\"");
7223            assert!(
7224                json.contains(&quoted),
7225                "serialized ChildSpec must carry the lifted \
7226                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
7227                 in the JSON emission (got: {json})",
7228            );
7229        }
7230    }
7231
7232    #[test]
7233    fn supervisor_child_key_consts_are_pairwise_distinct() {
7234        // Cross-axis drift-detection pin: a future collapse of two
7235        // canonical `ChildSpec` per-entry byte-strings onto the same
7236        // value (e.g. an accidental copy-paste flip of
7237        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
7238        // silently reroute every downstream probe on one axis onto the
7239        // sibling axis's overlay entry and pass every propagation-probe
7240        // test that expected only the stale axis's value. Peer of the
7241        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
7242        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
7243        // pair (ce80ca0).
7244        let all = [
7245            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7246            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7247            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7248        ];
7249        for (i, a) in all.iter().enumerate() {
7250            for b in all.iter().skip(i + 1) {
7251                assert_ne!(
7252                    a, b,
7253                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
7254                     distinct canonical byte-sequences — got `{a}` == `{b}`",
7255                );
7256            }
7257        }
7258    }
7259
7260    #[test]
7261    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
7262        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
7263        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7264        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7265        // capital, no whitespace / dots) — the canonical shape the
7266        // `#[serde(rename_all = "camelCase")]` derive produces on
7267        // `ChildSpec`. A future flip to a non-camelCase attribute at the
7268        // derive surfaces both here (this test fails on the
7269        // stale-constant shape) and at
7270        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
7271        // (that test fails on the mismatch between const and derive).
7272        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
7273        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
7274        for key in [
7275            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7276            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7277            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7278        ] {
7279            assert!(
7280                !key.is_empty(),
7281                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
7282            );
7283            let first = key.chars().next().unwrap();
7284            assert!(
7285                first.is_ascii_lowercase(),
7286                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
7287                 byte (got {key:?}, leads with {first:?})",
7288            );
7289            assert!(
7290                key.chars().all(|c| c.is_ascii_alphanumeric()),
7291                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
7292                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7293            );
7294        }
7295    }
7296
7297    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
7298
7299    #[test]
7300    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
7301        // The fail-before-pass-after pin: pre-lift there was no
7302        // single-source binding between the [`RestartStrategy`] variant
7303        // name the un-`rename`d `Serialize` derive emits under
7304        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
7305        // every downstream cluster-side dispatcher (the future
7306        // wasm-operator's per-supervisor sibling-restart branch, the
7307        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7308        // admission-time enum-arm bind, the `caixa-operator`'s
7309        // hierarchical reconciliation scheduler's per-strategy fan-out)
7310        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
7311        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
7312        // override, or a variant rename in the source — would silently
7313        // rebrand the emitted scalar under one spelling while every
7314        // downstream dispatcher still probed the other, with the failure
7315        // surfacing at the operator's reconcile posture (subtrees coming
7316        // up under the `default()` `OneForOne` arm rather than the typed
7317        // slot's declared strategy — a bad child would then only take
7318        // itself down instead of the sibling set the author intended, so
7319        // shared-state children fall out of sync) far from the source
7320        // rebrand commit and with no field naming the drift. Pinning the
7321        // two paths (the `Serialize` derive's serialized string AND the
7322        // [`RestartStrategy::as_str`] helper) to the same four lifted
7323        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
7324        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
7325        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
7326        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
7327        // byte-strings makes any future drift on either endpoint fail
7328        // here at caixa-core build time. Peer of the M3
7329        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7330        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
7331        // three-path-convergence discipline, extended to close the
7332        // OTP-shaped per-supervisor sibling-restart axis.
7333        for (variant, expected) in [
7334            (
7335                RestartStrategy::OneForOne,
7336                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7337            ),
7338            (
7339                RestartStrategy::OneForAll,
7340                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7341            ),
7342            (
7343                RestartStrategy::RestForOne,
7344                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7345            ),
7346            (
7347                RestartStrategy::SimpleOneForOne,
7348                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7349            ),
7350        ] {
7351            let json = serde_json::to_string(&variant).unwrap();
7352            assert_eq!(
7353                json,
7354                format!("\"{expected}\""),
7355                "RestartStrategy::{variant:?} must serialize to {expected:?}"
7356            );
7357            assert_eq!(
7358                variant.as_str(),
7359                expected,
7360                "RestartStrategy::{variant:?}.as_str() must return the lifted \
7361                 SUPERVISOR_ESTRATEGIA_* constant"
7362            );
7363        }
7364    }
7365
7366    #[test]
7367    fn supervisor_estrategia_consts_are_pairwise_distinct() {
7368        // Cross-arm drift-detection pin: a future collapse of two
7369        // canonical variant byte-strings onto the same value (e.g. an
7370        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
7371        // to also read `"OneForOne"`) would silently reroute every
7372        // downstream operator's per-strategy dispatch onto the sibling
7373        // arm's reconcile branch and pass every propagation-probe test
7374        // that expected only the stale arm's value — the mis-strategied
7375        // subtree would come up with the wrong sibling-restart posture
7376        // on every subsequent failure. Peer of the sibling four-way
7377        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
7378        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
7379        let all = [
7380            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7381            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7382            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7383            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7384        ];
7385        for (i, a) in all.iter().enumerate() {
7386            for (j, b) in all.iter().enumerate() {
7387                if i != j {
7388                    assert_ne!(
7389                        a, b,
7390                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
7391                         — got duplicate {a:?} at indices {i} and {j}",
7392                    );
7393                }
7394            }
7395        }
7396    }
7397
7398    #[test]
7399    fn restart_strategy_display_routes_through_as_str_helper() {
7400        // The fail-before-pass-after pin on the first half of the
7401        // three-path convergence: pre-convergence the sibling
7402        // OTP-shape typed enum [`RestartStrategy`] carried a
7403        // [`std::fmt::Display`] surface via its
7404        // `#[discriminant(also_display)]` gen-platform derive route,
7405        // which arrived kebab-case as `"one-for-one"` /
7406        // `"one-for-all"` / `"rest-for-one"` /
7407        // `"simple-one-for-one"` while the wire format ran as
7408        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
7409        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
7410        // Every consumer reaching for a strategy byte-string past the
7411        // wire format had to pick between three paths
7412        // ([`RestartStrategy::as_str`], the `Serialize` derive's
7413        // serialized string, or `format!("{v}")` on the
7414        // discriminant-Display route), any two of which a future
7415        // variant rename or `#[serde(rename_all = "kebab-case")]`
7416        // attribute would silently desynchronize. Wiring
7417        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
7418        // closes the third path: every `format!("{v}")` call reaches
7419        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7420        // const the wire format and the [`RestartStrategy::as_str`]
7421        // helper already route through, so a future variant rename
7422        // lands at exactly one place. Pin the routing here so a future
7423        // `impl std::fmt::Display for RestartStrategy`
7424        // reimplementation that hand-rolls the arms instead of
7425        // delegating to [`RestartStrategy::as_str`] fails at
7426        // caixa-core build time. Peer of the M3
7427        // `placement_strategy_display_routes_through_as_str_helper`
7428        // (cc8f749) which the M3 axis converged first.
7429        for &variant in RestartStrategy::ALL {
7430            assert_eq!(
7431                variant.to_string(),
7432                variant.as_str(),
7433                "RestartStrategy::{variant:?} Display must route through \
7434                 RestartStrategy::as_str (single source of truth: the lifted \
7435                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
7436            );
7437        }
7438    }
7439
7440    #[test]
7441    fn restart_strategy_display_matches_serialized_wire_byte_string() {
7442        // The fail-before-pass-after pin on the second half of the
7443        // three-path convergence: `Display` (user-facing text) agrees
7444        // byte-for-byte with the `Serialize` derive's wire format
7445        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
7446        // scalar) on every variant. Pre-convergence the two paths
7447        // were structurally independent — a future
7448        // `#[serde(rename_all = "kebab-case")]` attribute on the
7449        // enum would silently rebrand the emitted wire scalar
7450        // (`one-for-one`, `one-for-all`, `rest-for-one`,
7451        // `simple-one-for-one`) while every consumer that
7452        // pretty-prints the strategy (the future wasm-operator's
7453        // per-supervisor sibling-restart-strategy diagnostic line,
7454        // the future `feira app graph` per-supervisor strategy line,
7455        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7456        // materializer's admission-webhook rejection body) would
7457        // still emit the PascalCase form the `as_str` / `Display`
7458        // route returns, with the mismatch surfacing at consumer
7459        // parse time / operator dispatch time far from the source
7460        // rebrand commit. Pin the two paths byte-for-byte here so any
7461        // future serde-attribute or variant-rename drift is a
7462        // caixa-core-build-time test failure at this call, not a
7463        // silent per-consumer dispatch miss. Peer of the M3
7464        // `placement_strategy_display_matches_serialized_wire_byte_string`
7465        // (cc8f749) which the M3 axis converged first.
7466        for &variant in RestartStrategy::ALL {
7467            let wire = serde_json::to_string(&variant).unwrap();
7468            let unquoted = wire
7469                .strip_prefix('"')
7470                .and_then(|s| s.strip_suffix('"'))
7471                .expect("serialized RestartStrategy is a JSON string");
7472            assert_eq!(
7473                variant.to_string(),
7474                unquoted,
7475                "RestartStrategy::{variant:?} Display byte-string must match the \
7476                 Serialize derive's wire byte-string (three-path convergence: \
7477                 Display + as_str + Serialize all resolve to the same \
7478                 SUPERVISOR_ESTRATEGIA_* const)"
7479            );
7480        }
7481    }
7482
7483    #[test]
7484    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
7485        // Fail-before-pass-after byte-parity pin on the lifted
7486        // `impl AsRef<str> for RestartStrategy` — asserts the
7487        // standard-library trait impl and the substrate-primitive
7488        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
7489        // to the same `&str` per instance across the four-arm
7490        // closed set, so any future silent detour that routes the
7491        // impl through a divergent projection (a per-arm inline
7492        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
7493        // re-inlining that opens a compile-time link to the un-lifted
7494        // arm-literal, a swap onto the kebab-case
7495        // [`gen_platform::Discriminant`] catalog identity that would
7496        // collide the wire axis with the dispatcher-catalog axis) trips
7497        // at caixa-core test time under `PartialEq` rather than at a
7498        // downstream `impl AsRef<str>`-bound consumer's silent split.
7499        // Sweeps every one of the four arms
7500        // [`RestartStrategy::ALL`] carries so no arm's projection is
7501        // covered only by the sibling wire-format `Serialize` derive
7502        // path. Peer of the sibling
7503        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
7504        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
7505        // top-level `:versao` typed newtype — the two pins together
7506        // cover the substrate primitive's `AsRef<str>` projection axis
7507        // on the paired newtype + closed-set-typed-enum surface.
7508        for &variant in RestartStrategy::ALL {
7509            assert_eq!(
7510                <RestartStrategy as AsRef<str>>::as_ref(&variant),
7511                variant.as_str(),
7512                "AsRef<str> impl on RestartStrategy::{variant:?} must \
7513                 byte-equal RestartStrategy::as_str on the same instance \
7514                 — divergence signals a silent detour off the substrate-\
7515                 primitive accessor"
7516            );
7517        }
7518    }
7519
7520    #[test]
7521    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
7522        // Fail-before-pass-after byte-parity pin on the three-path
7523        // convergence discipline the M2 sibling-restart primitive now
7524        // carries on the `&str`-projection axis:
7525        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
7526        // lifted impl), `format!("{s}")` (the pre-existing
7527        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
7528        // primitive `pub const fn` accessor both trait impls delegate
7529        // through) must resolve to the same byte-string on every
7530        // instance across the four-arm closed set. Refuses any future
7531        // divergence between the two trait impls (a stray
7532        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7533        // rather than delegating through the shared accessor; a
7534        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7535        // literal cascade) that would silently split the two
7536        // projection paths of the same closed-set typed enum. Mirrors
7537        // the sibling three-path-convergence discipline the peer
7538        // [`crate::CaixaVersion`] typed newtype carries on its
7539        // `AsRef<str>` / `Display` / `as_str` triple
7540        // (version.rs pin
7541        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7542        // 16d5c7e).
7543        for &variant in RestartStrategy::ALL {
7544            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
7545            let via_display: String = format!("{variant}");
7546            let via_accessor: &str = variant.as_str();
7547            assert_eq!(via_as_ref, via_accessor);
7548            assert_eq!(via_display, via_accessor);
7549            assert_eq!(via_as_ref, via_display.as_str());
7550        }
7551    }
7552
7553    #[test]
7554    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
7555        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
7556        // exhaustive-iteration surface: every variant appears exactly
7557        // once, and the slice length matches the arm count of the
7558        // closed set. Every consumer that walks the accepted-strategy
7559        // set (a future `feira supervisor --estrategia …` CLI-side
7560        // arg-parse's "did you mean" hint, a future M4 admission-
7561        // webhook's rejection body naming the accepted-`:estrategia`
7562        // list, the [`RestartStrategy::from_wire`] reverse-projection
7563        // consumers that iterate the accept-set for diagnostic
7564        // rendering) reads through this slice, so a future arm addition
7565        // that grows the enum but forgets to grow [`Self::ALL`]
7566        // silently truncates every downstream consumer's accept-set at
7567        // the same pre-addition boundary — this pin fails at caixa-core
7568        // build time on the pairwise-distinct + arm-count invariants.
7569        //
7570        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
7571        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7572        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7573        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7574        // pins on the peer closed-set typed-enum axes.
7575        let all: &[RestartStrategy] = RestartStrategy::ALL;
7576        assert_eq!(
7577            all.len(),
7578            4,
7579            "RestartStrategy::ALL must enumerate every variant of the \
7580             four-arm closed set (OneForOne, OneForAll, RestForOne, \
7581             SimpleOneForOne); got {all:?}"
7582        );
7583        for (i, a) in all.iter().enumerate() {
7584            for (j, b) in all.iter().enumerate() {
7585                if i != j {
7586                    assert_ne!(
7587                        a, b,
7588                        "RestartStrategy::ALL must carry every variant exactly \
7589                         once — got duplicate {a:?} at indices {i} and {j}"
7590                    );
7591                }
7592            }
7593        }
7594        for variant in [
7595            RestartStrategy::OneForOne,
7596            RestartStrategy::OneForAll,
7597            RestartStrategy::RestForOne,
7598            RestartStrategy::SimpleOneForOne,
7599        ] {
7600            assert!(
7601                all.contains(&variant),
7602                "RestartStrategy::ALL must contain {variant:?} — a future arm \
7603                 addition that grows the enum but forgets to grow the ALL slice \
7604                 silently truncates every downstream consumer's accept-set at \
7605                 the pre-addition boundary"
7606            );
7607        }
7608    }
7609
7610    #[test]
7611    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
7612        // Fail-before-pass-after pin on the forward accept-set of the
7613        // [`RestartStrategy::from_wire`] reverse projection: every
7614        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7615        // constant the [`RestartStrategy::as_str`] emitter walks parses
7616        // back to its paired variant. Any future arm addition that
7617        // grows the emitter's `as_str` match but forgets to grow the
7618        // parser's `from_wire` match silently splits the two halves of
7619        // the round-trip — the wire byte-string one non-serde consumer
7620        // parses from the one the emitter wrote — with the failure
7621        // surfacing at parse time far from the rebrand commit. Pinning
7622        // the four-arm accept-set here catches the drift at caixa-core
7623        // build time.
7624        //
7625        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
7626        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
7627        // accept-set pins on the peer closed-set typed-enum `str → Self`
7628        // axes.
7629        for (wire, expected) in [
7630            (
7631                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7632                RestartStrategy::OneForOne,
7633            ),
7634            (
7635                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7636                RestartStrategy::OneForAll,
7637            ),
7638            (
7639                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7640                RestartStrategy::RestForOne,
7641            ),
7642            (
7643                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7644                RestartStrategy::SimpleOneForOne,
7645            ),
7646        ] {
7647            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7648                panic!(
7649                    "RestartStrategy::from_wire({wire:?}) must accept every \
7650                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
7651                     lifted canonical byte-string that RestartStrategy::{expected:?} \
7652                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
7653                )
7654            });
7655            assert_eq!(
7656                parsed, expected,
7657                "RestartStrategy::from_wire({wire:?}) must return \
7658                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
7659            );
7660        }
7661    }
7662
7663    #[test]
7664    fn restart_strategy_from_wire_round_trips_through_as_str() {
7665        // Fail-before-pass-after pin on the closed round-trip between
7666        // the forward [`RestartStrategy::as_str`] emitter and the
7667        // reverse [`RestartStrategy::from_wire`] parser: for every
7668        // variant in [`RestartStrategy::ALL`], parsing the emitter's
7669        // output must return exactly the same variant. Any per-arm
7670        // divergence — a future arm added to `as_str` but not
7671        // `from_wire`, an accidental copy-paste flip in one but not
7672        // the other — silently splits the emit and parse halves and
7673        // the failure surfaces at consumer parse time far from the
7674        // drift site. The `ALL`-iterating shape means a future arm
7675        // addition picks up the coverage by construction.
7676        //
7677        // Peer of the sibling
7678        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
7679        // (18c7342) round-trip pin on
7680        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
7681        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
7682        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
7683        for &variant in RestartStrategy::ALL {
7684            let wire = variant.as_str();
7685            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7686                panic!(
7687                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7688                     must be Some({variant:?}) — the two halves of the round-trip \
7689                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
7690                     got None on wire byte-string {wire:?}"
7691                )
7692            });
7693            assert_eq!(
7694                parsed, variant,
7695                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7696                 must round-trip to the same variant; got {parsed:?}"
7697            );
7698        }
7699    }
7700
7701    #[test]
7702    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
7703        // Fail-before-pass-after pin on the closed-set refusal
7704        // discipline of [`RestartStrategy::from_wire`]: every
7705        // byte-string outside the four-arm accept-set returns `None`
7706        // rather than silently collapsing onto the [`Default`]
7707        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
7708        // exercised here sweeps the load-bearing drift shapes: the
7709        // empty string (a stripped serde-attribute drift), all-
7710        // whitespace strings (the canonical text-editor accidental
7711        // padding shape), the kebab-case dispatcher-catalog identities
7712        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
7713        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
7714        // derived [`std::str::FromStr`] accept-set, which parses the
7715        // *other* axis of this enum's two-axis split and must not leak
7716        // into the `from_wire` PascalCase-wire accept-set), the
7717        // lowercased single-word forms (`"oneforone"`), the padded
7718        // canonical scalar (`" OneForOne "`), the trailing-newline
7719        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
7720        // (`"AllForOne"` — the canonical typo direction).
7721        //
7722        // Peer of the sibling
7723        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
7724        // (2aa6d23) +
7725        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
7726        // (18c7342) refusal pins on the peer closed-set typed-enum
7727        // axes.
7728        for bad in [
7729            "",
7730            " ",
7731            "\n",
7732            "\t",
7733            "one-for-one",
7734            "one-for-all",
7735            "rest-for-one",
7736            "simple-one-for-one",
7737            "oneforone",
7738            "OneForOnes",
7739            "one_for_one",
7740            "one for one",
7741            "ONEFORONE",
7742            "OneForOne ",
7743            " OneForOne",
7744            " SimpleOneForOne ",
7745            "OneForOne\n",
7746            "restforone",
7747            "REST_FOR_ONE",
7748            "AllForOne",
7749            "Simple",
7750            "?",
7751        ] {
7752            assert!(
7753                RestartStrategy::from_wire(bad).is_none(),
7754                "RestartStrategy::from_wire({bad:?}) must return None — the \
7755                 parser's accept-set is exactly the four RestartStrategy::as_str \
7756                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
7757                 and this byte-string is outside that closed set"
7758            );
7759        }
7760    }
7761
7762    #[test]
7763    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
7764        // Fail-before-pass-after pin on the fourth path of the four-path
7765        // convergence: `from_wire` (the reverse projection) inverts the
7766        // `Serialize` derive's wire byte-string on every variant.
7767        // Together with the pre-existing three-path convergence
7768        // (`Display` + `as_str` + `Serialize` all resolve to the same
7769        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
7770        // pinned by
7771        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
7772        // this closes the round-trip: the wire byte-string the
7773        // `Serialize` derive emits parses back to the same variant
7774        // through `from_wire`, so any future serde-attribute or variant-
7775        // rename drift on the emit half now surfaces as a matched drift
7776        // on the parse half at caixa-core build time — the two halves
7777        // migrate as a unit through the lifted consts on any future
7778        // rename, and the round-trip cannot silently split.
7779        //
7780        // Peer of the sibling
7781        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7782        // (18c7342) wire-format pin on
7783        // [`crate::aplicacao::PlacementStrategy::from_wire`].
7784        for &variant in RestartStrategy::ALL {
7785            let wire = serde_json::to_string(&variant).unwrap();
7786            let unquoted = wire
7787                .strip_prefix('"')
7788                .and_then(|s| s.strip_suffix('"'))
7789                .expect("serialized RestartStrategy is a JSON string");
7790            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
7791                panic!(
7792                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
7793                     Serialize derive's wire byte-string for \
7794                     RestartStrategy::{variant:?} — the four-path convergence \
7795                     (Display + as_str + Serialize + from_wire) resolves through \
7796                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
7797                )
7798            });
7799            assert_eq!(
7800                parsed, variant,
7801                "RestartStrategy::from_wire of the Serialize derive's wire \
7802                 byte-string for RestartStrategy::{variant:?} must round-trip \
7803                 to the same variant; got {parsed:?}"
7804            );
7805        }
7806    }
7807
7808    #[test]
7809    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
7810        // Fail-before-pass-after byte-parity pin on the newly lifted
7811        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
7812        // library trait impl and the substrate-primitive
7813        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
7814        // the same four-arm accept-set across every arm the exhaustive
7815        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7816        // detour that routes the trait impl through a divergent projection
7817        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
7818        // … }` re-inlining that opens a compile-time link to the un-
7819        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
7820        // attribute drift that silently splits the wire byte-string from
7821        // every consumer that reaches for this typed dispatch, an
7822        // accidental swap onto the kebab-case dispatcher-catalog axis the
7823        // pre-existing [`std::str::FromStr`] impl parses through and which
7824        // would collide the two-axis wire/catalog split the sibling
7825        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
7826        // trips at caixa-core test time under `assert_eq!` rather than at
7827        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
7828        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
7829        // carries so no arm's projection is covered only by the sibling
7830        // method-named `from_wire` path. Peer of the sibling
7831        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
7832        // (3c83606),
7833        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
7834        // (bf33136), and the M3
7835        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
7836        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
7837        // onto the first M2-OTP-shape closed-set typed enum on the caixa
7838        // surface.
7839        for &variant in RestartStrategy::ALL {
7840            let wire = variant.as_str();
7841            assert_eq!(
7842                <RestartStrategy as TryFrom<&str>>::try_from(wire),
7843                Ok(variant),
7844                "TryFrom<&str> impl on RestartStrategy must round-trip \
7845                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
7846                 Ok(RestartStrategy::{variant:?}) — divergence from \
7847                 RestartStrategy::from_wire signals a silent detour off \
7848                 the substrate-primitive accessor"
7849            );
7850            assert_eq!(
7851                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
7852                RestartStrategy::from_wire(wire),
7853                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
7854                 RestartStrategy::from_wire on the same input"
7855            );
7856        }
7857    }
7858
7859    #[test]
7860    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
7861        // Rejection witness on the `impl TryFrom<&str> for
7862        // RestartStrategy` — sweeps a candidate set of byte-strings
7863        // outside the four-arm PascalCase wire accept-set the sibling
7864        // [`RestartStrategy::as_str`] emits and asserts every one lands on
7865        // `Err(())`, so a future accidental widening of the trait impl's
7866        // accept-set (a stray additional
7867        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
7868        // path, a silent inclusion of the kebab-case dispatcher-catalog
7869        // byte-string the pre-existing [`std::str::FromStr`] impl the
7870        // [`gen_platform::FromStrKind`] derive installs parses onto the
7871        // wire axis — which would collide the two-axis
7872        // wire/dispatcher-catalog split the sibling
7873        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
7874        // an English-rebrand or plural-arm silent alias that would
7875        // widen the wire accept-set past the OTP-canonical four) trips at
7876        // caixa-core test time. The candidate set includes the empty
7877        // string, whitespace-only padding, the kebab-case dispatcher-
7878        // catalog byte-strings on the sibling axis (a caller who confuses
7879        // the two axes trips here rather than at a downstream consumer's
7880        // silent reject), a lowercase / uppercase / mixed-case fold of
7881        // each PascalCase arm (a caller who assumes case-fold acceptance
7882        // trips here), leading/trailing whitespace padding, the trailing-
7883        // newline shape, quote-wrapped candidates, and a residual set of
7884        // plausible-but-wrong English rebrand candidates. Peer of the
7885        // sibling
7886        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
7887        // (3c83606) and
7888        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
7889        // (6fd00cd) rejection witnesses.
7890        let rejected: &[&str] = &[
7891            "",
7892            " ",
7893            "\n",
7894            "\t",
7895            "one-for-one",
7896            "one-for-all",
7897            "rest-for-one",
7898            "simple-one-for-one",
7899            "oneforone",
7900            "one_for_one",
7901            "OneForOnes",
7902            "ONEFORONE",
7903            "oneforall",
7904            "restforone",
7905            "simpleoneforone",
7906            "OneForOne ",
7907            " OneForOne",
7908            " OneForAll ",
7909            "OneForOne\n",
7910            "RestForOne\t",
7911            "OneForEach",
7912            "AllForOne",
7913            "one for one",
7914            "\"OneForOne\"",
7915            "?",
7916        ];
7917        for &input in rejected {
7918            assert_eq!(
7919                <RestartStrategy as TryFrom<&str>>::try_from(input),
7920                Err(()),
7921                "TryFrom<&str> impl on RestartStrategy must reject the \
7922                 non-wire byte-string {input:?} — silent acceptance signals \
7923                 an accept-set widening off the paired \
7924                 RestartStrategy::from_wire resolver"
7925            );
7926        }
7927    }
7928
7929    #[test]
7930    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
7931        // Cross-axis partition pin: the paired `TryFrom<&str>` and
7932        // `from_wire` reverse projections must resolve identically on
7933        // *every* input, not just the ones [`RestartStrategy::ALL`]
7934        // enumerates. Sweeps a mixed candidate set spanning accepted
7935        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
7936        // dispatcher-catalog byte-strings, empty, whitespace-padded,
7937        // quoted, English-rebrand candidates) inputs and asserts the
7938        // trait's `Result::ok()` projection byte-equals the method-named
7939        // resolver's `Option<Self>` return-shape on each, locking the two
7940        // paths together by construction so any future detour (a stray
7941        // `try_from` special-case that widens or narrows the accept-set
7942        // outside the paired `from_wire` resolver, an accidental swap
7943        // onto the kebab-case [`std::str::FromStr`] impl the
7944        // [`gen_platform::FromStrKind`] derive installs on the sibling
7945        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
7946        // the sibling
7947        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
7948        // pin — extends the round-trip discipline onto the M2-OTP-shape
7949        // sibling-restart axis.
7950        let candidates: &[&str] = &[
7951            "OneForOne",
7952            "OneForAll",
7953            "RestForOne",
7954            "SimpleOneForOne",
7955            "",
7956            "one-for-one",
7957            "one-for-all",
7958            "rest-for-one",
7959            "simple-one-for-one",
7960            "oneforone",
7961            "unknown",
7962            "OneForOne ",
7963            " OneForOne",
7964            "\"OneForOne\"",
7965            "OneForEach",
7966            "?",
7967        ];
7968        for &input in candidates {
7969            let via_trait: Option<RestartStrategy> =
7970                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
7971            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
7972            assert_eq!(
7973                via_trait, via_method,
7974                "TryFrom<&str> and from_wire must resolve identically on \
7975                 input {input:?} — divergence signals the two reverse-\
7976                 projection paths have drifted onto different accept-sets"
7977            );
7978        }
7979    }
7980
7981    #[test]
7982    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
7983        // Fail-before-pass-after byte-parity pin on the newly lifted
7984        // `impl From<RestartStrategy> for &'static str` — asserts the
7985        // standard-library trait impl and the substrate-primitive
7986        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
7987        // the same four-arm emit-set across every arm the exhaustive
7988        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7989        // detour that routes the trait impl through a divergent
7990        // projection (a per-arm inline `match strategy { OneForOne =>
7991        // "OneForOne", … }` re-inlining that opens a compile-time link to
7992        // the un-lifted arm-literal, an accidental swap onto the sibling
7993        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
7994        // would collide the two-axis wire/catalog split the sibling
7995        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
7996        // at caixa-core test time under `assert_eq!` rather than at a
7997        // downstream `impl Into<&'static str>`-bound consumer's silent
7998        // split. Sweeps every one of the four arms
7999        // [`RestartStrategy::ALL`] carries so no arm's projection is
8000        // covered only by the sibling method-named `as_str` /
8001        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
8002        // `<&'static str as From<RestartStrategy>>::from` output in a
8003        // `const`-shape binding to make the `'static` lifetime promise a
8004        // build-time invariant — a future accidental downgrade of any of
8005        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8006        // constants to a non-`&'static str` (a `String::leak()`-produced
8007        // return, a `Box::leak`-cast) trips at caixa-core build time
8008        // rather than at a downstream `'static`-bound consumer.
8009        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8010        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8011        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8012        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8013        for &variant in RestartStrategy::ALL {
8014            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8015            let via_method: &'static str = variant.as_str();
8016            assert_eq!(
8017                via_trait, via_method,
8018                "From<RestartStrategy> for &'static str impl must round-trip \
8019                 RestartStrategy::{variant:?} to the same lifted \
8020                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
8021                 divergence signals a silent detour off the substrate-primitive \
8022                 accessor"
8023            );
8024            let via_into: &'static str = variant.into();
8025            assert_eq!(
8026                via_into, via_method,
8027                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
8028                 byte-equal RestartStrategy::as_str on the same input — the \
8029                 blanket-derived Into shape must resolve to the same as_str \
8030                 dispatch as the explicit From impl"
8031            );
8032        }
8033        assert_eq!(
8034            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8035            [
8036                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8037                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8038                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8039                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8040            ],
8041            "const-context RestartStrategy::as_str must resolve to the four \
8042             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
8043             downgrade of any arm to a non-const or non-static byte-string \
8044             breaks the `&'static str`-lifetime promise the paired \
8045             From<RestartStrategy> for &'static str impl carries by \
8046             construction"
8047        );
8048    }
8049
8050    #[test]
8051    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
8052        // Cross-axis partition pin: the paired trait-idiomatic
8053        // `From<RestartStrategy> for &'static str` forward projection and
8054        // the method-named [`RestartStrategy::as_str`] forward projection
8055        // must resolve identically on *every* arm, not just the ones
8056        // named in the primary byte-parity pin above. Sweeps every
8057        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
8058        // output byte-equals the method-named accessor's return-value on
8059        // each, locking the two forward-projection paths together by
8060        // construction so any future detour (a stray `From` special-case
8061        // that lands on a divergent per-arm literal outside the paired
8062        // `as_str` dispatch, a hypothetical rebrand touching one axis
8063        // without the other) trips at caixa-core test time. Peer of the
8064        // sibling reverse-projection partition pin
8065        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
8066        // — extends the round-trip discipline onto the trait-idiomatic
8067        // *forward* axis, closing the two-way `Self ↔ &'static str`
8068        // round-trip on the trait-idiomatic pair
8069        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
8070        // well as the pre-existing method-named pair
8071        // (`as_str` + `from_wire`).
8072        for &variant in RestartStrategy::ALL {
8073            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8074            let via_method: &'static str = variant.as_str();
8075            assert_eq!(
8076                via_trait, via_method,
8077                "From<RestartStrategy> for &'static str and \
8078                 RestartStrategy::as_str must resolve identically on \
8079                 RestartStrategy::{variant:?} — divergence signals the \
8080                 two forward-projection paths have drifted onto different \
8081                 emit-sets"
8082            );
8083        }
8084        // Round-trip witness: every arm's forward `From` output re-parses
8085        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8086        // to the original variant. Closes the two-way `RestartStrategy ↔
8087        // &'static str` round-trip on the trait-idiomatic axis pair,
8088        // mirroring the pre-existing method-named `as_str` + `from_wire`
8089        // round-trip on the substrate-primitive axis pair.
8090        for &variant in RestartStrategy::ALL {
8091            let emitted: &'static str = variant.into();
8092            let re_parsed: Result<RestartStrategy, ()> =
8093                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8094            assert_eq!(
8095                re_parsed,
8096                Ok(variant),
8097                "trait-idiomatic axis pair must round-trip \
8098                 RestartStrategy::{variant:?} through `.into::<&'static \
8099                 str>()` and back through `TryFrom<&str>` — a break signals \
8100                 the forward-emit and reverse-parse axes have drifted onto \
8101                 different vocabularies"
8102            );
8103        }
8104    }
8105
8106    #[test]
8107    fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
8108        // Fail-before-pass-after byte-parity pin on the newly lifted
8109        // `impl From<&RestartStrategy> for &'static str` — asserts the
8110        // borrowed-input standard-library trait impl and the substrate-
8111        // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
8112        // resolve to the same four-arm emit-set across every arm the
8113        // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
8114        // `From` trait does not auto-derive the borrowed-input sibling
8115        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8116        // where T: Copy, U: From<T>` blanket in `core`), so the
8117        // borrowed-input axis is a distinct trait-idiomatic surface
8118        // that a `.iter().map(Into::into)` shape over
8119        // [`RestartStrategy::ALL`] (whose iterator yields
8120        // `&RestartStrategy`, not `RestartStrategy`) reaches through
8121        // this impl and no other — the paired owned-input
8122        // [`From<RestartStrategy>`] impl requires an explicit
8123        // `.copied()` / dereference before the trait fires.
8124        // Materializes the `<&'static str as
8125        // From<&RestartStrategy>>::from` output in a `const`-shape
8126        // binding to make the `'static` lifetime promise a build-time
8127        // invariant.
8128        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8129        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8130        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8131        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8132        for variant in RestartStrategy::ALL {
8133            let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
8134            let via_method: &'static str = variant.as_str();
8135            assert_eq!(
8136                via_trait, via_method,
8137                "From<&RestartStrategy> for &'static str impl must \
8138                 round-trip &RestartStrategy::{variant:?} to the same \
8139                 lifted SUPERVISOR_ESTRATEGIA_* const \
8140                 RestartStrategy::as_str returns — divergence signals a \
8141                 silent detour off the substrate-primitive accessor"
8142            );
8143            let via_into: &'static str = variant.into();
8144            assert_eq!(
8145                via_into, via_method,
8146                "Into<&'static str>::into on &RestartStrategy::{variant:?} \
8147                 must byte-equal RestartStrategy::as_str on the same input — \
8148                 the blanket-derived Into shape must resolve to the same \
8149                 as_str dispatch as the explicit From impl"
8150            );
8151        }
8152        assert_eq!(
8153            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8154            [
8155                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8156                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8157                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8158                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8159            ],
8160            "const-context RestartStrategy::as_str must resolve to the \
8161             four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
8162             input From<&RestartStrategy> for &'static str impl inherits \
8163             its `'static` lifetime promise from the same accessor the \
8164             owned-input sibling routes through"
8165        );
8166    }
8167
8168    #[test]
8169    fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8170        // Cross-axis partition pin: the paired trait-idiomatic
8171        // owned-input `From<RestartStrategy> for &'static str` (523157d
8172        // campaign-shape) and borrowed-input `From<&RestartStrategy> for
8173        // &'static str` (this lift) forward projections must resolve
8174        // identically on every arm, locking the two input-shape paths
8175        // together so any future detour trips at caixa-core test time.
8176        // Then a witness that a `.iter().map(Into::into)` pipe over
8177        // [`RestartStrategy::ALL`] (whose iterator yields
8178        // `&RestartStrategy`) materializes the four-arm accept-set
8179        // through the borrowed-input axis alone — the exact shape a
8180        // future wasm-operator per-supervisor sibling-restart-strategy
8181        // diagnostic line, a future substrate-wide per-arm diagnostic
8182        // column, or a
8183        // `HashMap::<&'static str, RestartStrategy>::from_iter(
8184        //     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
8185        // per-strategy lookup reaches through — closing the two-way
8186        // owned/borrowed input-shape symmetry on the forward-projection
8187        // trait-idiomatic axis. Peer of the sibling
8188        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8189        // (64aa742) /
8190        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8191        // (5ab993a) /
8192        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8193        // (807b0b5) partition pins on the sibling closed-set typed-enum
8194        // discriminator axes — extends the borrowed-input axis
8195        // discipline onto the first M2 OTP-shape sibling-restart
8196        // closed-set typed enum on the caixa surface. Also closes the
8197        // direct two-way `&Self → &'static str → Self` round-trip via
8198        // the paired [`TryFrom<&str>`] axis — unlike the peer
8199        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
8200        // lowercase Portuguese diagnostic bytes while the reverse
8201        // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
8202        // trip through an intermediate wire-vocab hop), the
8203        // [`RestartStrategy::as_str`] emit and
8204        // [`RestartStrategy::from_wire`] parse share the same
8205        // `PascalCase` vocabulary by construction, so the borrowed-
8206        // input forward axis and the reverse axis compose directly.
8207        for &variant in RestartStrategy::ALL {
8208            let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8209            let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
8210            assert_eq!(
8211                owned, borrowed,
8212                "From<RestartStrategy> and From<&RestartStrategy> for \
8213                 &'static str must resolve identically on \
8214                 RestartStrategy::{variant:?} — divergence signals the \
8215                 owned-input and borrowed-input forward-projection paths \
8216                 have drifted onto different emit-sets"
8217            );
8218        }
8219        let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
8220        let via_method: Vec<&'static str> =
8221            RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
8222        assert_eq!(
8223            via_iter, via_method,
8224            "`.iter().map(Into::into)` over RestartStrategy::ALL must \
8225             byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
8226             borrowed-input `From<&RestartStrategy> for &'static str` \
8227             axis is what makes the `.iter().map(Into::into)` shape route \
8228             through the substrate-primitive `RestartStrategy::as_str` \
8229             accessor rather than through a per-call-site `.copied()` / \
8230             dereference detour"
8231        );
8232        for variant in RestartStrategy::ALL {
8233            let emitted: &'static str = variant.into();
8234            let re_parsed: Result<RestartStrategy, ()> =
8235                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8236            assert_eq!(
8237                re_parsed,
8238                Ok(*variant),
8239                "trait-idiomatic borrowed-input forward-projection + \
8240                 reverse-projection axis pair must round-trip \
8241                 &RestartStrategy::{variant:?} through `.into::<&'static \
8242                 str>()` (via the borrowed-input axis) and back through \
8243                 `TryFrom<&str>` — a break signals the borrowed-input \
8244                 forward-emit and reverse-parse axes have drifted onto \
8245                 different vocabularies"
8246            );
8247        }
8248    }
8249
8250    #[test]
8251    fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
8252        // Fail-before-pass-after byte-parity pin on the newly lifted
8253        // `impl From<RestartStrategy> for String` — asserts the
8254        // owned-`String`-returning standard-library trait impl and the
8255        // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
8256        // accessor resolve to the same four-arm emit-set across every
8257        // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
8258        // Rust's standard library does not carry a blanket
8259        // `impl<T: AsRef<str>> From<T> for String` (nor an
8260        // `impl<T: fmt::Display> From<T> for String`), so the
8261        // owned-`String` forward-projection axis is a distinct
8262        // trait-idiomatic surface that a
8263        // `let key: String = strategy.into();`-shaped call site
8264        // reaches through this impl and no other — the paired sibling
8265        // `From<RestartStrategy> for &'static str` impl forces every
8266        // owned-`String` call site through an explicit
8267        // `.to_owned()` / `String::from` restatement.
8268        for &variant in RestartStrategy::ALL {
8269            let via_trait: String = <String as From<RestartStrategy>>::from(variant);
8270            let via_method: &'static str = variant.as_str();
8271            assert_eq!(
8272                via_trait.as_str(),
8273                via_method,
8274                "From<RestartStrategy> for String impl must round-trip \
8275                 RestartStrategy::{variant:?} to the same lifted \
8276                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8277                 returns — divergence signals a silent detour off the \
8278                 substrate-primitive accessor"
8279            );
8280            let via_into: String = variant.into();
8281            assert_eq!(
8282                via_into.as_str(),
8283                via_method,
8284                "Into<String>::into on RestartStrategy::{variant:?} must \
8285                 byte-equal RestartStrategy::as_str on the same input — the \
8286                 blanket-derived Into shape must resolve to the same as_str \
8287                 dispatch as the explicit From impl"
8288            );
8289        }
8290    }
8291
8292    #[test]
8293    fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
8294        // Cross-axis partition pin: the paired trait-idiomatic
8295        // owned-`String` `From<RestartStrategy> for String` (this lift)
8296        // and owned-`&'static str` `From<RestartStrategy> for &'static
8297        // str` (523157d) forward projections must resolve identically
8298        // on every arm, locking the two return-type-shape paths
8299        // together so any future detour trips at caixa-core test time.
8300        // Also byte-parity witness against the sibling
8301        // [`ToString::to_string`] surface routed through
8302        // [`std::fmt::Display`] — the three owned-heap-string paths
8303        // (`.into::<String>()`, `String::from`, `.to_string()`) must
8304        // resolve identically on every arm so a future consumer that
8305        // picks any of the three lands on the same lifted
8306        // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
8307        // witness through the paired trait-idiomatic reverse
8308        // [`TryFrom<&str>`] axis on the owned-`String`'s
8309        // [`String::as_str`] borrow that closes the two-way
8310        // `Self → String → Self` round-trip on the trait-idiomatic
8311        // owned-`String` forward + reverse axis pair.
8312        for &variant in RestartStrategy::ALL {
8313            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8314            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8315            assert_eq!(
8316                owned_string.as_str(),
8317                owned_static,
8318                "From<RestartStrategy> for String and From<RestartStrategy> \
8319                 for &'static str must resolve identically on \
8320                 RestartStrategy::{variant:?} — divergence signals the \
8321                 owned-`String` and owned-`&'static str` forward-projection \
8322                 return-type-shape paths have drifted onto different \
8323                 emit-sets"
8324            );
8325            let via_to_string: String = variant.to_string();
8326            assert_eq!(
8327                owned_string, via_to_string,
8328                "From<RestartStrategy> for String must byte-equal \
8329                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8330                 divergence signals the trait-idiomatic owned-`String` \
8331                 forward-projection axis and the ToString-through-Display \
8332                 axis have drifted onto different emit-sets"
8333            );
8334        }
8335        let via_iter: Vec<String> = RestartStrategy::ALL
8336            .iter()
8337            .copied()
8338            .map(String::from)
8339            .collect();
8340        let via_method: Vec<String> = RestartStrategy::ALL
8341            .iter()
8342            .map(|s| s.as_str().to_owned())
8343            .collect();
8344        assert_eq!(
8345            via_iter, via_method,
8346            "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
8347             must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
8348             every arm — the owned-`String` `From<RestartStrategy> for \
8349             String` axis is what makes the `String::from` composition \
8350             route through the substrate-primitive `RestartStrategy::as_str` \
8351             accessor rather than through a per-call-site `.to_owned()` / \
8352             `String::from(strategy.as_str())` detour"
8353        );
8354        for &variant in RestartStrategy::ALL {
8355            let emitted: String = variant.into();
8356            let re_parsed: Result<RestartStrategy, ()> =
8357                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8358            assert_eq!(
8359                re_parsed,
8360                Ok(variant),
8361                "trait-idiomatic owned-`String` forward-projection + \
8362                 reverse-projection axis pair must round-trip \
8363                 RestartStrategy::{variant:?} through `.into::<String>()` \
8364                 and back through `TryFrom<&str>` on the owned-`String`'s \
8365                 String::as_str borrow — a break signals the owned-`String` \
8366                 forward-emit and reverse-parse axes have drifted onto \
8367                 different vocabularies"
8368            );
8369        }
8370    }
8371
8372    #[test]
8373    fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
8374        // Fail-before-pass-after byte-parity pin on the newly lifted
8375        // `impl From<&RestartStrategy> for String` — asserts the
8376        // borrowed-input owned-`String`-returning standard-library trait
8377        // impl and the substrate-primitive [`RestartStrategy::as_str`]
8378        // `pub const fn` accessor resolve to the same four-arm emit-set
8379        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
8380        // enumerates. Rust's standard library does not carry a blanket
8381        // `impl<T: AsRef<str>> From<&T> for String` (nor an
8382        // `impl<T: fmt::Display> From<&T> for String`), so the
8383        // borrowed-input owned-`String` forward-projection axis is a
8384        // distinct trait-idiomatic surface that a
8385        // `let key: String = (&strategy).into();`-shaped call site
8386        // reaches through this impl and no other — the paired sibling
8387        // `From<RestartStrategy> for String` impl forces every
8388        // borrowed-input call site through an explicit `Copy` deref
8389        // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
8390        // `.to_string()` detour.
8391        for &variant in RestartStrategy::ALL {
8392            let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
8393            let via_method: &'static str = variant.as_str();
8394            assert_eq!(
8395                via_trait.as_str(),
8396                via_method,
8397                "From<&RestartStrategy> for String impl must round-trip \
8398                 &RestartStrategy::{variant:?} to the same lifted \
8399                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8400                 returns — divergence signals a silent detour off the \
8401                 substrate-primitive accessor"
8402            );
8403            let via_into: String = (&variant).into();
8404            assert_eq!(
8405                via_into.as_str(),
8406                via_method,
8407                "Into<String>::into on &RestartStrategy::{variant:?} must \
8408                 byte-equal RestartStrategy::as_str on the same input — the \
8409                 blanket-derived Into shape must resolve to the same as_str \
8410                 dispatch as the explicit From impl"
8411            );
8412        }
8413    }
8414
8415    #[test]
8416    fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
8417        // Cross-axis partition pin: the newly lifted trait-idiomatic
8418        // borrowed-input owned-`String` `From<&RestartStrategy> for
8419        // String` (this lift), the paired owned-input owned-`String`
8420        // `From<RestartStrategy> for String` (7baa18a), the paired
8421        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8422        // for &'static str` (e941836), and the paired owned-input
8423        // owned-`&'static str` `From<RestartStrategy> for &'static str`
8424        // (523157d) — every corner of the `{Self, &Self} × {&'static
8425        // str, String}` 2×2 trait-idiomatic projection family — must
8426        // resolve identically on every arm, locking the four
8427        // return-shape × input-shape paths together so any future
8428        // detour trips at caixa-core test time. Also byte-parity
8429        // witness against the sibling [`ToString::to_string`] surface
8430        // routed through [`std::fmt::Display`] and a direct round-trip
8431        // witness through the paired trait-idiomatic reverse
8432        // [`TryFrom<&str>`] axis on the owned-`String`'s
8433        // [`String::as_str`] borrow that closes the two-way
8434        // `&Self → String → Self` round-trip on the trait-idiomatic
8435        // borrowed-input owned-`String` forward + reverse axis pair.
8436        for &variant in RestartStrategy::ALL {
8437            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
8438            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8439            let borrowed_static: &'static str =
8440                <&'static str as From<&RestartStrategy>>::from(&variant);
8441            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8442            assert_eq!(
8443                borrowed_string, owned_string,
8444                "From<&RestartStrategy> for String and From<RestartStrategy> \
8445                 for String must resolve identically on \
8446                 RestartStrategy::{variant:?} — divergence signals the \
8447                 borrowed-input and owned-input owned-`String` \
8448                 forward-projection input-shape paths have drifted onto \
8449                 different emit-sets"
8450            );
8451            assert_eq!(
8452                borrowed_string.as_str(),
8453                borrowed_static,
8454                "From<&RestartStrategy> for String and From<&RestartStrategy> \
8455                 for &'static str must resolve identically on \
8456                 RestartStrategy::{variant:?} — divergence signals the \
8457                 borrowed-input `&'static str` and owned-`String` \
8458                 return-shape paths have drifted onto different emit-sets"
8459            );
8460            assert_eq!(
8461                borrowed_string.as_str(),
8462                owned_static,
8463                "From<&RestartStrategy> for String and From<RestartStrategy> \
8464                 for &'static str must resolve identically on \
8465                 RestartStrategy::{variant:?} — divergence signals a break \
8466                 in the diagonal corner of the {{Self, &Self}} × \
8467                 {{&'static str, String}} 2×2 trait-idiomatic \
8468                 projection family"
8469            );
8470            let via_to_string: String = variant.to_string();
8471            assert_eq!(
8472                borrowed_string, via_to_string,
8473                "From<&RestartStrategy> for String must byte-equal \
8474                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8475                 divergence signals the trait-idiomatic borrowed-input \
8476                 owned-`String` forward-projection axis and the \
8477                 ToString-through-Display axis have drifted onto different \
8478                 emit-sets"
8479            );
8480        }
8481        let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
8482        let via_method: Vec<String> = RestartStrategy::ALL
8483            .iter()
8484            .map(|s| s.as_str().to_owned())
8485            .collect();
8486        assert_eq!(
8487            via_iter, via_method,
8488            "`.iter().map(String::from)` over RestartStrategy::ALL — a \
8489             call site whose iteration axis holds `&RestartStrategy` by \
8490             construction — must byte-equal `.iter().map(|s| \
8491             s.as_str().to_owned())` on every arm — the borrowed-input \
8492             owned-`String` `From<&RestartStrategy> for String` axis is \
8493             what makes the `String::from` composition route through the \
8494             substrate-primitive `RestartStrategy::as_str` accessor \
8495             without a spurious `Copy` deref (which would only be \
8496             reachable through the owned-input `From<RestartStrategy> for \
8497             String` axis by first calling `.copied()` on the iterator)"
8498        );
8499        for &variant in RestartStrategy::ALL {
8500            let emitted: String = (&variant).into();
8501            let re_parsed: Result<RestartStrategy, ()> =
8502                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8503            assert_eq!(
8504                re_parsed,
8505                Ok(variant),
8506                "trait-idiomatic borrowed-input owned-`String` \
8507                 forward-projection + reverse-projection axis pair must \
8508                 round-trip &RestartStrategy::{variant:?} through \
8509                 `.into::<String>()` on the borrowed-input surface and \
8510                 back through `TryFrom<&str>` on the owned-`String`'s \
8511                 String::as_str borrow — a break signals the \
8512                 borrowed-input owned-`String` forward-emit and \
8513                 reverse-parse axes have drifted onto different \
8514                 vocabularies"
8515            );
8516        }
8517    }
8518
8519    #[test]
8520    fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
8521        // Fail-before-pass-after byte-parity pin on the newly lifted
8522        // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
8523        // asserts the standard-library trait impl and the substrate-
8524        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
8525        // accessor resolve to the same four-arm emit-set across every
8526        // arm the exhaustive [`super::RestartStrategy::ALL`] slice
8527        // enumerates. Rust's standard library does not carry a blanket
8528        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
8529        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
8530        // the `Cow<'static, str>` forward-projection axis is a
8531        // distinct trait-idiomatic surface that a
8532        // `let key: Cow<'static, str> = strategy.into();`-shaped call
8533        // site reaches through this impl and no other — the paired
8534        // sibling `From<RestartStrategy> for &'static str` and
8535        // `From<RestartStrategy> for String` impls force every
8536        // `Cow<'static, str>`-parameterized call site through a
8537        // `Cow::Borrowed(strategy.as_str())` /
8538        // `Cow::Owned(strategy.to_string())` composition whose type
8539        // bounds have no compile-time link back to the substrate
8540        // primitive.
8541        //
8542        // Also asserts the projection lands on the zero-alloc
8543        // [`std::borrow::Cow::Borrowed`] arm (not the
8544        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8545        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8546        // return lifetime by construction makes the borrowed arm the
8547        // type-correct projection with no runtime allocation. Any
8548        // future silent detour that routes the impl through the owned
8549        // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
8550        // that would allocate on every call site where the
8551        // `&'static str` return of [`super::RestartStrategy::as_str`]
8552        // makes the zero-alloc borrowed projection type-correct) trips
8553        // at caixa-core test time under the
8554        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
8555        // than at a downstream `Cow<'static, str>`-bound consumer's
8556        // silent allocation.
8557        //
8558        // First peer on the substrate-wide trait-idiomatic
8559        // [`std::borrow::Cow<'static, str>`] forward-projection family
8560        // to extend the axis off the top-level [`super::CaixaKind`]
8561        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
8562        // first M2 OTP-shape closed-set fieldless typed enum on the
8563        // caixa surface.
8564        for &variant in RestartStrategy::ALL {
8565            let via_trait: std::borrow::Cow<'static, str> =
8566                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8567            let via_method: &'static str = variant.as_str();
8568            assert_eq!(
8569                via_trait.as_ref(),
8570                via_method,
8571                "From<RestartStrategy> for Cow<'static, str> impl must \
8572                 round-trip RestartStrategy::{variant:?} to the same \
8573                 lifted SUPERVISOR_ESTRATEGIA_* const \
8574                 RestartStrategy::as_str returns — divergence signals a \
8575                 silent detour off the substrate-primitive accessor"
8576            );
8577            assert!(
8578                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
8579                "From<RestartStrategy> for Cow<'static, str> impl must \
8580                 land on the zero-alloc Cow::Borrowed arm on \
8581                 RestartStrategy::{variant:?} — a Cow::Owned outcome \
8582                 signals the projection has silently allocated where \
8583                 the substrate-primitive RestartStrategy::as_str \
8584                 `&'static str` return makes the borrowed arm the \
8585                 type-correct projection"
8586            );
8587            let via_into: std::borrow::Cow<'static, str> = variant.into();
8588            assert_eq!(
8589                via_into.as_ref(),
8590                via_method,
8591                "Into<Cow<'static, str>>::into on \
8592                 RestartStrategy::{variant:?} must byte-equal \
8593                 RestartStrategy::as_str on the same input — the \
8594                 blanket-derived Into shape must resolve to the same \
8595                 as_str dispatch as the explicit From impl"
8596            );
8597            assert!(
8598                matches!(via_into, std::borrow::Cow::Borrowed(_)),
8599                "Into<Cow<'static, str>>::into on \
8600                 RestartStrategy::{variant:?} must land on the \
8601                 zero-alloc Cow::Borrowed arm — the blanket-derived \
8602                 Into shape must resolve to the same Cow::Borrowed \
8603                 dispatch as the explicit From impl"
8604            );
8605        }
8606    }
8607
8608    #[test]
8609    fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
8610        // Cross-axis partition pin: the newly lifted trait-idiomatic
8611        // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
8612        // (this lift), the paired owned-input `From<RestartStrategy>
8613        // for &'static str` (523157d), and the paired owned-input
8614        // `From<RestartStrategy> for String` (7baa18a) forward
8615        // projections must resolve identically on every arm, locking
8616        // the three return-shape paths together by construction so any
8617        // future detour trips at caixa-core test time. Also byte-parity
8618        // witness against the sibling [`ToString::to_string`] surface
8619        // routed through [`std::fmt::Display`] — every owned-heap-
8620        // string path (the `Cow::Owned` promotion of this axis's
8621        // `.into_owned()`, `From<RestartStrategy> for String`, and
8622        // `.to_string()`) resolves to the same lifted
8623        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
8624        //
8625        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
8626        // witness over [`super::RestartStrategy::ALL`] that
8627        // materializes the four-arm accept-set through the
8628        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
8629        // shape a future `axum::response::IntoResponse` per-strategy
8630        // rejection-body composer, a future M4 admission-webhook
8631        // per-strategy rejection-reason emitter whose typing rules out
8632        // the sibling [`AsRef<str>`] borrowed return, or a future
8633        // substrate-wide per-strategy diagnostic surface that binds
8634        // through a [`Cow<'static, str>`] boundary reaches through.
8635        // The pipe witness also pins the zero-alloc discipline: every
8636        // element in the collected vector satisfies the
8637        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
8638        // accidental silent-allocation regression on the pipe's
8639        // iteration axis is a caixa-core-test-time failure.
8640        for &variant in RestartStrategy::ALL {
8641            let via_cow: std::borrow::Cow<'static, str> =
8642                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8643            let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8644            let via_string: String = <String as From<RestartStrategy>>::from(variant);
8645            assert_eq!(
8646                via_cow.as_ref(),
8647                via_static,
8648                "From<RestartStrategy> for Cow<'static, str> and \
8649                 From<RestartStrategy> for &'static str must resolve \
8650                 identically on RestartStrategy::{variant:?} — \
8651                 divergence signals the Cow<'static, str> and \
8652                 &'static str return-shape paths have drifted onto \
8653                 different emit-sets"
8654            );
8655            assert_eq!(
8656                via_cow.as_ref(),
8657                via_string.as_str(),
8658                "From<RestartStrategy> for Cow<'static, str> and \
8659                 From<RestartStrategy> for String must resolve \
8660                 identically on RestartStrategy::{variant:?} — \
8661                 divergence signals the Cow<'static, str> and String \
8662                 return-shape paths have drifted onto different \
8663                 emit-sets"
8664            );
8665            let via_to_string: String = variant.to_string();
8666            assert_eq!(
8667                via_cow.as_ref(),
8668                via_to_string.as_str(),
8669                "From<RestartStrategy> for Cow<'static, str> must \
8670                 byte-equal RestartStrategy::to_string on \
8671                 RestartStrategy::{variant:?} — divergence signals the \
8672                 trait-idiomatic Cow<'static, str> forward-projection \
8673                 axis and the ToString-through-Display axis have \
8674                 drifted onto different emit-sets"
8675            );
8676        }
8677        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8678            .iter()
8679            .copied()
8680            .map(std::borrow::Cow::from)
8681            .collect();
8682        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8683            .iter()
8684            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
8685            .collect();
8686        assert_eq!(
8687            via_iter, via_method,
8688            "`.iter().copied().map(Cow::from)` over \
8689             RestartStrategy::ALL must byte-equal `.iter().map(|s| \
8690             Cow::Borrowed(s.as_str()))` on every arm — the \
8691             trait-idiomatic `From<RestartStrategy> for Cow<'static, \
8692             str>` axis is what makes the `Cow::from` composition \
8693             route through the substrate-primitive \
8694             `RestartStrategy::as_str` accessor with the zero-alloc \
8695             Cow::Borrowed arm by construction, rather than a \
8696             per-call-site `Cow::Owned(strategy.to_string())` \
8697             allocation"
8698        );
8699        for cow in &via_iter {
8700            assert!(
8701                matches!(cow, std::borrow::Cow::Borrowed(_)),
8702                "every element of the \
8703                 .iter().copied().map(Cow::from) pipe over \
8704                 RestartStrategy::ALL must land on the zero-alloc \
8705                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
8706                 signals the pipe's iteration axis has silently \
8707                 allocated where the substrate-primitive \
8708                 RestartStrategy::as_str `&'static str` return makes \
8709                 the borrowed arm the type-correct projection"
8710            );
8711        }
8712    }
8713
8714    #[test]
8715    fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
8716        // Fail-before-pass-after byte-parity pin on the newly lifted
8717        // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
8718        // asserts the borrowed-input standard-library trait impl and
8719        // the substrate-primitive [`super::RestartStrategy::as_str`]
8720        // `pub const fn` accessor resolve to the same four-arm emit-
8721        // set across every arm the exhaustive
8722        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
8723        // standard library does not carry a blanket
8724        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
8725        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
8726        // the borrowed-input `Cow<'static, str>` forward-projection
8727        // axis is a distinct trait-idiomatic surface that a
8728        // `let key: Cow<'static, str> = (&strategy).into();`-shaped
8729        // call site or a
8730        // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
8731        // reaches through this impl and no other — the paired owned-
8732        // input `From<RestartStrategy> for Cow<'static, str>` impl
8733        // (7dd28b3) forces every borrowed-input call site through an
8734        // explicit `Copy` deref (`Cow::from(*strategy)`) or a
8735        // `Cow::Borrowed(strategy.as_str())` open-code whose type
8736        // bounds have no compile-time link back to the substrate
8737        // primitive.
8738        //
8739        // Also asserts the projection lands on the zero-alloc
8740        // [`std::borrow::Cow::Borrowed`] arm (not the
8741        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8742        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8743        // return lifetime by construction makes the borrowed arm the
8744        // type-correct projection with no runtime allocation on the
8745        // borrowed-input surface just as on the paired owned-input
8746        // surface.
8747        //
8748        // Second peer on the substrate-wide trait-idiomatic
8749        // [`std::borrow::Cow<'static, str>`] forward-projection family
8750        // on this enum — closes the `{Self, &Self}` input-shape
8751        // corner of the [`Cow<'static, str>`] axis on the first M2
8752        // OTP-shape closed-set fieldless typed enum peer on the caixa
8753        // surface (`:supervisor :estrategia`), exactly as d45c409
8754        // closed it on the top-level [`super::CaixaKind`] one commit
8755        // after the owning half (99c1735) landed. Every future
8756        // closed-set fieldless typed enum peer on the substrate is a
8757        // future target of the campaign.
8758        for &variant in RestartStrategy::ALL {
8759            let via_trait: std::borrow::Cow<'static, str> =
8760                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
8761            let via_method: &'static str = variant.as_str();
8762            assert_eq!(
8763                via_trait.as_ref(),
8764                via_method,
8765                "From<&RestartStrategy> for Cow<'static, str> impl must \
8766                 round-trip &RestartStrategy::{variant:?} to the same \
8767                 lifted SUPERVISOR_ESTRATEGIA_* const \
8768                 RestartStrategy::as_str returns — divergence signals a \
8769                 silent detour off the substrate-primitive accessor"
8770            );
8771            assert!(
8772                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
8773                "From<&RestartStrategy> for Cow<'static, str> impl must \
8774                 land on the zero-alloc Cow::Borrowed arm on \
8775                 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
8776                 signals the projection has silently allocated where \
8777                 the substrate-primitive RestartStrategy::as_str \
8778                 `&'static str` return makes the borrowed arm the \
8779                 type-correct projection"
8780            );
8781            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
8782            assert_eq!(
8783                via_into.as_ref(),
8784                via_method,
8785                "Into<Cow<'static, str>>::into on \
8786                 &RestartStrategy::{variant:?} must byte-equal \
8787                 RestartStrategy::as_str on the same input — the \
8788                 blanket-derived Into shape must resolve to the same \
8789                 as_str dispatch as the explicit From impl"
8790            );
8791            assert!(
8792                matches!(via_into, std::borrow::Cow::Borrowed(_)),
8793                "Into<Cow<'static, str>>::into on \
8794                 &RestartStrategy::{variant:?} must land on the \
8795                 zero-alloc Cow::Borrowed arm — the blanket-derived \
8796                 Into shape must resolve to the same Cow::Borrowed \
8797                 dispatch as the explicit From impl"
8798            );
8799        }
8800    }
8801
8802    #[test]
8803    fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
8804        // Cross-axis partition pin: the newly lifted trait-idiomatic
8805        // borrowed-input `From<&RestartStrategy> for
8806        // std::borrow::Cow<'static, str>` (this lift), the paired
8807        // owned-input `From<RestartStrategy> for
8808        // std::borrow::Cow<'static, str>` (7dd28b3), the paired
8809        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8810        // for &'static str`, and the paired borrowed-input owned-
8811        // `String` `From<&RestartStrategy> for String` must resolve
8812        // identically on every arm, locking the four
8813        // return-shape × input-shape paths together by construction so
8814        // any future detour trips at caixa-core test time. Also byte-
8815        // parity witness against the sibling [`ToString::to_string`]
8816        // surface routed through [`std::fmt::Display`] — every owned-
8817        // heap-string path (this axis's `.into_owned()` promotion, the
8818        // paired [`From<&RestartStrategy> for String`], and
8819        // `.to_string()`) resolves to the same lifted
8820        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
8821        //
8822        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
8823        // over [`super::RestartStrategy::ALL`] — whose iterator yields
8824        // `&RestartStrategy` by construction, so the borrowed-input
8825        // [`Cow<'static, str>`] axis is what routes the pipe through
8826        // the substrate-primitive [`super::RestartStrategy::as_str`]
8827        // accessor without a spurious [`Copy`] deref (which would only
8828        // be reachable through the owned-input
8829        // [`From<RestartStrategy> for Cow<'static, str>`] axis by
8830        // first calling `.copied()` on the iterator). The pipe witness
8831        // also pins the zero-alloc discipline: every element in the
8832        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
8833        // arm predicate, so a future accidental silent-allocation
8834        // regression on the pipe's iteration axis is a caixa-core-
8835        // test-time failure.
8836        for &strategy in RestartStrategy::ALL {
8837            let borrowed_cow: std::borrow::Cow<'static, str> =
8838                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
8839            let owned_cow: std::borrow::Cow<'static, str> =
8840                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
8841            let borrowed_static: &'static str =
8842                <&'static str as From<&RestartStrategy>>::from(&strategy);
8843            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
8844            assert_eq!(
8845                borrowed_cow, owned_cow,
8846                "From<&RestartStrategy> for Cow<'static, str> and \
8847                 From<RestartStrategy> for Cow<'static, str> must \
8848                 resolve identically on RestartStrategy::{strategy:?} — \
8849                 divergence signals the borrowed-input and owned-input \
8850                 Cow<'static, str> forward-projection input-shape \
8851                 paths have drifted onto different emit-sets"
8852            );
8853            assert_eq!(
8854                borrowed_cow.as_ref(),
8855                borrowed_static,
8856                "From<&RestartStrategy> for Cow<'static, str> and \
8857                 From<&RestartStrategy> for &'static str must resolve \
8858                 identically on RestartStrategy::{strategy:?} — \
8859                 divergence signals the borrowed-input Cow<'static, \
8860                 str> and &'static str return-shape paths have drifted \
8861                 onto different emit-sets"
8862            );
8863            assert_eq!(
8864                borrowed_cow.as_ref(),
8865                borrowed_string.as_str(),
8866                "From<&RestartStrategy> for Cow<'static, str> and \
8867                 From<&RestartStrategy> for String must resolve \
8868                 identically on RestartStrategy::{strategy:?} — \
8869                 divergence signals the borrowed-input Cow<'static, \
8870                 str> and owned-`String` return-shape paths have \
8871                 drifted onto different emit-sets"
8872            );
8873            let via_to_string: String = strategy.to_string();
8874            assert_eq!(
8875                borrowed_cow.as_ref(),
8876                via_to_string.as_str(),
8877                "From<&RestartStrategy> for Cow<'static, str> must \
8878                 byte-equal RestartStrategy::to_string on \
8879                 RestartStrategy::{strategy:?} — divergence signals \
8880                 the trait-idiomatic borrowed-input Cow<'static, str> \
8881                 forward-projection axis and the ToString-through-\
8882                 Display axis have drifted onto different emit-sets"
8883            );
8884        }
8885        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8886            .iter()
8887            .map(std::borrow::Cow::from)
8888            .collect();
8889        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8890            .iter()
8891            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
8892            .collect();
8893        assert_eq!(
8894            via_iter, via_method,
8895            "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
8896             call site whose iteration axis holds `&RestartStrategy` \
8897             by construction — must byte-equal `.iter().map(|s| \
8898             Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
8899             input Cow<'static, str> `From<&RestartStrategy> for \
8900             Cow<'static, str>` axis is what makes the `Cow::from` \
8901             composition route through the substrate-primitive \
8902             `RestartStrategy::as_str` accessor with the zero-alloc \
8903             Cow::Borrowed arm by construction and without a spurious \
8904             `Copy` deref (which would only be reachable through the \
8905             owned-input `From<RestartStrategy> for Cow<'static, str>` \
8906             axis by first calling `.copied()` on the iterator)"
8907        );
8908        for cow in &via_iter {
8909            assert!(
8910                matches!(cow, std::borrow::Cow::Borrowed(_)),
8911                "every element of the .iter().map(Cow::from) pipe \
8912                 over RestartStrategy::ALL must land on the zero-\
8913                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
8914                 any arm signals the pipe's iteration axis has \
8915                 silently allocated where the substrate-primitive \
8916                 RestartStrategy::as_str `&'static str` return makes \
8917                 the borrowed arm the type-correct projection"
8918            );
8919        }
8920    }
8921
8922    #[test]
8923    fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
8924        // Fail-before-pass-after byte-parity pin on the newly lifted
8925        // `impl From<RestartStrategy> for Box<str>` — asserts the
8926        // owned-input standard-library trait impl and the
8927        // substrate-primitive [`super::RestartStrategy::as_str`]
8928        // `pub const fn` accessor resolve to the same four-arm emit-
8929        // set across every arm the exhaustive
8930        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
8931        // substrate-wide `Box<str>` forward-projection campaign tier
8932        // on the first M2 OTP-shape closed-set fieldless typed enum
8933        // peer on the caixa surface (`:supervisor :estrategia`),
8934        // immediately after the paired `Cow<'static, str>` axis
8935        // (7dd28b3 / ee577fd) closed the
8936        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
8937        // 2×3 corner on this enum. Rust's standard library carries
8938        // `impl From<&str> for Box<str>` and
8939        // `impl From<String> for Box<str>` but no blanket
8940        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
8941        // a distinct trait-idiomatic surface that a
8942        // `let key: Box<str> = strategy.into();`-shaped call site
8943        // reaches through this impl and no other — a paired
8944        // `Box::from(strategy.as_str())` open-code has no compile-
8945        // time link back to the substrate primitive.
8946        for &variant in RestartStrategy::ALL {
8947            let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
8948            let via_method: &'static str = variant.as_str();
8949            assert_eq!(
8950                via_trait.as_ref(),
8951                via_method,
8952                "From<RestartStrategy> for Box<str> impl must round-\
8953                 trip RestartStrategy::{variant:?} to the same lifted \
8954                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8955                 returns — divergence signals a silent detour off the \
8956                 substrate-primitive accessor"
8957            );
8958            let via_into: Box<str> = variant.into();
8959            assert_eq!(
8960                via_into.as_ref(),
8961                via_method,
8962                "Into<Box<str>>::into on RestartStrategy::{variant:?} \
8963                 must byte-equal RestartStrategy::as_str on the same \
8964                 input — the blanket-derived Into shape must resolve \
8965                 to the same as_str dispatch as the explicit From impl"
8966            );
8967        }
8968    }
8969
8970    #[test]
8971    fn restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
8972        // Fail-before-pass-after byte-parity pin on the newly lifted
8973        // `impl From<&RestartStrategy> for Box<str>` — asserts the
8974        // borrowed-input standard-library trait impl and the
8975        // substrate-primitive [`super::RestartStrategy::as_str`]
8976        // `pub const fn` accessor resolve to the same four-arm emit-
8977        // set across every arm the exhaustive
8978        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
8979        // standard library does not carry a blanket
8980        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
8981        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
8982        // so the borrowed-input `Box<str>` forward-projection axis
8983        // is a distinct trait-idiomatic surface that a
8984        // `let key: Box<str> = (&strategy).into();`-shaped call site
8985        // or a `RestartStrategy::ALL.iter().map(Box::<str>::from)`-
8986        // shaped pipe reaches through this impl and no other — the
8987        // paired owned-input `From<RestartStrategy> for Box<str>`
8988        // impl (69ef45c) forces every borrowed-input call site
8989        // through an explicit `Copy` deref
8990        // (`Box::<str>::from((*strategy).as_str())`) or a
8991        // `Box::<str>::from(strategy.as_str())` open-code whose
8992        // type bounds have no compile-time link back to the
8993        // substrate primitive.
8994        //
8995        // Second peer on the substrate-wide trait-idiomatic
8996        // [`Box<str>`] forward-projection family on this enum —
8997        // closes the `{Self, &Self}` input-shape corner of the
8998        // [`Box<str>`] axis on the first M2 OTP-shape closed-set
8999        // fieldless typed enum peer on the caixa surface
9000        // (`:supervisor :estrategia`), exactly as ee577fd closed
9001        // the paired [`Cow<'static, str>`] axis one commit after
9002        // its owning half (7dd28b3) landed. Every future closed-
9003        // set fieldless typed enum peer on the substrate is a
9004        // future target of the campaign.
9005        //
9006        // Also byte-parity witness against the paired owned-input
9007        // [`From<RestartStrategy> for Box<str>`] and the sibling
9008        // borrowed-input [`From<&RestartStrategy> for &'static str`],
9009        // [`From<&RestartStrategy> for String`], and
9010        // [`From<&RestartStrategy> for Cow<'static, str>`]
9011        // return-shape axes — locking the four
9012        // return-shape × input-shape paths together by construction
9013        // so any future detour trips at caixa-core test time. Then a
9014        // `.iter().map(Box::<str>::from)` pipe witness over
9015        // [`super::RestartStrategy::ALL`] — whose iterator yields
9016        // `&RestartStrategy` by construction, so the borrowed-input
9017        // [`Box<str>`] axis is what routes the pipe through the
9018        // substrate-primitive [`super::RestartStrategy::as_str`]
9019        // accessor without a spurious [`Copy`] deref (which would
9020        // only be reachable through the owned-input
9021        // [`From<RestartStrategy> for Box<str>`] axis by first
9022        // calling `.copied()` on the iterator).
9023        for &variant in RestartStrategy::ALL {
9024            let via_trait: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
9025            let via_method: &'static str = variant.as_str();
9026            assert_eq!(
9027                via_trait.as_ref(),
9028                via_method,
9029                "From<&RestartStrategy> for Box<str> impl must \
9030                 round-trip &RestartStrategy::{variant:?} to the same \
9031                 lifted SUPERVISOR_ESTRATEGIA_* const \
9032                 RestartStrategy::as_str returns — divergence signals \
9033                 a silent detour off the substrate-primitive accessor"
9034            );
9035            let via_into: Box<str> = (&variant).into();
9036            assert_eq!(
9037                via_into.as_ref(),
9038                via_method,
9039                "Into<Box<str>>::into on &RestartStrategy::{variant:?} \
9040                 must byte-equal RestartStrategy::as_str on the same \
9041                 input — the blanket-derived Into shape must resolve \
9042                 to the same as_str dispatch as the explicit From impl"
9043            );
9044            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9045            assert_eq!(
9046                via_trait, owned_box,
9047                "From<&RestartStrategy> for Box<str> and \
9048                 From<RestartStrategy> for Box<str> must resolve \
9049                 identically on RestartStrategy::{variant:?} — \
9050                 divergence signals the borrowed-input and owned-input \
9051                 Box<str> forward-projection input-shape paths have \
9052                 drifted onto different emit-sets"
9053            );
9054            let borrowed_static: &'static str =
9055                <&'static str as From<&RestartStrategy>>::from(&variant);
9056            assert_eq!(
9057                via_trait.as_ref(),
9058                borrowed_static,
9059                "From<&RestartStrategy> for Box<str> and \
9060                 From<&RestartStrategy> for &'static str must resolve \
9061                 identically on RestartStrategy::{variant:?} — \
9062                 divergence signals the borrowed-input Box<str> and \
9063                 &'static str return-shape paths have drifted onto \
9064                 different emit-sets"
9065            );
9066            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9067            assert_eq!(
9068                via_trait.as_ref(),
9069                borrowed_string.as_str(),
9070                "From<&RestartStrategy> for Box<str> and \
9071                 From<&RestartStrategy> for String must resolve \
9072                 identically on RestartStrategy::{variant:?} — \
9073                 divergence signals the borrowed-input Box<str> and \
9074                 owned-`String` return-shape paths have drifted onto \
9075                 different emit-sets"
9076            );
9077            let borrowed_cow: std::borrow::Cow<'static, str> =
9078                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9079            assert_eq!(
9080                via_trait.as_ref(),
9081                borrowed_cow.as_ref(),
9082                "From<&RestartStrategy> for Box<str> and \
9083                 From<&RestartStrategy> for Cow<'static, str> must \
9084                 resolve identically on RestartStrategy::{variant:?} — \
9085                 divergence signals the borrowed-input Box<str> and \
9086                 Cow<'static, str> return-shape paths have drifted \
9087                 onto different emit-sets"
9088            );
9089        }
9090        let via_iter: Vec<Box<str>> = RestartStrategy::ALL.iter().map(Box::<str>::from).collect();
9091        let via_method: Vec<Box<str>> = RestartStrategy::ALL
9092            .iter()
9093            .map(|s| Box::<str>::from(s.as_str()))
9094            .collect();
9095        assert_eq!(
9096            via_iter, via_method,
9097            "`.iter().map(Box::<str>::from)` over \
9098             RestartStrategy::ALL — a call site whose iteration axis \
9099             holds `&RestartStrategy` by construction — must byte-\
9100             equal `.iter().map(|s| Box::<str>::from(s.as_str()))` \
9101             on every arm — the borrowed-input Box<str> \
9102             `From<&RestartStrategy> for Box<str>` axis is what \
9103             makes the `Box::<str>::from` composition route through \
9104             the substrate-primitive `RestartStrategy::as_str` \
9105             accessor without a spurious `Copy` deref (which would \
9106             only be reachable through the owned-input \
9107             `From<RestartStrategy> for Box<str>` axis by first \
9108             calling `.copied()` on the iterator)"
9109        );
9110    }
9111
9112    #[test]
9113    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
9114        // Fail-before-pass-after byte-parity pin on the newly lifted
9115        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
9116        // library trait impl and the substrate-primitive
9117        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
9118        // the same three-arm accept-set across every arm the exhaustive
9119        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
9120        // detour that routes the trait impl through a divergent
9121        // projection (a per-arm inline `match s { "Permanent" =>
9122        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
9123        // link to the un-lifted arm-literal, a hypothetical
9124        // `#[serde(rename_all = "…")]` attribute drift that silently
9125        // splits the wire byte-string from every consumer that reaches
9126        // for this typed dispatch, an accidental swap onto the kebab-case
9127        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
9128        // impl parses through and which would collide the two-axis
9129        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
9130        // doc block makes load-bearing) trips at caixa-core test time
9131        // under `assert_eq!` rather than at a downstream
9132        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
9133        // every one of the three arms [`RestartPolicy::ALL`] carries so
9134        // no arm's projection is covered only by the sibling method-
9135        // named `from_wire` path. Peer of the sibling
9136        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
9137        // (5b828ed) — extends the trait-idiomatic reverse-projection
9138        // axis onto the third and final M2-OTP-shape closed-set typed
9139        // enum on the caixa surface (the paired per-child restart-
9140        // decision-policy sibling on the same M2 `:supervisor` slot).
9141        for &variant in RestartPolicy::ALL {
9142            let wire = variant.as_str();
9143            assert_eq!(
9144                <RestartPolicy as TryFrom<&str>>::try_from(wire),
9145                Ok(variant),
9146                "TryFrom<&str> impl on RestartPolicy must round-trip \
9147                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
9148                 Ok(RestartPolicy::{variant:?}) — divergence from \
9149                 RestartPolicy::from_wire signals a silent detour off \
9150                 the substrate-primitive accessor"
9151            );
9152            assert_eq!(
9153                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
9154                RestartPolicy::from_wire(wire),
9155                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
9156                 equal RestartPolicy::from_wire on the same input"
9157            );
9158        }
9159    }
9160
9161    #[test]
9162    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
9163        // Rejection witness on the `impl TryFrom<&str> for
9164        // RestartPolicy` — sweeps a candidate set of byte-strings
9165        // outside the three-arm PascalCase wire accept-set the sibling
9166        // [`RestartPolicy::as_str`] emits and asserts every one lands on
9167        // `Err(())`, so a future accidental widening of the trait impl's
9168        // accept-set (a stray additional
9169        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
9170        // path, a silent inclusion of the kebab-case dispatcher-catalog
9171        // byte-string the pre-existing [`std::str::FromStr`] impl the
9172        // [`gen_platform::FromStrKind`] derive installs parses onto the
9173        // wire axis — which would collide the two-axis
9174        // wire/dispatcher-catalog split the sibling
9175        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
9176        // an English-rebrand or plural-arm silent alias that would widen
9177        // the wire accept-set past the OTP-canonical three) trips at
9178        // caixa-core test time. The candidate set includes the empty
9179        // string, whitespace-only padding, the kebab-case dispatcher-
9180        // catalog byte-strings on the sibling axis (a caller who
9181        // confuses the two axes trips here rather than at a downstream
9182        // consumer's silent reject), a lowercase / uppercase / mixed-case
9183        // fold of each PascalCase arm (a caller who assumes case-fold
9184        // acceptance trips here), leading/trailing whitespace padding,
9185        // the trailing-newline shape, quote-wrapped candidates, and a
9186        // residual set of plausible-but-wrong English rebrand
9187        // candidates. Peer of the sibling
9188        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
9189        // (5b828ed) rejection witness.
9190        let rejected: &[&str] = &[
9191            "",
9192            " ",
9193            "\n",
9194            "\t",
9195            "permanent",
9196            "temporary",
9197            "transient",
9198            "PERMANENT",
9199            "TEMPORARY",
9200            "TRANSIENT",
9201            "Permanents",
9202            "Permanent ",
9203            " Permanent",
9204            " Temporary ",
9205            "Permanent\n",
9206            "Transient\t",
9207            "\"Permanent\"",
9208            "Ephemeral",
9209            "Always",
9210            "Never",
9211            "OnAbnormalExit",
9212            "intrinsic",
9213            "?",
9214        ];
9215        for &input in rejected {
9216            assert_eq!(
9217                <RestartPolicy as TryFrom<&str>>::try_from(input),
9218                Err(()),
9219                "TryFrom<&str> impl on RestartPolicy must reject the \
9220                 non-wire byte-string {input:?} — silent acceptance \
9221                 signals an accept-set widening off the paired \
9222                 RestartPolicy::from_wire resolver"
9223            );
9224        }
9225    }
9226
9227    #[test]
9228    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
9229        // Cross-axis partition pin: the paired `TryFrom<&str>` and
9230        // `from_wire` reverse projections must resolve identically on
9231        // *every* input, not just the ones [`RestartPolicy::ALL`]
9232        // enumerates. Sweeps a mixed candidate set spanning accepted
9233        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
9234        // case dispatcher-catalog byte-strings, empty, whitespace-
9235        // padded, quoted, English-rebrand candidates) inputs and asserts
9236        // the trait's `Result::ok()` projection byte-equals the method-
9237        // named resolver's `Option<Self>` return-shape on each, locking
9238        // the two paths together by construction so any future detour
9239        // (a stray `try_from` special-case that widens or narrows the
9240        // accept-set outside the paired `from_wire` resolver, an
9241        // accidental swap onto the kebab-case [`std::str::FromStr`]
9242        // impl the [`gen_platform::FromStrKind`] derive installs on the
9243        // sibling dispatcher-catalog axis) trips at caixa-core test
9244        // time. Peer of the sibling
9245        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
9246        // pin — extends the round-trip discipline onto the M2-OTP-shape
9247        // per-child restart-policy axis.
9248        let candidates: &[&str] = &[
9249            "Permanent",
9250            "Temporary",
9251            "Transient",
9252            "",
9253            "permanent",
9254            "temporary",
9255            "transient",
9256            "PERMANENT",
9257            "unknown",
9258            "Permanent ",
9259            " Permanent",
9260            "\"Permanent\"",
9261            "Ephemeral",
9262            "OnAbnormalExit",
9263            "?",
9264        ];
9265        for &input in candidates {
9266            let via_trait: Option<RestartPolicy> =
9267                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
9268            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
9269            assert_eq!(
9270                via_trait, via_method,
9271                "TryFrom<&str> and from_wire must resolve identically on \
9272                 input {input:?} — divergence signals the two reverse-\
9273                 projection paths have drifted onto different accept-sets"
9274            );
9275        }
9276    }
9277
9278    #[test]
9279    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
9280        // Fail-before-pass-after byte-parity pin on the newly lifted
9281        // `impl From<RestartPolicy> for &'static str` — asserts the
9282        // standard-library trait impl and the substrate-primitive
9283        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
9284        // the same three-arm emit-set across every arm the exhaustive
9285        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
9286        // detour that routes the trait impl through a divergent
9287        // projection (a per-arm inline `match policy { Permanent =>
9288        // "Permanent", … }` re-inlining that opens a compile-time link
9289        // to the un-lifted arm-literal, an accidental swap onto the
9290        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
9291        // axis that would collide the two-axis wire/catalog split the
9292        // sibling [`RestartPolicy::from_wire`] doc block makes
9293        // load-bearing) trips at caixa-core test time under
9294        // `assert_eq!` rather than at a downstream
9295        // `impl Into<&'static str>`-bound consumer's silent split.
9296        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
9297        // carries so no arm's projection is covered only by the sibling
9298        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
9299        // paths. Materializes the `<&'static str as
9300        // From<RestartPolicy>>::from` output in a `const`-shape binding
9301        // to make the `'static` lifetime promise a build-time invariant
9302        // — a future accidental downgrade of any of the three arms'
9303        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
9304        // non-`&'static str` (a `String::leak()`-produced return, a
9305        // `Box::leak`-cast) trips at caixa-core build time rather than
9306        // at a downstream `'static`-bound consumer. Peer of the sibling
9307        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
9308        // (523157d) — extends the trait-idiomatic forward-projection
9309        // axis onto the second (and second-of-two-in-M2) closed-set
9310        // typed enum on the caixa surface (the paired per-child
9311        // restart-decision-policy sibling on the same M2 `:supervisor`
9312        // slot).
9313        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
9314        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
9315        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
9316        for &variant in RestartPolicy::ALL {
9317            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9318            let via_method: &'static str = variant.as_str();
9319            assert_eq!(
9320                via_trait, via_method,
9321                "From<RestartPolicy> for &'static str impl must round-trip \
9322                 RestartPolicy::{variant:?} to the same lifted \
9323                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
9324                 divergence signals a silent detour off the substrate-primitive \
9325                 accessor"
9326            );
9327            let via_into: &'static str = variant.into();
9328            assert_eq!(
9329                via_into, via_method,
9330                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
9331                 byte-equal RestartPolicy::as_str on the same input — the \
9332                 blanket-derived Into shape must resolve to the same as_str \
9333                 dispatch as the explicit From impl"
9334            );
9335        }
9336        assert_eq!(
9337            [PERMANENT, TEMPORARY, TRANSIENT],
9338            [
9339                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9340                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9341                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9342            ],
9343            "const-context RestartPolicy::as_str must resolve to the three \
9344             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
9345             downgrade of any arm to a non-const or non-static byte-string \
9346             breaks the `&'static str`-lifetime promise the paired \
9347             From<RestartPolicy> for &'static str impl carries by \
9348             construction"
9349        );
9350    }
9351
9352    #[test]
9353    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
9354        // Cross-axis partition pin: the paired trait-idiomatic
9355        // `From<RestartPolicy> for &'static str` forward projection and
9356        // the method-named [`RestartPolicy::as_str`] forward projection
9357        // must resolve identically on *every* arm, not just the ones
9358        // named in the primary byte-parity pin above. Sweeps every
9359        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
9360        // output byte-equals the method-named accessor's return-value on
9361        // each, locking the two forward-projection paths together by
9362        // construction so any future detour (a stray `From` special-case
9363        // that lands on a divergent per-arm literal outside the paired
9364        // `as_str` dispatch, a hypothetical rebrand touching one axis
9365        // without the other) trips at caixa-core test time. Peer of the
9366        // sibling forward-projection partition pin
9367        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
9368        // (523157d) — extends the round-trip discipline onto the
9369        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
9370        // surface, closing the two-way `Self ↔ &'static str` round-trip
9371        // on the trait-idiomatic pair (`From<Self> for &'static str` +
9372        // `TryFrom<&str> for Self`) as well as the pre-existing method-
9373        // named pair (`as_str` + `from_wire`).
9374        for &variant in RestartPolicy::ALL {
9375            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9376            let via_method: &'static str = variant.as_str();
9377            assert_eq!(
9378                via_trait, via_method,
9379                "From<RestartPolicy> for &'static str and \
9380                 RestartPolicy::as_str must resolve identically on \
9381                 RestartPolicy::{variant:?} — divergence signals the \
9382                 two forward-projection paths have drifted onto different \
9383                 emit-sets"
9384            );
9385        }
9386        // Round-trip witness: every arm's forward `From` output re-parses
9387        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
9388        // to the original variant. Closes the two-way `RestartPolicy ↔
9389        // &'static str` round-trip on the trait-idiomatic axis pair,
9390        // mirroring the pre-existing method-named `as_str` + `from_wire`
9391        // round-trip on the substrate-primitive axis pair.
9392        for &variant in RestartPolicy::ALL {
9393            let emitted: &'static str = variant.into();
9394            let re_parsed: Result<RestartPolicy, ()> =
9395                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
9396            assert_eq!(
9397                re_parsed,
9398                Ok(variant),
9399                "trait-idiomatic axis pair must round-trip \
9400                 RestartPolicy::{variant:?} through `.into::<&'static \
9401                 str>()` and back through `TryFrom<&str>` — a break signals \
9402                 the forward-emit and reverse-parse axes have drifted onto \
9403                 different vocabularies"
9404            );
9405        }
9406    }
9407
9408    #[test]
9409    fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
9410        // Fail-before-pass-after byte-parity pin on the newly lifted
9411        // `impl From<&RestartPolicy> for &'static str` — asserts the
9412        // borrowed-input standard-library trait impl and the substrate-
9413        // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
9414        // resolve to the same three-arm emit-set across every arm the
9415        // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
9416        // `From` trait does not auto-derive the borrowed-input sibling
9417        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
9418        // where T: Copy, U: From<T>` blanket in `core`), so the
9419        // borrowed-input axis is a distinct trait-idiomatic surface
9420        // that a `.iter().map(Into::into)` shape over
9421        // [`RestartPolicy::ALL`] (whose iterator yields
9422        // `&RestartPolicy`, not `RestartPolicy`) reaches through this
9423        // impl and no other — the paired owned-input
9424        // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
9425        // / dereference before the trait fires. Materializes the
9426        // `<&'static str as From<&RestartPolicy>>::from` output in a
9427        // `const`-shape binding to make the `'static` lifetime promise
9428        // a build-time invariant.
9429        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
9430        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
9431        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
9432        for variant in RestartPolicy::ALL {
9433            let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
9434            let via_method: &'static str = variant.as_str();
9435            assert_eq!(
9436                via_trait, via_method,
9437                "From<&RestartPolicy> for &'static str impl must round-trip \
9438                 &RestartPolicy::{variant:?} to the same lifted \
9439                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9440                 returns — divergence signals a silent detour off the \
9441                 substrate-primitive accessor"
9442            );
9443            let via_into: &'static str = variant.into();
9444            assert_eq!(
9445                via_into, via_method,
9446                "Into<&'static str>::into on &RestartPolicy::{variant:?} \
9447                 must byte-equal RestartPolicy::as_str on the same input — \
9448                 the blanket-derived Into shape must resolve to the same \
9449                 as_str dispatch as the explicit From impl"
9450            );
9451        }
9452        assert_eq!(
9453            [PERMANENT, TEMPORARY, TRANSIENT],
9454            [
9455                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9456                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9457                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9458            ],
9459            "const-context RestartPolicy::as_str must resolve to the three \
9460             lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
9461             From<&RestartPolicy> for &'static str impl inherits its \
9462             `'static` lifetime promise from the same accessor the \
9463             owned-input sibling routes through"
9464        );
9465    }
9466
9467    #[test]
9468    fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
9469        // Cross-axis partition pin: the paired trait-idiomatic
9470        // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
9471        // campaign-shape) and borrowed-input `From<&RestartPolicy> for
9472        // &'static str` (this lift) forward projections must resolve
9473        // identically on every arm, locking the two input-shape paths
9474        // together so any future detour trips at caixa-core test time.
9475        // Then a witness that a `.iter().map(Into::into)` pipe over
9476        // [`RestartPolicy::ALL`] (whose iterator yields
9477        // `&RestartPolicy`) materializes the three-arm accept-set
9478        // through the borrowed-input axis alone — the exact shape a
9479        // future wasm-operator per-child post-exit restart-decision
9480        // diagnostic line, a future substrate-wide per-arm diagnostic
9481        // column, or a
9482        // `HashMap::<&'static str, RestartPolicy>::from_iter(
9483        //     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
9484        // per-policy lookup reaches through — closing the two-way
9485        // owned/borrowed input-shape symmetry on the forward-projection
9486        // trait-idiomatic axis. Peer of the sibling
9487        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9488        // (64aa742) /
9489        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9490        // (5ab993a) /
9491        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9492        // (807b0b5) /
9493        // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9494        // (e941836) partition pins on the sibling closed-set typed-enum
9495        // discriminator axes — extends the borrowed-input axis
9496        // discipline onto the second-of-two M2 OTP-shape closed-set
9497        // typed enum on the caixa surface (per-child restart-decision
9498        // policy). Also closes the direct two-way `&Self → &'static
9499        // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
9500        // — unlike the peer [`crate::CaixaKind`] axis pair (whose
9501        // forward `From` emits lowercase Portuguese diagnostic bytes
9502        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
9503        // forcing the round-trip through an intermediate wire-vocab
9504        // hop), the [`RestartPolicy::as_str`] emit and
9505        // [`RestartPolicy::from_wire`] parse share the same
9506        // `PascalCase` vocabulary by construction, so the borrowed-
9507        // input forward axis and the reverse axis compose directly.
9508        for &variant in RestartPolicy::ALL {
9509            let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9510            let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
9511            assert_eq!(
9512                owned, borrowed,
9513                "From<RestartPolicy> and From<&RestartPolicy> for \
9514                 &'static str must resolve identically on \
9515                 RestartPolicy::{variant:?} — divergence signals the \
9516                 owned-input and borrowed-input forward-projection paths \
9517                 have drifted onto different emit-sets"
9518            );
9519        }
9520        let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
9521        let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
9522        assert_eq!(
9523            via_iter, via_method,
9524            "`.iter().map(Into::into)` over RestartPolicy::ALL must \
9525             byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
9526             borrowed-input `From<&RestartPolicy> for &'static str` axis \
9527             is what makes the `.iter().map(Into::into)` shape route \
9528             through the substrate-primitive `RestartPolicy::as_str` \
9529             accessor rather than through a per-call-site `.copied()` / \
9530             dereference detour"
9531        );
9532        for variant in RestartPolicy::ALL {
9533            let emitted: &'static str = variant.into();
9534            let re_parsed: Result<RestartPolicy, ()> =
9535                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
9536            assert_eq!(
9537                re_parsed,
9538                Ok(*variant),
9539                "trait-idiomatic borrowed-input forward-projection + \
9540                 reverse-projection axis pair must round-trip \
9541                 &RestartPolicy::{variant:?} through `.into::<&'static \
9542                 str>()` (via the borrowed-input axis) and back through \
9543                 `TryFrom<&str>` — a break signals the borrowed-input \
9544                 forward-emit and reverse-parse axes have drifted onto \
9545                 different vocabularies"
9546            );
9547        }
9548    }
9549
9550    #[test]
9551    fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
9552        // Fail-before-pass-after byte-parity pin on the newly lifted
9553        // `impl From<RestartPolicy> for String` — asserts the
9554        // owned-`String`-returning standard-library trait impl and the
9555        // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
9556        // accessor resolve to the same three-arm emit-set across every
9557        // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
9558        // Rust's standard library does not carry a blanket
9559        // `impl<T: AsRef<str>> From<T> for String` (nor an
9560        // `impl<T: fmt::Display> From<T> for String`), so the
9561        // owned-`String` forward-projection axis is a distinct
9562        // trait-idiomatic surface that a `let key: String =
9563        // policy.into();`-shaped call site reaches through this impl
9564        // and no other — the paired sibling `From<RestartPolicy> for
9565        // &'static str` impl forces every owned-`String` call site
9566        // through an explicit `.to_owned()` / `String::from`
9567        // restatement. Peer of the first-mover
9568        // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
9569        // (7baa18a) — extends the trait-idiomatic owned-`String`
9570        // forward-projection axis onto the second-of-two M2 OTP-shape
9571        // closed-set typed enums on the caixa surface (per-child
9572        // restart-decision-policy sibling on the same M2 `:supervisor`
9573        // slot).
9574        for &variant in RestartPolicy::ALL {
9575            let via_trait: String = <String as From<RestartPolicy>>::from(variant);
9576            let via_method: &'static str = variant.as_str();
9577            assert_eq!(
9578                via_trait.as_str(),
9579                via_method,
9580                "From<RestartPolicy> for String impl must round-trip \
9581                 RestartPolicy::{variant:?} to the same lifted \
9582                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9583                 returns — divergence signals a silent detour off the \
9584                 substrate-primitive accessor"
9585            );
9586            let via_into: String = variant.into();
9587            assert_eq!(
9588                via_into.as_str(),
9589                via_method,
9590                "Into<String>::into on RestartPolicy::{variant:?} must \
9591                 byte-equal RestartPolicy::as_str on the same input — the \
9592                 blanket-derived Into shape must resolve to the same as_str \
9593                 dispatch as the explicit From impl"
9594            );
9595        }
9596    }
9597
9598    #[test]
9599    fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
9600        // Cross-axis partition pin: the paired trait-idiomatic
9601        // owned-`String` `From<RestartPolicy> for String` (this lift)
9602        // and owned-`&'static str` `From<RestartPolicy> for &'static
9603        // str` (9fb37d0) forward projections must resolve identically
9604        // on every arm, locking the two return-type-shape paths
9605        // together so any future detour trips at caixa-core test time.
9606        // Also byte-parity witness against the sibling
9607        // [`ToString::to_string`] surface routed through
9608        // [`std::fmt::Display`] — the three owned-heap-string paths
9609        // (`.into::<String>()`, `String::from`, `.to_string()`) must
9610        // resolve identically on every arm so a future consumer that
9611        // picks any of the three lands on the same lifted
9612        // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
9613        // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
9614        // that materializes the three-arm accept-set through the
9615        // owned-`String` axis alone — the exact shape a future
9616        // wasm-operator per-child post-exit restart-decision
9617        // diagnostic line composer or a
9618        // `HashMap::<String, RestartPolicy>::from_iter(
9619        //     RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
9620        // owned-key per-policy lookup reaches through — closing the
9621        // owned-`String` forward-projection axis's iterator-pipe
9622        // shape. Then a direct round-trip witness through the paired
9623        // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
9624        // owned-`String`'s [`String::as_str`] borrow that closes the
9625        // two-way `Self → String → Self` round-trip on the trait-
9626        // idiomatic owned-`String` forward + reverse axis pair —
9627        // unlike the peer [`crate::CaixaKind`] axis pair (whose
9628        // forward `From` emits lowercase Portuguese diagnostic bytes
9629        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
9630        // forcing the round-trip through an intermediate wire-vocab
9631        // hop), the [`RestartPolicy::as_str`] emit and
9632        // [`RestartPolicy::from_wire`] parse share the same
9633        // `PascalCase` vocabulary by construction, so the owned-
9634        // `String` forward axis and the reverse axis compose directly.
9635        for &variant in RestartPolicy::ALL {
9636            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
9637            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9638            assert_eq!(
9639                owned_string.as_str(),
9640                owned_static,
9641                "From<RestartPolicy> for String and From<RestartPolicy> \
9642                 for &'static str must resolve identically on \
9643                 RestartPolicy::{variant:?} — divergence signals the \
9644                 owned-`String` and owned-`&'static str` forward-projection \
9645                 return-type-shape paths have drifted onto different \
9646                 emit-sets"
9647            );
9648            let via_to_string: String = variant.to_string();
9649            assert_eq!(
9650                owned_string, via_to_string,
9651                "From<RestartPolicy> for String must byte-equal \
9652                 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
9653                 divergence signals the trait-idiomatic owned-`String` \
9654                 forward-projection axis and the ToString-through-Display \
9655                 axis have drifted onto different emit-sets"
9656            );
9657        }
9658        let via_iter: Vec<String> = RestartPolicy::ALL
9659            .iter()
9660            .copied()
9661            .map(String::from)
9662            .collect();
9663        let via_method: Vec<String> = RestartPolicy::ALL
9664            .iter()
9665            .map(|p| p.as_str().to_owned())
9666            .collect();
9667        assert_eq!(
9668            via_iter, via_method,
9669            "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
9670             must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
9671             every arm — the owned-`String` `From<RestartPolicy> for \
9672             String` axis is what makes the `String::from` composition \
9673             route through the substrate-primitive `RestartPolicy::as_str` \
9674             accessor rather than through a per-call-site `.to_owned()` / \
9675             `String::from(policy.as_str())` detour"
9676        );
9677        for &variant in RestartPolicy::ALL {
9678            let emitted: String = variant.into();
9679            let re_parsed: Result<RestartPolicy, ()> =
9680                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
9681            assert_eq!(
9682                re_parsed,
9683                Ok(variant),
9684                "trait-idiomatic owned-`String` forward-projection + \
9685                 reverse-projection axis pair must round-trip \
9686                 RestartPolicy::{variant:?} through `.into::<String>()` \
9687                 and back through `TryFrom<&str>` on the owned-`String`'s \
9688                 String::as_str borrow — a break signals the owned-`String` \
9689                 forward-emit and reverse-parse axes have drifted onto \
9690                 different vocabularies"
9691            );
9692        }
9693    }
9694
9695    #[test]
9696    fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
9697        // Fail-before-pass-after byte-parity pin on the newly lifted
9698        // `impl From<&RestartPolicy> for String` — asserts the
9699        // borrowed-input owned-`String`-returning standard-library
9700        // trait impl and the substrate-primitive
9701        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
9702        // the same three-arm emit-set across every arm the exhaustive
9703        // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
9704        // library does not carry a blanket `impl<T: AsRef<str>>
9705        // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
9706        // for String`), so the borrowed-input owned-`String` forward-
9707        // projection axis is a distinct trait-idiomatic surface that a
9708        // `let key: String = (&policy).into();`-shaped call site
9709        // reaches through this impl and no other — the paired sibling
9710        // `From<RestartPolicy> for String` impl forces every borrowed-
9711        // input call site through an explicit `Copy` deref
9712        // (`String::from(*policy)`) or an `.as_str().to_owned()` /
9713        // `.to_string()` detour. Peer of the first-mover
9714        // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
9715        // (579385f) — extends the trait-idiomatic borrowed-input
9716        // owned-`String` forward-projection axis onto the second-of-
9717        // two M2 OTP-shape closed-set typed enums on the caixa surface
9718        // (per-child restart-decision-policy sibling on the same M2
9719        // `:supervisor` slot).
9720        for &variant in RestartPolicy::ALL {
9721            let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
9722            let via_method: &'static str = variant.as_str();
9723            assert_eq!(
9724                via_trait.as_str(),
9725                via_method,
9726                "From<&RestartPolicy> for String impl must round-trip \
9727                 &RestartPolicy::{variant:?} to the same lifted \
9728                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9729                 returns — divergence signals a silent detour off the \
9730                 substrate-primitive accessor"
9731            );
9732            let via_into: String = (&variant).into();
9733            assert_eq!(
9734                via_into.as_str(),
9735                via_method,
9736                "Into<String>::into on &RestartPolicy::{variant:?} must \
9737                 byte-equal RestartPolicy::as_str on the same input — \
9738                 the blanket-derived Into shape must resolve to the \
9739                 same as_str dispatch as the explicit From impl"
9740            );
9741        }
9742    }
9743
9744    #[test]
9745    fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
9746        // Cross-axis partition pin: the newly lifted trait-idiomatic
9747        // borrowed-input owned-`String` `From<&RestartPolicy> for
9748        // String` (this lift), the paired owned-input owned-`String`
9749        // `From<RestartPolicy> for String` (7851725), the paired
9750        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
9751        // for &'static str` (842c7f3), and the paired owned-input
9752        // owned-`&'static str` `From<RestartPolicy> for &'static str`
9753        // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
9754        // str, String}` 2×2 trait-idiomatic projection family — must
9755        // resolve identically on every arm, locking the four
9756        // return-shape × input-shape paths together so any future
9757        // detour trips at caixa-core test time. Also byte-parity
9758        // witness against the sibling [`ToString::to_string`] surface
9759        // routed through [`std::fmt::Display`] and a direct round-trip
9760        // witness through the paired trait-idiomatic reverse
9761        // [`TryFrom<&str>`] axis on the owned-`String`'s
9762        // [`String::as_str`] borrow that closes the two-way
9763        // `&Self → String → Self` round-trip on the trait-idiomatic
9764        // borrowed-input owned-`String` forward + reverse axis pair.
9765        // Peer of the first-mover
9766        // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
9767        // (579385f) — closes the whole `{Self, &Self} × {&'static str,
9768        // String}` 2×2 projection corner on both M2 OTP-shape sibling
9769        // peers.
9770        for &variant in RestartPolicy::ALL {
9771            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
9772            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
9773            let borrowed_static: &'static str =
9774                <&'static str as From<&RestartPolicy>>::from(&variant);
9775            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9776            assert_eq!(
9777                borrowed_string, owned_string,
9778                "From<&RestartPolicy> for String and From<RestartPolicy> \
9779                 for String must resolve identically on \
9780                 RestartPolicy::{variant:?} — divergence signals the \
9781                 borrowed-input and owned-input owned-`String` \
9782                 forward-projection input-shape paths have drifted onto \
9783                 different emit-sets"
9784            );
9785            assert_eq!(
9786                borrowed_string.as_str(),
9787                borrowed_static,
9788                "From<&RestartPolicy> for String and From<&RestartPolicy> \
9789                 for &'static str must resolve identically on \
9790                 RestartPolicy::{variant:?} — divergence signals the \
9791                 borrowed-input `&'static str` and owned-`String` \
9792                 return-shape paths have drifted onto different \
9793                 emit-sets"
9794            );
9795            assert_eq!(
9796                borrowed_string.as_str(),
9797                owned_static,
9798                "From<&RestartPolicy> for String and From<RestartPolicy> \
9799                 for &'static str must resolve identically on \
9800                 RestartPolicy::{variant:?} — divergence signals a \
9801                 break in the diagonal corner of the {{Self, &Self}} × \
9802                 {{&'static str, String}} 2×2 trait-idiomatic \
9803                 projection family"
9804            );
9805            let via_to_string: String = variant.to_string();
9806            assert_eq!(
9807                borrowed_string, via_to_string,
9808                "From<&RestartPolicy> for String must byte-equal \
9809                 RestartPolicy::to_string on RestartPolicy::{variant:?} \
9810                 — divergence signals the trait-idiomatic borrowed-input \
9811                 owned-`String` forward-projection axis and the \
9812                 ToString-through-Display axis have drifted onto \
9813                 different emit-sets"
9814            );
9815        }
9816        let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
9817        let via_method: Vec<String> = RestartPolicy::ALL
9818            .iter()
9819            .map(|p| p.as_str().to_owned())
9820            .collect();
9821        assert_eq!(
9822            via_iter, via_method,
9823            "`.iter().map(String::from)` over RestartPolicy::ALL — a \
9824             call site whose iteration axis holds `&RestartPolicy` by \
9825             construction — must byte-equal `.iter().map(|p| \
9826             p.as_str().to_owned())` on every arm — the borrowed-input \
9827             owned-`String` `From<&RestartPolicy> for String` axis is \
9828             what makes the `String::from` composition route through \
9829             the substrate-primitive `RestartPolicy::as_str` accessor \
9830             without a spurious `Copy` deref (which would only be \
9831             reachable through the owned-input `From<RestartPolicy> \
9832             for String` axis by first calling `.copied()` on the \
9833             iterator)"
9834        );
9835        for &variant in RestartPolicy::ALL {
9836            let emitted: String = (&variant).into();
9837            let re_parsed: Result<RestartPolicy, ()> =
9838                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
9839            assert_eq!(
9840                re_parsed,
9841                Ok(variant),
9842                "trait-idiomatic borrowed-input owned-`String` \
9843                 forward-projection + reverse-projection axis pair must \
9844                 round-trip &RestartPolicy::{variant:?} through \
9845                 `.into::<String>()` on the borrowed-input surface and \
9846                 back through `TryFrom<&str>` on the owned-`String`'s \
9847                 String::as_str borrow — a break signals the \
9848                 borrowed-input owned-`String` forward-emit and \
9849                 reverse-parse axes have drifted onto different \
9850                 vocabularies"
9851            );
9852        }
9853    }
9854
9855    #[test]
9856    fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
9857        // Fail-before-pass-after byte-parity pin on the newly lifted
9858        // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
9859        // asserts the standard-library trait impl and the substrate-
9860        // primitive [`super::RestartPolicy::as_str`] `pub const fn`
9861        // accessor resolve to the same three-arm emit-set across every
9862        // arm the exhaustive [`super::RestartPolicy::ALL`] slice
9863        // enumerates. Rust's standard library does not carry a blanket
9864        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
9865        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
9866        // the `Cow<'static, str>` forward-projection axis is a
9867        // distinct trait-idiomatic surface that a
9868        // `let key: Cow<'static, str> = policy.into();`-shaped call
9869        // site reaches through this impl and no other — the paired
9870        // sibling `From<RestartPolicy> for &'static str` and
9871        // `From<RestartPolicy> for String` impls force every
9872        // `Cow<'static, str>`-parameterized call site through a
9873        // `Cow::Borrowed(policy.as_str())` /
9874        // `Cow::Owned(policy.to_string())` composition whose type
9875        // bounds have no compile-time link back to the substrate
9876        // primitive.
9877        //
9878        // Also asserts the projection lands on the zero-alloc
9879        // [`std::borrow::Cow::Borrowed`] arm (not the
9880        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9881        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
9882        // return lifetime by construction makes the borrowed arm the
9883        // type-correct projection with no runtime allocation. Any
9884        // future silent detour that routes the impl through the owned
9885        // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
9886        // that would allocate on every call site where the
9887        // `&'static str` return of [`super::RestartPolicy::as_str`]
9888        // makes the zero-alloc borrowed projection type-correct) trips
9889        // at caixa-core test time under the
9890        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
9891        // than at a downstream `Cow<'static, str>`-bound consumer's
9892        // silent allocation.
9893        //
9894        // Second peer on the substrate-wide trait-idiomatic
9895        // [`std::borrow::Cow<'static, str>`] forward-projection family
9896        // to extend the axis off the top-level [`super::CaixaKind`]
9897        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
9898        // second (and second-of-two-in-M2) M2 OTP-shape closed-set
9899        // fieldless typed enum peer on the caixa surface — closes the
9900        // M2 OTP-shape tier of the campaign on the owned-input axis
9901        // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
9902        // now carry the owned-input Cow<'static, str> forward
9903        // projection).
9904        for &variant in RestartPolicy::ALL {
9905            let via_trait: std::borrow::Cow<'static, str> =
9906                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
9907            let via_method: &'static str = variant.as_str();
9908            assert_eq!(
9909                via_trait.as_ref(),
9910                via_method,
9911                "From<RestartPolicy> for Cow<'static, str> impl must \
9912                 round-trip RestartPolicy::{variant:?} to the same \
9913                 lifted SUPERVISOR_CHILD_RESTART_* const \
9914                 RestartPolicy::as_str returns — divergence signals a \
9915                 silent detour off the substrate-primitive accessor"
9916            );
9917            assert!(
9918                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9919                "From<RestartPolicy> for Cow<'static, str> impl must \
9920                 land on the zero-alloc Cow::Borrowed arm on \
9921                 RestartPolicy::{variant:?} — a Cow::Owned outcome \
9922                 signals the projection has silently allocated where \
9923                 the substrate-primitive RestartPolicy::as_str \
9924                 `&'static str` return makes the borrowed arm the \
9925                 type-correct projection"
9926            );
9927            let via_into: std::borrow::Cow<'static, str> = variant.into();
9928            assert_eq!(
9929                via_into.as_ref(),
9930                via_method,
9931                "Into<Cow<'static, str>>::into on \
9932                 RestartPolicy::{variant:?} must byte-equal \
9933                 RestartPolicy::as_str on the same input — the \
9934                 blanket-derived Into shape must resolve to the same \
9935                 as_str dispatch as the explicit From impl"
9936            );
9937            assert!(
9938                matches!(via_into, std::borrow::Cow::Borrowed(_)),
9939                "Into<Cow<'static, str>>::into on \
9940                 RestartPolicy::{variant:?} must land on the \
9941                 zero-alloc Cow::Borrowed arm — the blanket-derived \
9942                 Into shape must resolve to the same Cow::Borrowed \
9943                 dispatch as the explicit From impl"
9944            );
9945        }
9946    }
9947
9948    #[test]
9949    fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9950        // Cross-axis partition pin: the newly lifted trait-idiomatic
9951        // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
9952        // (this lift), the paired owned-input `From<RestartPolicy>
9953        // for &'static str` (9fb37d0), and the paired owned-input
9954        // `From<RestartPolicy> for String` (7851725) forward
9955        // projections must resolve identically on every arm, locking
9956        // the three return-shape paths together by construction so any
9957        // future detour trips at caixa-core test time. Also byte-parity
9958        // witness against the sibling [`ToString::to_string`] surface
9959        // routed through [`std::fmt::Display`] — every owned-heap-
9960        // string path (the `Cow::Owned` promotion of this axis's
9961        // `.into_owned()`, `From<RestartPolicy> for String`, and
9962        // `.to_string()`) resolves to the same lifted
9963        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
9964        //
9965        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
9966        // witness over [`super::RestartPolicy::ALL`] that
9967        // materializes the three-arm accept-set through the
9968        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
9969        // shape a future `axum::response::IntoResponse` per-policy
9970        // rejection-body composer, a future M4 admission-webhook
9971        // per-policy rejection-reason emitter whose typing rules out
9972        // the sibling [`AsRef<str>`] borrowed return, or a future
9973        // substrate-wide per-policy diagnostic surface that binds
9974        // through a [`Cow<'static, str>`] boundary reaches through.
9975        // The pipe witness also pins the zero-alloc discipline: every
9976        // element in the collected vector satisfies the
9977        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
9978        // accidental silent-allocation regression on the pipe's
9979        // iteration axis is a caixa-core-test-time failure. Peer of
9980        // the first-mover
9981        // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
9982        // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
9983        // — closes the whole owned-input `Cow<'static, str>` +
9984        // paired `{&'static str, String}` cross-axis-parity corner on
9985        // both M2 OTP-shape sibling peers.
9986        for &variant in RestartPolicy::ALL {
9987            let via_cow: std::borrow::Cow<'static, str> =
9988                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
9989            let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9990            let via_string: String = <String as From<RestartPolicy>>::from(variant);
9991            assert_eq!(
9992                via_cow.as_ref(),
9993                via_static,
9994                "From<RestartPolicy> for Cow<'static, str> and \
9995                 From<RestartPolicy> for &'static str must resolve \
9996                 identically on RestartPolicy::{variant:?} — \
9997                 divergence signals the Cow<'static, str> and \
9998                 &'static str return-shape paths have drifted onto \
9999                 different emit-sets"
10000            );
10001            assert_eq!(
10002                via_cow.as_ref(),
10003                via_string.as_str(),
10004                "From<RestartPolicy> for Cow<'static, str> and \
10005                 From<RestartPolicy> for String must resolve \
10006                 identically on RestartPolicy::{variant:?} — \
10007                 divergence signals the Cow<'static, str> and String \
10008                 return-shape paths have drifted onto different \
10009                 emit-sets"
10010            );
10011            let via_to_string: String = variant.to_string();
10012            assert_eq!(
10013                via_cow.as_ref(),
10014                via_to_string.as_str(),
10015                "From<RestartPolicy> for Cow<'static, str> must \
10016                 byte-equal RestartPolicy::to_string on \
10017                 RestartPolicy::{variant:?} — divergence signals the \
10018                 trait-idiomatic Cow<'static, str> forward-projection \
10019                 axis and the ToString-through-Display axis have \
10020                 drifted onto different emit-sets"
10021            );
10022        }
10023        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10024            .iter()
10025            .copied()
10026            .map(std::borrow::Cow::from)
10027            .collect();
10028        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10029            .iter()
10030            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
10031            .collect();
10032        assert_eq!(
10033            via_iter, via_method,
10034            "`.iter().copied().map(Cow::from)` over \
10035             RestartPolicy::ALL must byte-equal `.iter().map(|p| \
10036             Cow::Borrowed(p.as_str()))` on every arm — the \
10037             trait-idiomatic `From<RestartPolicy> for Cow<'static, \
10038             str>` axis is what makes the `Cow::from` composition \
10039             route through the substrate-primitive \
10040             `RestartPolicy::as_str` accessor with the zero-alloc \
10041             Cow::Borrowed arm by construction, rather than a \
10042             per-call-site `Cow::Owned(policy.to_string())` \
10043             allocation"
10044        );
10045        for cow in &via_iter {
10046            assert!(
10047                matches!(cow, std::borrow::Cow::Borrowed(_)),
10048                "every element of the \
10049                 .iter().copied().map(Cow::from) pipe over \
10050                 RestartPolicy::ALL must land on the zero-alloc \
10051                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
10052                 signals the pipe's iteration axis has silently \
10053                 allocated where the substrate-primitive \
10054                 RestartPolicy::as_str `&'static str` return makes \
10055                 the borrowed arm the type-correct projection"
10056            );
10057        }
10058    }
10059
10060    #[test]
10061    fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
10062        // Fail-before-pass-after byte-parity pin on the newly lifted
10063        // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
10064        // asserts the borrowed-input standard-library trait impl and
10065        // the substrate-primitive [`super::RestartPolicy::as_str`]
10066        // `pub const fn` accessor resolve to the same three-arm emit-
10067        // set across every arm the exhaustive
10068        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
10069        // standard library does not carry a blanket
10070        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
10071        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
10072        // the borrowed-input `Cow<'static, str>` forward-projection
10073        // axis is a distinct trait-idiomatic surface that a
10074        // `let key: Cow<'static, str> = (&policy).into();`-shaped
10075        // call site or a
10076        // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
10077        // reaches through this impl and no other — the paired owned-
10078        // input `From<RestartPolicy> for Cow<'static, str>` impl
10079        // (0612398) forces every borrowed-input call site through an
10080        // explicit `Copy` deref (`Cow::from(*policy)`) or a
10081        // `Cow::Borrowed(policy.as_str())` open-code whose type
10082        // bounds have no compile-time link back to the substrate
10083        // primitive.
10084        //
10085        // Also asserts the projection lands on the zero-alloc
10086        // [`std::borrow::Cow::Borrowed`] arm (not the
10087        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10088        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
10089        // return lifetime by construction makes the borrowed arm the
10090        // type-correct projection with no runtime allocation on the
10091        // borrowed-input surface just as on the paired owned-input
10092        // surface.
10093        //
10094        // Closes the `{Self, &Self}` input-shape corner on the M2
10095        // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
10096        // the second-of-two-in-M2 closed-set fieldless typed enum peer
10097        // on the caixa surface (`:supervisor :children :restart`),
10098        // exactly as d45c409 closed it on the top-level
10099        // [`super::CaixaKind`] one commit after the owning half
10100        // (99c1735) landed and as 9b3e4b3 closed it on the sibling
10101        // M2 OTP-shape [`super::RestartStrategy`] one commit after
10102        // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
10103        // tier of the substrate-wide Cow<'static, str> forward-
10104        // projection campaign on both input-shape corners
10105        // ({Self, &Self}) of both M2 OTP-shape sibling peers.
10106        for &variant in RestartPolicy::ALL {
10107            let via_trait: std::borrow::Cow<'static, str> =
10108                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
10109            let via_method: &'static str = variant.as_str();
10110            assert_eq!(
10111                via_trait.as_ref(),
10112                via_method,
10113                "From<&RestartPolicy> for Cow<'static, str> impl must \
10114                 round-trip &RestartPolicy::{variant:?} to the same \
10115                 lifted SUPERVISOR_CHILD_RESTART_* const \
10116                 RestartPolicy::as_str returns — divergence signals a \
10117                 silent detour off the substrate-primitive accessor"
10118            );
10119            assert!(
10120                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10121                "From<&RestartPolicy> for Cow<'static, str> impl must \
10122                 land on the zero-alloc Cow::Borrowed arm on \
10123                 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
10124                 signals the projection has silently allocated where \
10125                 the substrate-primitive RestartPolicy::as_str \
10126                 `&'static str` return makes the borrowed arm the \
10127                 type-correct projection"
10128            );
10129            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
10130            assert_eq!(
10131                via_into.as_ref(),
10132                via_method,
10133                "Into<Cow<'static, str>>::into on \
10134                 &RestartPolicy::{variant:?} must byte-equal \
10135                 RestartPolicy::as_str on the same input — the \
10136                 blanket-derived Into shape must resolve to the same \
10137                 as_str dispatch as the explicit From impl"
10138            );
10139            assert!(
10140                matches!(via_into, std::borrow::Cow::Borrowed(_)),
10141                "Into<Cow<'static, str>>::into on \
10142                 &RestartPolicy::{variant:?} must land on the \
10143                 zero-alloc Cow::Borrowed arm — the blanket-derived \
10144                 Into shape must resolve to the same Cow::Borrowed \
10145                 dispatch as the explicit From impl"
10146            );
10147        }
10148    }
10149
10150    #[test]
10151    fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10152        // Cross-axis partition pin: the newly lifted trait-idiomatic
10153        // borrowed-input `From<&RestartPolicy> for
10154        // std::borrow::Cow<'static, str>` (this lift), the paired
10155        // owned-input `From<RestartPolicy> for
10156        // std::borrow::Cow<'static, str>` (0612398), the paired
10157        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
10158        // for &'static str`, and the paired borrowed-input owned-
10159        // `String` `From<&RestartPolicy> for String` must resolve
10160        // identically on every arm, locking the four
10161        // return-shape × input-shape paths together by construction so
10162        // any future detour trips at caixa-core test time. Also byte-
10163        // parity witness against the sibling [`ToString::to_string`]
10164        // surface routed through [`std::fmt::Display`] — every owned-
10165        // heap-string path (this axis's `.into_owned()` promotion, the
10166        // paired [`From<&RestartPolicy> for String`], and
10167        // `.to_string()`) resolves to the same lifted
10168        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
10169        //
10170        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
10171        // over [`super::RestartPolicy::ALL`] — whose iterator yields
10172        // `&RestartPolicy` by construction, so the borrowed-input
10173        // [`Cow<'static, str>`] axis is what routes the pipe through
10174        // the substrate-primitive [`super::RestartPolicy::as_str`]
10175        // accessor without a spurious [`Copy`] deref (which would only
10176        // be reachable through the owned-input
10177        // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
10178        // calling `.copied()` on the iterator). The pipe witness also
10179        // pins the zero-alloc discipline: every element in the
10180        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
10181        // arm predicate, so a future accidental silent-allocation
10182        // regression on the pipe's iteration axis is a caixa-core-
10183        // test-time failure. Peer of the sibling
10184        // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
10185        // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
10186        // the whole borrowed-input `Cow<'static, str>` +
10187        // paired `{&'static str, String}` cross-axis-parity corner on
10188        // both M2 OTP-shape sibling peers.
10189        for &policy in RestartPolicy::ALL {
10190            let borrowed_cow: std::borrow::Cow<'static, str> =
10191                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
10192            let owned_cow: std::borrow::Cow<'static, str> =
10193                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
10194            let borrowed_static: &'static str =
10195                <&'static str as From<&RestartPolicy>>::from(&policy);
10196            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
10197            assert_eq!(
10198                borrowed_cow, owned_cow,
10199                "From<&RestartPolicy> for Cow<'static, str> and \
10200                 From<RestartPolicy> for Cow<'static, str> must \
10201                 resolve identically on RestartPolicy::{policy:?} — \
10202                 divergence signals the borrowed-input and owned-input \
10203                 Cow<'static, str> forward-projection input-shape \
10204                 paths have drifted onto different emit-sets"
10205            );
10206            assert_eq!(
10207                borrowed_cow.as_ref(),
10208                borrowed_static,
10209                "From<&RestartPolicy> for Cow<'static, str> and \
10210                 From<&RestartPolicy> for &'static str must resolve \
10211                 identically on RestartPolicy::{policy:?} — \
10212                 divergence signals the borrowed-input Cow<'static, \
10213                 str> and &'static str return-shape paths have drifted \
10214                 onto different emit-sets"
10215            );
10216            assert_eq!(
10217                borrowed_cow.as_ref(),
10218                borrowed_string.as_str(),
10219                "From<&RestartPolicy> for Cow<'static, str> and \
10220                 From<&RestartPolicy> for String must resolve \
10221                 identically on RestartPolicy::{policy:?} — \
10222                 divergence signals the borrowed-input Cow<'static, \
10223                 str> and owned-`String` return-shape paths have \
10224                 drifted onto different emit-sets"
10225            );
10226            let via_to_string: String = policy.to_string();
10227            assert_eq!(
10228                borrowed_cow.as_ref(),
10229                via_to_string.as_str(),
10230                "From<&RestartPolicy> for Cow<'static, str> must \
10231                 byte-equal RestartPolicy::to_string on \
10232                 RestartPolicy::{policy:?} — divergence signals \
10233                 the trait-idiomatic borrowed-input Cow<'static, str> \
10234                 forward-projection axis and the ToString-through-\
10235                 Display axis have drifted onto different emit-sets"
10236            );
10237        }
10238        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10239            .iter()
10240            .map(std::borrow::Cow::from)
10241            .collect();
10242        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10243            .iter()
10244            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
10245            .collect();
10246        assert_eq!(
10247            via_iter, via_method,
10248            "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
10249             call site whose iteration axis holds `&RestartPolicy` \
10250             by construction — must byte-equal `.iter().map(|p| \
10251             Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
10252             input Cow<'static, str> `From<&RestartPolicy> for \
10253             Cow<'static, str>` axis is what makes the `Cow::from` \
10254             composition route through the substrate-primitive \
10255             `RestartPolicy::as_str` accessor with the zero-alloc \
10256             Cow::Borrowed arm by construction and without a spurious \
10257             `Copy` deref (which would only be reachable through the \
10258             owned-input `From<RestartPolicy> for Cow<'static, str>` \
10259             axis by first calling `.copied()` on the iterator)"
10260        );
10261        for cow in &via_iter {
10262            assert!(
10263                matches!(cow, std::borrow::Cow::Borrowed(_)),
10264                "every element of the .iter().map(Cow::from) pipe \
10265                 over RestartPolicy::ALL must land on the zero-\
10266                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
10267                 any arm signals the pipe's iteration axis has \
10268                 silently allocated where the substrate-primitive \
10269                 RestartPolicy::as_str `&'static str` return makes \
10270                 the borrowed arm the type-correct projection"
10271            );
10272        }
10273    }
10274
10275    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
10276
10277    #[test]
10278    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
10279        // The fail-before-pass-after pin: pre-lift there was no
10280        // single-source binding between the [`RestartPolicy`] variant
10281        // name the un-`rename`d `Serialize` derive emits under
10282        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
10283        // byte-string every downstream cluster-side dispatcher (the
10284        // future wasm-operator's per-child post-exit restart-decision
10285        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
10286        // materializer's admission-time enum-arm bind, the
10287        // `caixa-operator`'s hierarchical reconciliation scheduler's
10288        // per-child-policy fan-out) probes verbatim. A future
10289        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
10290        // or a per-variant `#[serde(rename = "…")]` override, or a
10291        // variant rename in the source — would silently rebrand the
10292        // emitted scalar under one spelling while every downstream
10293        // dispatcher still probed the other, with the failure surfacing
10294        // at the operator's reconcile posture (children coming up under
10295        // the `default()` `Permanent` arm rather than the typed slot's
10296        // declared policy — a `:temporary` `oneShot` child would be
10297        // restarted on clean exit, treating the successful-completion
10298        // signal as failure and re-running the completion-terminal
10299        // one-shot indefinitely; a `:transient` child that clean-exited
10300        // would be restarted, masking the clean-completion contract)
10301        // far from the source rebrand commit and with no field naming
10302        // the drift. Pinning the two paths (the `Serialize` derive's
10303        // serialized string AND the [`RestartPolicy::as_str`] helper)
10304        // to the same three lifted
10305        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
10306        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
10307        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
10308        // byte-strings makes any future drift on either endpoint fail
10309        // here at caixa-core build time. Peer of the sibling
10310        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
10311        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
10312        // and the M3
10313        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
10314        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
10315        // same three-path-convergence discipline, extended to close the
10316        // third OTP-shaped closed-enum discriminator axis on the caixa
10317        // typed surface (per-child restart-decision policy).
10318        for (variant, expected) in [
10319            (
10320                RestartPolicy::Permanent,
10321                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10322            ),
10323            (
10324                RestartPolicy::Temporary,
10325                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10326            ),
10327            (
10328                RestartPolicy::Transient,
10329                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10330            ),
10331        ] {
10332            let json = serde_json::to_string(&variant).unwrap();
10333            assert_eq!(
10334                json,
10335                format!("\"{expected}\""),
10336                "RestartPolicy::{variant:?} must serialize to {expected:?}"
10337            );
10338            assert_eq!(
10339                variant.as_str(),
10340                expected,
10341                "RestartPolicy::{variant:?}.as_str() must return the lifted \
10342                 SUPERVISOR_CHILD_RESTART_* constant"
10343            );
10344        }
10345    }
10346
10347    #[test]
10348    fn supervisor_child_restart_consts_are_pairwise_distinct() {
10349        // Cross-arm drift-detection pin: a future collapse of two
10350        // canonical variant byte-strings onto the same value (e.g. an
10351        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
10352        // to also read `"Permanent"`) would silently reroute every
10353        // downstream operator's per-child-policy dispatch onto the
10354        // sibling arm's reconcile branch and pass every propagation-probe
10355        // test that expected only the stale arm's value — a `:transient`
10356        // child would come up under the `:permanent` restart-decision
10357        // posture on every subsequent clean exit, so a completion-terminal
10358        // child would be restarted indefinitely against its declared
10359        // policy. Peer of the sibling
10360        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
10361        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
10362        // and the four-way distinct pin
10363        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
10364        // top-level `SUPERVISOR_KEY_*` axis.
10365        let all = [
10366            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10367            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10368            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10369        ];
10370        for (i, a) in all.iter().enumerate() {
10371            for (j, b) in all.iter().enumerate() {
10372                if i != j {
10373                    assert_ne!(
10374                        a, b,
10375                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
10376                         — got duplicate {a:?} at indices {i} and {j}",
10377                    );
10378                }
10379            }
10380        }
10381    }
10382
10383    #[test]
10384    fn restart_policy_display_routes_through_as_str_helper() {
10385        // The fail-before-pass-after pin on the first half of the
10386        // three-path convergence: pre-convergence [`RestartPolicy`]
10387        // carried a [`std::fmt::Display`] surface via its
10388        // `#[discriminant(also_display)]` gen-platform derive route,
10389        // which arrived kebab-case as `"permanent"` / `"temporary"`
10390        // / `"transient"` on this three-arm enum (whose variant
10391        // names each collapse to their own lowercase form under the
10392        // kebab-case transform) while the wire format ran as
10393        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
10394        // through the un-`rename`d serde derive. Every consumer
10395        // reaching for a policy byte-string past the wire format had
10396        // to pick between three paths ([`RestartPolicy::as_str`],
10397        // the `Serialize` derive's serialized string, or
10398        // `format!("{v}")` on the discriminant-Display route), any
10399        // two of which a future variant rename or
10400        // `#[serde(rename_all = "kebab-case")]` attribute would
10401        // silently desynchronize. Wiring [`std::fmt::Display`]
10402        // through [`RestartPolicy::as_str`] closes the third path:
10403        // every `format!("{v}")` call reaches the same lifted
10404        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
10405        // wire format and the [`RestartPolicy::as_str`] helper
10406        // already route through, so a future variant rename lands at
10407        // exactly one place. Pin the routing here so a future
10408        // `impl std::fmt::Display for RestartPolicy`
10409        // reimplementation that hand-rolls the arms instead of
10410        // delegating to [`RestartPolicy::as_str`] fails at
10411        // caixa-core build time. Peer of the sibling
10412        // [`restart_strategy_display_routes_through_as_str_helper`]
10413        // on the per-supervisor sibling-restart-strategy axis and
10414        // the M3
10415        // `placement_strategy_display_routes_through_as_str_helper`
10416        // (cc8f749) — the third of three OTP-shape closed-enum
10417        // discriminator axes on the caixa typed surface now
10418        // converged onto the same three-path
10419        // (Display → as_str → lifted const) discipline.
10420        for variant in [
10421            RestartPolicy::Permanent,
10422            RestartPolicy::Temporary,
10423            RestartPolicy::Transient,
10424        ] {
10425            assert_eq!(
10426                variant.to_string(),
10427                variant.as_str(),
10428                "RestartPolicy::{variant:?} Display must route through \
10429                 RestartPolicy::as_str (single source of truth: the lifted \
10430                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
10431            );
10432        }
10433    }
10434
10435    #[test]
10436    fn restart_policy_display_matches_serialized_wire_byte_string() {
10437        // The fail-before-pass-after pin on the second half of the
10438        // three-path convergence: `Display` (user-facing text) agrees
10439        // byte-for-byte with the `Serialize` derive's wire format
10440        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
10441        // scalar) on every variant. Pre-convergence the two paths
10442        // were structurally independent — a future
10443        // `#[serde(rename_all = "kebab-case")]` attribute on the
10444        // enum would silently rebrand the emitted wire scalar
10445        // (`permanent`, `temporary`, `transient`) while every
10446        // consumer that pretty-prints the policy (the future
10447        // wasm-operator's per-child post-exit restart-decision
10448        // diagnostic line, the future `feira app graph` per-child
10449        // restart column, the future M4
10450        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
10451        // per-child admission-webhook rejection body) would still
10452        // emit the PascalCase form the `as_str` / `Display` route
10453        // returns, with the mismatch surfacing at consumer parse
10454        // time / operator dispatch time far from the source rebrand
10455        // commit. Pin the two paths byte-for-byte here so any future
10456        // serde-attribute or variant-rename drift is a
10457        // caixa-core-build-time test failure at this call, not a
10458        // silent per-consumer dispatch miss. Peer of the sibling
10459        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
10460        // on the per-supervisor sibling-restart-strategy axis and
10461        // the M3
10462        // `placement_strategy_display_matches_serialized_wire_byte_string`
10463        // (cc8f749).
10464        for variant in [
10465            RestartPolicy::Permanent,
10466            RestartPolicy::Temporary,
10467            RestartPolicy::Transient,
10468        ] {
10469            let wire = serde_json::to_string(&variant).unwrap();
10470            let unquoted = wire
10471                .strip_prefix('"')
10472                .and_then(|s| s.strip_suffix('"'))
10473                .expect("serialized RestartPolicy is a JSON string");
10474            assert_eq!(
10475                variant.to_string(),
10476                unquoted,
10477                "RestartPolicy::{variant:?} Display byte-string must match the \
10478                 Serialize derive's wire byte-string (three-path convergence: \
10479                 Display + as_str + Serialize all resolve to the same \
10480                 SUPERVISOR_CHILD_RESTART_* const)"
10481            );
10482        }
10483    }
10484
10485    #[test]
10486    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
10487        // Fail-before-pass-after byte-parity pin on the lifted
10488        // `impl AsRef<str> for RestartPolicy` — asserts the
10489        // standard-library trait impl and the substrate-primitive
10490        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
10491        // to the same `&str` per instance across the three-arm
10492        // closed set, so any future silent detour that routes the
10493        // impl through a divergent projection (a per-arm inline
10494        // `match self { RestartPolicy::Permanent => "Permanent", … }`
10495        // re-inlining that opens a compile-time link to the un-lifted
10496        // arm-literal, a swap onto the kebab-case
10497        // [`gen_platform::Discriminant`] catalog identity that would
10498        // collide the wire axis with the dispatcher-catalog axis) trips
10499        // at caixa-core test time under `PartialEq` rather than at a
10500        // downstream `impl AsRef<str>`-bound consumer's silent split.
10501        // Sweeps every one of the three arms
10502        // [`RestartPolicy::ALL`] carries so no arm's projection is
10503        // covered only by the sibling wire-format `Serialize` derive
10504        // path. Peer of the sibling
10505        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
10506        // (63eb1a4) on the paired per-supervisor sibling-restart-
10507        // strategy axis and the [`crate::CaixaVersion`]
10508        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
10509        // top-level `:versao` typed newtype — the three pins together
10510        // cover the substrate primitive's `AsRef<str>` projection axis
10511        // on the paired newtype + M2 closed-set-typed-enum surface.
10512        for &variant in RestartPolicy::ALL {
10513            assert_eq!(
10514                <RestartPolicy as AsRef<str>>::as_ref(&variant),
10515                variant.as_str(),
10516                "AsRef<str> impl on RestartPolicy::{variant:?} must \
10517                 byte-equal RestartPolicy::as_str on the same instance \
10518                 — divergence signals a silent detour off the substrate-\
10519                 primitive accessor"
10520            );
10521        }
10522    }
10523
10524    #[test]
10525    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
10526        // Fail-before-pass-after byte-parity pin on the three-path
10527        // convergence discipline the M2 per-child-restart-policy
10528        // primitive now carries on the `&str`-projection axis:
10529        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
10530        // lifted impl), `format!("{v}")` (the pre-existing
10531        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
10532        // primitive `pub const fn` accessor both trait impls delegate
10533        // through) must resolve to the same byte-string on every
10534        // instance across the three-arm closed set. Refuses any future
10535        // divergence between the two trait impls (a stray
10536        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
10537        // rather than delegating through the shared accessor; a
10538        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
10539        // literal cascade) that would silently split the two
10540        // projection paths of the same closed-set typed enum. Mirrors
10541        // the sibling three-path-convergence discipline the peer
10542        // [`RestartStrategy`] typed enum carries on its
10543        // `AsRef<str>` / `Display` / `as_str` triple
10544        // (supervisor.rs pin
10545        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
10546        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
10547        // carries on the same triple (version.rs pin
10548        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
10549        // 16d5c7e).
10550        for &variant in RestartPolicy::ALL {
10551            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
10552            let via_display: String = format!("{variant}");
10553            let via_accessor: &str = variant.as_str();
10554            assert_eq!(via_as_ref, via_accessor);
10555            assert_eq!(via_display, via_accessor);
10556            assert_eq!(via_as_ref, via_display.as_str());
10557        }
10558    }
10559
10560    #[test]
10561    fn restart_policy_all_enumerates_every_variant_exactly_once() {
10562        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
10563        // exhaustive-iteration surface: every variant appears exactly
10564        // once, and the slice length matches the arm count of the
10565        // closed set. Every consumer that walks the accepted-policy
10566        // set (a future `feira supervisor --restart …` CLI-side
10567        // arg-parse's "did you mean" hint, a future M4 admission-
10568        // webhook's per-child rejection body naming the accepted-
10569        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
10570        // projection consumers that iterate the accept-set for
10571        // diagnostic rendering) reads through this slice, so a future
10572        // arm addition that grows the enum but forgets to grow
10573        // [`Self::ALL`] silently truncates every downstream consumer's
10574        // accept-set at the same pre-addition boundary — this pin
10575        // fails at caixa-core build time on the pairwise-distinct +
10576        // arm-count invariants.
10577        //
10578        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
10579        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
10580        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
10581        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
10582        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
10583        // pins on the peer closed-set typed-enum axes.
10584        let all: &[RestartPolicy] = RestartPolicy::ALL;
10585        assert_eq!(
10586            all.len(),
10587            3,
10588            "RestartPolicy::ALL must enumerate every variant of the \
10589             three-arm closed set (Permanent, Temporary, Transient); \
10590             got {all:?}"
10591        );
10592        for (i, a) in all.iter().enumerate() {
10593            for (j, b) in all.iter().enumerate() {
10594                if i != j {
10595                    assert_ne!(
10596                        a, b,
10597                        "RestartPolicy::ALL must carry every variant exactly \
10598                         once — got duplicate {a:?} at indices {i} and {j}"
10599                    );
10600                }
10601            }
10602        }
10603        for variant in [
10604            RestartPolicy::Permanent,
10605            RestartPolicy::Temporary,
10606            RestartPolicy::Transient,
10607        ] {
10608            assert!(
10609                all.contains(&variant),
10610                "RestartPolicy::ALL must contain {variant:?} — a future arm \
10611                 addition that grows the enum but forgets to grow the ALL slice \
10612                 silently truncates every downstream consumer's accept-set at \
10613                 the pre-addition boundary"
10614            );
10615        }
10616    }
10617
10618    #[test]
10619    fn restart_policy_from_wire_accepts_every_lifted_constant() {
10620        // Fail-before-pass-after pin on the forward accept-set of the
10621        // [`RestartPolicy::from_wire`] reverse projection: every
10622        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
10623        // constant the [`RestartPolicy::as_str`] emitter walks parses
10624        // back to its paired variant. Any future arm addition that
10625        // grows the emitter's `as_str` match but forgets to grow the
10626        // parser's `from_wire` match silently splits the two halves of
10627        // the round-trip — the wire byte-string one non-serde consumer
10628        // parses from the one the emitter wrote — with the failure
10629        // surfacing at the operator's reconcile posture (a `:temporary`
10630        // `oneShot` child restarted on clean exit, a `:transient` child
10631        // restarted after clean completion) far from the rebrand
10632        // commit. Pinning the three-arm accept-set here catches the
10633        // drift at caixa-core build time.
10634        //
10635        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
10636        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
10637        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
10638        // accept-set pins on the peer closed-set typed-enum `str → Self`
10639        // axes.
10640        for (wire, expected) in [
10641            (
10642                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10643                RestartPolicy::Permanent,
10644            ),
10645            (
10646                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10647                RestartPolicy::Temporary,
10648            ),
10649            (
10650                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10651                RestartPolicy::Transient,
10652            ),
10653        ] {
10654            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
10655                panic!(
10656                    "RestartPolicy::from_wire({wire:?}) must accept every \
10657                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
10658                     lifted canonical byte-string that RestartPolicy::{expected:?} \
10659                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
10660                )
10661            });
10662            assert_eq!(
10663                parsed, expected,
10664                "RestartPolicy::from_wire({wire:?}) must return \
10665                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
10666            );
10667        }
10668    }
10669
10670    #[test]
10671    fn restart_policy_from_wire_round_trips_through_as_str() {
10672        // Fail-before-pass-after pin on the closed round-trip between
10673        // the forward [`RestartPolicy::as_str`] emitter and the
10674        // reverse [`RestartPolicy::from_wire`] parser: for every
10675        // variant in [`RestartPolicy::ALL`], parsing the emitter's
10676        // output must return exactly the same variant. Any per-arm
10677        // divergence — a future arm added to `as_str` but not
10678        // `from_wire`, an accidental copy-paste flip in one but not
10679        // the other — silently splits the emit and parse halves and
10680        // the failure surfaces at consumer parse time far from the
10681        // drift site. The `ALL`-iterating shape means a future arm
10682        // addition picks up the coverage by construction.
10683        //
10684        // Peer of the sibling
10685        // [`restart_strategy_from_wire_round_trips_through_as_str`]
10686        // (4eec29c) round-trip pin on
10687        // [`RestartStrategy::from_wire`] and the M3
10688        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
10689        // (18c7342) round-trip pin on
10690        // [`crate::aplicacao::PlacementStrategy::from_wire`].
10691        for &variant in RestartPolicy::ALL {
10692            let wire = variant.as_str();
10693            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
10694                panic!(
10695                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
10696                     must be Some({variant:?}) — the two halves of the round-trip \
10697                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
10698                     got None on wire byte-string {wire:?}"
10699                )
10700            });
10701            assert_eq!(
10702                parsed, variant,
10703                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
10704                 must round-trip to the same variant; got {parsed:?}"
10705            );
10706        }
10707    }
10708
10709    #[test]
10710    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
10711        // Fail-before-pass-after pin on the closed-set refusal
10712        // discipline of [`RestartPolicy::from_wire`]: every
10713        // byte-string outside the three-arm accept-set returns `None`
10714        // rather than silently collapsing onto the [`Default`]
10715        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
10716        // exercised here sweeps the load-bearing drift shapes: the
10717        // empty string (a stripped serde-attribute drift), all-
10718        // whitespace strings (the canonical text-editor accidental
10719        // padding shape), the kebab-case dispatcher-catalog identities
10720        // (`"permanent"` / `"temporary"` / `"transient"` — the
10721        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
10722        // accept-set, which parses the *other* axis of this enum's
10723        // two-axis split and must not leak into the `from_wire`
10724        // PascalCase-wire accept-set — a lowercase leak here would
10725        // silently accept the operator's kebab-case
10726        // dispatcher-catalog probe under the wire-axis parser and mis-
10727        // route a `:permanent` intent), the padded canonical scalar
10728        // (`" Permanent "`), the trailing-newline shapes
10729        // (`"Permanent\n"`), the uppercase-single-word forms
10730        // (`"PERMANENT"`), and neighboring-but-unknown arms
10731        // (`"Restart"` — the canonical typo direction toward the
10732        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
10733        //
10734        // Peer of the sibling
10735        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
10736        // (4eec29c) +
10737        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
10738        // (2aa6d23) +
10739        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
10740        // (18c7342) refusal pins on the peer closed-set typed-enum
10741        // axes.
10742        for bad in [
10743            "",
10744            " ",
10745            "\n",
10746            "\t",
10747            "permanent",
10748            "temporary",
10749            "transient",
10750            "PERMANENT",
10751            "TEMPORARY",
10752            "TRANSIENT",
10753            "Permanents",
10754            "Permanent ",
10755            " Permanent",
10756            " Transient ",
10757            "Permanent\n",
10758            "perma",
10759            "Trans",
10760            "OneForOne",
10761            "Restart",
10762            "?",
10763        ] {
10764            assert!(
10765                RestartPolicy::from_wire(bad).is_none(),
10766                "RestartPolicy::from_wire({bad:?}) must return None — the \
10767                 parser's accept-set is exactly the three RestartPolicy::as_str \
10768                 outputs (Permanent, Temporary, Transient), and this \
10769                 byte-string is outside that closed set"
10770            );
10771        }
10772    }
10773
10774    #[test]
10775    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
10776        // Fail-before-pass-after pin on the fourth path of the four-path
10777        // convergence: `from_wire` (the reverse projection) inverts the
10778        // `Serialize` derive's wire byte-string on every variant.
10779        // Together with the pre-existing three-path convergence
10780        // (`Display` + `as_str` + `Serialize` all resolve to the same
10781        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
10782        // pinned by
10783        // [`restart_policy_display_matches_serialized_wire_byte_string`])
10784        // this closes the round-trip: the wire byte-string the
10785        // `Serialize` derive emits parses back to the same variant
10786        // through `from_wire`, so any future serde-attribute or variant-
10787        // rename drift on the emit half now surfaces as a matched drift
10788        // on the parse half at caixa-core build time — the two halves
10789        // migrate as a unit through the lifted consts on any future
10790        // rename, and the round-trip cannot silently split.
10791        //
10792        // Peer of the sibling
10793        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
10794        // (4eec29c) wire-format pin on
10795        // [`RestartStrategy::from_wire`] and the M3
10796        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
10797        // (18c7342) wire-format pin on
10798        // [`crate::aplicacao::PlacementStrategy::from_wire`].
10799        for &variant in RestartPolicy::ALL {
10800            let wire = serde_json::to_string(&variant).unwrap();
10801            let unquoted = wire
10802                .strip_prefix('"')
10803                .and_then(|s| s.strip_suffix('"'))
10804                .expect("serialized RestartPolicy is a JSON string");
10805            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
10806                panic!(
10807                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
10808                     Serialize derive's wire byte-string for \
10809                     RestartPolicy::{variant:?} — the four-path convergence \
10810                     (Display + as_str + Serialize + from_wire) resolves through \
10811                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
10812                )
10813            });
10814            assert_eq!(
10815                parsed, variant,
10816                "RestartPolicy::from_wire of the Serialize derive's wire \
10817                 byte-string for RestartPolicy::{variant:?} must round-trip \
10818                 to the same variant; got {parsed:?}"
10819            );
10820        }
10821    }
10822
10823    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
10824    //
10825    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
10826    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
10827    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
10828    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
10829    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
10830    // the peer per-`:upgrade-from :from` axis. The three pins jointly
10831    // brace the accessor against every future silent detour that would
10832    // desynchronize it from the raw `.caixa` field access every consumer
10833    // previously open-coded.
10834
10835    #[test]
10836    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
10837        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
10838        // [`ChildSpec::nome`] must return the `:children :caixa` field
10839        // byte-for-byte across every DNS-1123-label value the upstream
10840        // [`crate::render::require_valid_dns_1123_label`] gate at
10841        // `SupervisorSpec::validate` admits. Peer of the sibling
10842        // `membro_nome_returns_caixa_byte_equal_across_permutations`
10843        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
10844        // substrate-primitive accessor must byte-equal the raw field
10845        // access verbatim across every author-declared value" discipline
10846        // extended to the M2 supervisor-tree per-`:children` arm. Pins
10847        // against a future silent detour that re-normalized the child
10848        // identity (an accidental `.to_lowercase()` — every `:children
10849        // :caixa` is validated as a DNS-1123 label upstream, so any
10850        // re-normalization is redundant + a drift surface between the
10851        // validator and the accessor), a namespace-prefix rewrite (an
10852        // accidental `format!("{namespace}/{caixa}")` per-CR
10853        // fully-qualified rewrite that didn't land on the peer axes), or
10854        // a per-cluster alias stamp the future wasm-operator's
10855        // hierarchical reconciliation scheduler authors on one consumer
10856        // without the others. Five values sweep the accept-set the
10857        // DNS-1123 gate upstream admits (short single-word / dashed /
10858        // v-suffixed / mixed-digit child names).
10859        for name in [
10860            "worker",
10861            "cache-server",
10862            "scratch-job",
10863            "orders-v2",
10864            "session-8080",
10865        ] {
10866            let c = ChildSpec {
10867                caixa: name.into(),
10868                versao: "^0.1".into(),
10869                restart: RestartPolicy::Permanent,
10870            };
10871            assert_eq!(
10872                c.nome(),
10873                name,
10874                "ChildSpec::nome must return :children :caixa verbatim \
10875                 (got {:?}, expected {name:?})",
10876                c.nome(),
10877            );
10878            assert_eq!(
10879                c.nome(),
10880                c.caixa.as_str(),
10881                "ChildSpec::nome must byte-equal the .caixa field access",
10882            );
10883        }
10884    }
10885
10886    #[test]
10887    fn child_spec_nome_borrows_from_caixa_storage() {
10888        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
10889        // `&str` slice that borrows from the typed slot's own [`String`]
10890        // storage — same-address invariant with `c.caixa.as_str()`. Pins
10891        // against a future silent detour that allocated a fresh `String`
10892        // (`self.caixa.clone()` in the body would type-check but silently
10893        // drop the borrow, and every downstream consumer that assumed
10894        // the returned slice outlives `&self` would break on a stale-
10895        // reference use-after-free — the [`crate::render::insert_first_seen`]
10896        // dedup key at [`SupervisorSpec::validate`], the
10897        // [`validate_no_self_supervision`] equality check against the
10898        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
10899        // borrow — each would silently misbehave if this accessor
10900        // produced a detached copy). Peer of the sibling
10901        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
10902        // M3 per-`:membros` axis and the
10903        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
10904        // first M2 slot scalar accessor.
10905        let c = ChildSpec {
10906            caixa: "worker".into(),
10907            versao: "^0.1".into(),
10908            restart: RestartPolicy::Permanent,
10909        };
10910        let name = c.nome();
10911        let caixa_slice = c.caixa.as_str();
10912        assert_eq!(
10913            name.as_ptr(),
10914            caixa_slice.as_ptr(),
10915            "ChildSpec::nome must borrow from the .caixa String's backing \
10916             storage — a fresh allocation here means the accessor no \
10917             longer names the substrate-primitive typed dispatch and \
10918             every downstream consumer would silently carry a detached \
10919             copy",
10920        );
10921        assert_eq!(
10922            name.len(),
10923            caixa_slice.len(),
10924            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
10925             as well as in address",
10926        );
10927    }
10928
10929    #[test]
10930    fn validate_gates_child_nome_through_lifted_accessor() {
10931        // Bilateral coherence pin: every `:children :caixa` that
10932        // [`SupervisorSpec::validate`] accepts is one
10933        // [`crate::render::require_valid_dns_1123_label`] accepts on the
10934        // accessor-projected value, and vice versa on the reject side.
10935        // This closes the "the validator reads through the accessor"
10936        // contract structurally — a future silent detour that made the
10937        // accessor return a different byte-string than the validator
10938        // gates against would surface here as a coverage mismatch, not
10939        // as an apply-time DNS-1123 rejection at
10940        // `metadata.name: Invalid value` far from the caixa.lisp source.
10941        // Peer of the M2 sibling
10942        // `validate_parses_prior_versao_through_lifted_accessor`
10943        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
10944        // `validate_membros` peer discipline.
10945        //
10946        // Accept-set sweep: five DNS-1123-label values the upstream gate
10947        // admits.
10948        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
10949            let s = SupervisorSpec {
10950                children: vec![ChildSpec {
10951                    caixa: ok_name.into(),
10952                    versao: "^0.1".into(),
10953                    restart: RestartPolicy::Permanent,
10954                }],
10955                ..SupervisorSpec::default()
10956            };
10957            s.validate().unwrap_or_else(|e| {
10958                panic!(
10959                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
10960                     (upstream DNS-1123 gate accepts it): got {e:?}",
10961                );
10962            });
10963            let c = ChildSpec {
10964                caixa: ok_name.into(),
10965                versao: "^0.1".into(),
10966                restart: RestartPolicy::Permanent,
10967            };
10968            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
10969                .unwrap_or_else(|()| {
10970                    panic!(
10971                        "require_valid_dns_1123_label must accept the accessor-projected \
10972                     :children :caixa {ok_name:?}",
10973                    );
10974                });
10975        }
10976        // Reject-set sweep: five DNS-1123-label-violating shapes the
10977        // upstream gate refuses (empty / uppercase / underscore / dot /
10978        // leading-hyphen). Every rejection at the validator must
10979        // correspond to a rejection when the accessor's projected value
10980        // is fed back through the shared gate.
10981        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
10982            let s = SupervisorSpec {
10983                children: vec![ChildSpec {
10984                    caixa: bad_name.into(),
10985                    versao: "^0.1".into(),
10986                    restart: RestartPolicy::Permanent,
10987                }],
10988                ..SupervisorSpec::default()
10989            };
10990            let err = s.validate().unwrap_err();
10991            assert!(
10992                matches!(
10993                    err,
10994                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
10995                ),
10996                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
10997                 via the DNS-1123 gate: got {err:?}",
10998            );
10999            let c = ChildSpec {
11000                caixa: bad_name.into(),
11001                versao: "^0.1".into(),
11002                restart: RestartPolicy::Permanent,
11003            };
11004            assert!(
11005                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
11006                    .is_err(),
11007                "require_valid_dns_1123_label must reject the accessor-projected \
11008                 :children :caixa {bad_name:?}",
11009            );
11010        }
11011    }
11012
11013    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
11014    //
11015    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
11016    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
11017    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
11018    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
11019    // trio on the peer per-`:children` `String`-carry axis. The three pins
11020    // jointly brace the accessor against every future silent detour that
11021    // would desynchronize it from the raw `.versao` field access the
11022    // requirement gate + error carrier previously open-coded.
11023    //
11024    // Closes the last unlifted per-`:children` `String`-carry axis: the
11025    // pair (`nome`, `versao_requirement`) now jointly projects the
11026    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
11027    // consumer that fans on per-child identity + version pin reads,
11028    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
11029    // pair discipline verbatim.
11030    #[test]
11031    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
11032        // The canonical per-`:children` child-`:versao`-scalar pin:
11033        // [`ChildSpec::versao_requirement`] must return the `:children
11034        // :versao` field byte-for-byte across every Cargo-shaped semver
11035        // requirement value the upstream
11036        // [`crate::render::require_valid_versao_requirement`] gate admits.
11037        // Peer of the sibling
11038        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
11039        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
11040        // substrate-primitive accessor must byte-equal the raw field
11041        // access verbatim across every author-declared value" discipline
11042        // extended to the M2 supervisor-tree per-`:children` arm. Pins
11043        // against a future silent detour that re-canonicalized the
11044        // requirement (an accidental `.to_string()` via
11045        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
11046        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
11047        // silently drifted the error carrier's quoted requirement away
11048        // from the source `caixa.lisp`, an accidental whitespace trim on
11049        // `"^ 0.1"` that no consumer ever produced from the field-access
11050        // side, an accidental per-cluster lacre-projected concrete-version
11051        // rewrite that didn't land on the peer requirement-gate call).
11052        // Five values sweep the accept-set the shared
11053        // [`crate::render::require_valid_versao_requirement`] gate admits
11054        // (caret / tilde / exact / wildcard / bare-major).
11055        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
11056            let c = ChildSpec {
11057                caixa: "worker".into(),
11058                versao: req.into(),
11059                restart: RestartPolicy::Permanent,
11060            };
11061            assert_eq!(
11062                c.versao_requirement(),
11063                req,
11064                "ChildSpec::versao_requirement must return :children :versao \
11065                 verbatim (got {:?}, expected {req:?})",
11066                c.versao_requirement(),
11067            );
11068            assert_eq!(
11069                c.versao_requirement(),
11070                c.versao.as_str(),
11071                "ChildSpec::versao_requirement must byte-equal the .versao \
11072                 field access",
11073            );
11074        }
11075    }
11076
11077    #[test]
11078    fn child_spec_versao_requirement_borrows_from_versao_storage() {
11079        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
11080        // return a `&str` slice that borrows from the typed slot's own
11081        // [`String`] storage — same-address invariant with
11082        // `c.versao.as_str()`. Pins against a future silent detour that
11083        // allocated a fresh `String` (`self.versao.clone()` in the body
11084        // would type-check but silently drop the borrow, and every
11085        // downstream consumer that assumed the returned slice outlives
11086        // `&self` — the [`crate::render::require_valid_versao_requirement`]
11087        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
11088        // `.to_string()` carrier's byte-length assumption — would silently
11089        // misbehave if this accessor produced a detached copy). Peer of
11090        // the sibling `child_spec_nome_borrows_from_caixa_storage`
11091        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
11092        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
11093        // pin on the peer per-`:membros` `:versao` axis.
11094        let c = ChildSpec {
11095            caixa: "worker".into(),
11096            versao: "^0.1".into(),
11097            restart: RestartPolicy::Permanent,
11098        };
11099        let req = c.versao_requirement();
11100        let versao_slice = c.versao.as_str();
11101        assert_eq!(
11102            req.as_ptr(),
11103            versao_slice.as_ptr(),
11104            "ChildSpec::versao_requirement must borrow from the .versao \
11105             String's backing storage — a fresh allocation here means the \
11106             accessor no longer names the substrate-primitive typed \
11107             dispatch and every downstream consumer would silently carry \
11108             a detached copy",
11109        );
11110        assert_eq!(
11111            req.len(),
11112            versao_slice.len(),
11113            "ChildSpec::versao_requirement and .versao.as_str() must \
11114             byte-equal in length as well as in address",
11115        );
11116    }
11117
11118    #[test]
11119    fn validate_gates_child_versao_through_lifted_accessor() {
11120        // Bilateral coherence pin: every `:children :versao` that
11121        // [`SupervisorSpec::validate`] accepts is one
11122        // [`crate::render::require_valid_versao_requirement`] accepts on
11123        // the accessor-projected value, and vice versa on the reject side.
11124        // This closes the "the validator reads through the accessor"
11125        // contract structurally — a future silent detour that made the
11126        // accessor return a different byte-string than the validator gates
11127        // against would surface here as a coverage mismatch, not as a
11128        // resolver-time semver-parse rejection at lacre-closure time far
11129        // from the caixa.lisp source. Peer of the sibling
11130        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
11131        // the per-`:children :caixa` axis and the M2
11132        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
11133        // on the peer per-`:upgrade-from :from` axis.
11134        //
11135        // Accept-set sweep: five Cargo-shaped semver requirement values
11136        // the upstream gate admits (caret / tilde / exact / wildcard /
11137        // bare-major).
11138        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
11139            let s = SupervisorSpec {
11140                children: vec![ChildSpec {
11141                    caixa: "worker".into(),
11142                    versao: ok_req.into(),
11143                    restart: RestartPolicy::Permanent,
11144                }],
11145                ..SupervisorSpec::default()
11146            };
11147            s.validate().unwrap_or_else(|e| {
11148                panic!(
11149                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
11150                     (upstream versao-requirement gate accepts it): got {e:?}",
11151                );
11152            });
11153            let c = ChildSpec {
11154                caixa: "worker".into(),
11155                versao: ok_req.into(),
11156                restart: RestartPolicy::Permanent,
11157            };
11158            crate::render::require_valid_versao_requirement(
11159                c.versao_requirement(),
11160                || (),
11161                |_reason| (),
11162            )
11163            .unwrap_or_else(|()| {
11164                panic!(
11165                    "require_valid_versao_requirement must accept the accessor-projected \
11166                     :children :versao {ok_req:?}",
11167                );
11168            });
11169        }
11170        // Reject-set sweep: five requirement-violating shapes the upstream
11171        // gate refuses. The empty string closes the empty-first arm of the
11172        // shared [`crate::render::require_valid_versao_requirement`]
11173        // cascade; the four non-empty arms exercise distinct semver-parse
11174        // failure modes the M3 peer per-`:membros` reject-set already pins
11175        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
11176        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
11177        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
11178        // shared parser routing means the same reject-set must fail
11179        // identically at the M2 supervisor-tree per-`:children` accessor
11180        // arm here. Every rejection at the validator must correspond to a
11181        // rejection when the accessor's projected value is fed back
11182        // through the shared gate.
11183        //
11184        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
11185        // `"not-a-semver"` are intentionally *not* in the reject-set: the
11186        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
11187        // and the identifier-tail arm's grammar admits some non-canonical
11188        // shapes — matching what the M3 peer test suite already documents
11189        // as the shared parser's accept-set edges.)
11190        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
11191            let s = SupervisorSpec {
11192                children: vec![ChildSpec {
11193                    caixa: "worker".into(),
11194                    versao: bad_req.into(),
11195                    restart: RestartPolicy::Permanent,
11196                }],
11197                ..SupervisorSpec::default()
11198            };
11199            let err = s.validate().unwrap_err();
11200            assert!(
11201                matches!(
11202                    err,
11203                    SupervisorError::EmptyChildVersion { .. }
11204                        | SupervisorError::ChildVersaoInvalid { .. }
11205                ),
11206                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
11207                 via the versao-requirement gate: got {err:?}",
11208            );
11209            let c = ChildSpec {
11210                caixa: "worker".into(),
11211                versao: bad_req.into(),
11212                restart: RestartPolicy::Permanent,
11213            };
11214            assert!(
11215                crate::render::require_valid_versao_requirement(
11216                    c.versao_requirement(),
11217                    || (),
11218                    |_reason| (),
11219                )
11220                .is_err(),
11221                "require_valid_versao_requirement must reject the accessor-projected \
11222                 :children :versao {bad_req:?}",
11223            );
11224        }
11225    }
11226
11227    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
11228    //
11229    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
11230    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
11231    // already project the `String`-carry `(caixa, versao)` fields; the
11232    // `Copy`-composite-enum `restart` field is the third and final axis).
11233    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
11234    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
11235    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
11236    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
11237    // strategy scalar accessor — same "one typed dispatch on the substrate
11238    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
11239    // extended onto the M2 supervisor-slot per-`:children` restart-decision
11240    // axis. The pin below covers the accessor's byte-equal projection
11241    // against the raw field access across every variant in the closed
11242    // accept-set (`Permanent`, `Transient`, `Temporary`).
11243
11244    #[test]
11245    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
11246        // The canonical per-`:children` restart-decision-policy-scalar
11247        // pin: [`ChildSpec::restart`] must return the `:children :restart`
11248        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
11249        // typed slot's own [`RestartPolicy`] storage across every variant
11250        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
11251        // Pins against a future silent detour that re-derived the policy
11252        // from a peer axis (an accidental fallback to
11253        // `if is_supervisor_child { Permanent } else { Temporary }` that
11254        // collapsed the child's kind axis into the restart discriminator),
11255        // a variant remap the operator authors on one consumer without the
11256        // other, or a stale-derive detour that substituted
11257        // [`RestartPolicy::default`] when the field held any explicit
11258        // variant (which would silently collapse the distinction between
11259        // "author explicitly declared `:restart Permanent`" and "author
11260        // omitted the slot and inherited the default" the future
11261        // per-cluster restart-decision override slot depends on).
11262        //
11263        // Peer of the sibling per-`:supervisor`
11264        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
11265        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
11266        // axis and the M3
11267        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
11268        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
11269        // — same "the substrate-primitive accessor must byte-equal the raw
11270        // field access verbatim across every author-declared value"
11271        // discipline extended onto the M2 supervisor-slot per-`:children`
11272        // restart-decision-policy axis, closing the last unlifted axis on
11273        // the per-`:children` [`ChildSpec`] type.
11274        for restart in [
11275            RestartPolicy::Permanent,
11276            RestartPolicy::Transient,
11277            RestartPolicy::Temporary,
11278        ] {
11279            let c = ChildSpec {
11280                caixa: "worker".into(),
11281                versao: "^0.1".into(),
11282                restart,
11283            };
11284            assert_eq!(
11285                c.restart(),
11286                restart,
11287                "ChildSpec::restart must return :children :restart \
11288                 verbatim (got {:?}, expected {restart:?})",
11289                c.restart(),
11290            );
11291            assert_eq!(
11292                c.restart(),
11293                c.restart,
11294                "ChildSpec::restart accessor and .restart field access \
11295                 must byte-equal — the accessor is the substrate-primitive \
11296                 typed dispatch every downstream per-child restart-\
11297                 decision consumer must route through",
11298            );
11299        }
11300    }
11301
11302    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
11303    //
11304    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
11305    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
11306    // distribution-strategy accessor discipline onto the M2 supervisor-slot
11307    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
11308    // scalar axis. The two pins below cover (1) the accessor's byte-equal
11309    // projection against the raw field access across every variant in the
11310    // closed accept-set, and (2) the two-consumer coherence between the
11311    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
11312    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
11313    // carrier's `estrategia:` field — peer of the sibling M3
11314    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
11315    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
11316    // pair on the per-`:placement` distribution-strategy axis.
11317
11318    #[test]
11319    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
11320        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
11321        // pin: [`SupervisorSpec::estrategia`] must return the
11322        // `:supervisor :estrategia` field verbatim as a
11323        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
11324        // [`RestartStrategy`] storage across every variant in the closed
11325        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
11326        // `SimpleOneForOne`). Pins against a future silent detour that
11327        // re-derived the strategy from a peer axis (an accidental
11328        // fallback to `if children.is_empty() { SimpleOneForOne } else {
11329        // OneForOne }` collapse that read the children-count axis into
11330        // the strategy discriminator), a variant remap the operator
11331        // authors on one consumer without the other, or a stale-derive
11332        // detour that substituted [`RestartStrategy::default`] when the
11333        // field held any explicit variant (which would silently collapse
11334        // the distinction between "author explicitly declared
11335        // `:estrategia OneForOne`" and "author omitted the slot and
11336        // inherited the default" the future per-cluster strategy override
11337        // slot depends on). Peer of the sibling M3
11338        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
11339        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
11340        // axis — same "the substrate-primitive accessor must byte-equal
11341        // the raw field access verbatim across every author-declared
11342        // value" discipline extended onto the M2 supervisor-slot
11343        // per-`:supervisor` sibling-restart-strategy axis.
11344        for &estrategia in RestartStrategy::ALL {
11345            // `SimpleOneForOne` requires `children.is_empty()`; the peer
11346            // three strategies require a non-empty static children list.
11347            // Build each shape coherently so the pin's fixture would
11348            // itself pass [`SupervisorSpec::validate`] once fed through
11349            // the sibling coherence pin below — the byte-equal projection
11350            // asserted here is a strictly weaker property (a `Copy` field
11351            // read) that does not depend on `validate` running, but
11352            // keeping the fixture validate-clean means a future extension
11353            // of the pin to exercise `validate` end-to-end does not have
11354            // to re-author the children shape.
11355            //
11356            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
11357            // shape partition through the [`gen_platform::IsVariant`]
11358            // derive-generated
11359            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
11360            // than the raw `matches!(estrategia, RestartStrategy::
11361            // SimpleOneForOne)` open-coded pattern-match — same closed-
11362            // set-typed-enum arm-discriminator dispatch discipline the
11363            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
11364            // convergence (915a934) extended onto its two paired positive
11365            // / negated `matches!` sites and the peer
11366            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
11367            // predicate convergence (766ec63) extended onto the M3 mesh-
11368            // slot per-`:placement` distribution-strategy discriminator
11369            // axis. See the sibling `round_trip_all_strategies` and the
11370            // peer `manifest::tests::
11371            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
11372            // fixture for the two peer sites the same lift closes on.
11373            let children = if estrategia.is_simple_one_for_one() {
11374                Vec::new()
11375            } else {
11376                vec![ChildSpec {
11377                    caixa: "worker".into(),
11378                    versao: "^0.1".into(),
11379                    restart: RestartPolicy::Permanent,
11380                }]
11381            };
11382            let s = SupervisorSpec {
11383                estrategia,
11384                children,
11385                ..SupervisorSpec::default()
11386            };
11387            assert_eq!(
11388                s.estrategia(),
11389                estrategia,
11390                "SupervisorSpec::estrategia must return :supervisor :estrategia \
11391                 verbatim (got {:?}, expected {estrategia:?})",
11392                s.estrategia(),
11393            );
11394            assert_eq!(
11395                s.estrategia(),
11396                s.estrategia,
11397                "SupervisorSpec::estrategia accessor and .estrategia field \
11398                 access must byte-equal — the accessor is the substrate-\
11399                 primitive typed dispatch every downstream sibling-restart-\
11400                 strategy consumer must route through",
11401            );
11402        }
11403    }
11404
11405    #[test]
11406    fn validate_reads_through_lifted_estrategia_accessor() {
11407        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
11408        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
11409        // dispatch (which reads through [`SupervisorSpec::estrategia`]
11410        // to fan across the strategy-arm shape-gate cascades) and the
11411        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
11412        // error carrier's `estrategia:` field (which reads through
11413        // [`SupervisorSpec::estrategia`] to name the strategy the empty
11414        // `:children` list was declared against) must both key off the
11415        // lifted accessor, so any future rebrand on the typed slot's
11416        // reader shape lands at exactly one place. Pins the two-site
11417        // coherence by exercising the `NoChildren` error surface end-to-
11418        // end across every non-`SimpleOneForOne` variant and asserting
11419        // the surfaced `estrategia:` field byte-equals the accessor's
11420        // return. Peer of the sibling M3
11421        // `validate_placement_reads_through_lifted_estrategia_accessor`
11422        // (921fe1b) three-consumer coherence pin on the per-`:placement`
11423        // distribution-strategy axis.
11424        for estrategia in [
11425            RestartStrategy::OneForOne,
11426            RestartStrategy::OneForAll,
11427            RestartStrategy::RestForOne,
11428        ] {
11429            let s = SupervisorSpec {
11430                estrategia,
11431                children: Vec::new(),
11432                ..SupervisorSpec::default()
11433            };
11434            let err = s.validate().unwrap_err();
11435            match err {
11436                SupervisorError::NoChildren { estrategia: e } => {
11437                    assert_eq!(
11438                        e,
11439                        s.estrategia(),
11440                        "NoChildren.estrategia must byte-equal \
11441                         SupervisorSpec::estrategia() — the empty-`:children` \
11442                         refusal reads through the lifted accessor",
11443                    );
11444                    assert_eq!(
11445                        e, estrategia,
11446                        "NoChildren.estrategia must carry the author-declared \
11447                         :supervisor :estrategia variant verbatim (got {e:?}, \
11448                         expected {estrategia:?})",
11449                    );
11450                }
11451                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
11452            }
11453        }
11454    }
11455
11456    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
11457    //
11458    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
11459    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
11460    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
11461    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
11462    // The two pins below cover (1) the accessor's byte-equal projection
11463    // against the raw field access across every representative value in
11464    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
11465    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
11466    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
11467    // zero-floor / cap composition — the validate gate and the accessor
11468    // must route through the same substrate-primitive typed dispatch, so
11469    // any future silent detour that had the accessor perform a
11470    // bounds-collapsing clamp would fail here at caixa-core build time.
11471    // Peer of the sibling M3
11472    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
11473    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
11474
11475    #[test]
11476    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
11477        // The canonical per-`:supervisor` restart-budget-count scalar pin:
11478        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
11479        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
11480        // typed slot's own `u32` storage, byte-equal to the raw field
11481        // access across every representative value in the accept-set —
11482        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
11483        // accept-set the surrounding [`SupervisorSpec::validate`] gate
11484        // carves out on the sibling `ZeroMaxRestarts` refusal),
11485        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
11486        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
11487        // (a past-the-guard sentinel that pins the accessor doesn't
11488        // perform a silent bounds-collapse into `1` on the zero arm —
11489        // validate rejects zero but the accessor must ship the raw slot
11490        // verbatim so a validate-time gate regression surfaces at the
11491        // emit boundary rather than being silently absorbed), `u32::MAX`
11492        // (a past-the-guard sentinel that pins the accessor doesn't
11493        // perform a silent bounds-collapse through
11494        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
11495        //
11496        // Peer of the sibling M3
11497        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
11498        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
11499        // required-scalar axis — same "the substrate-primitive accessor
11500        // must byte-equal the raw field access verbatim across every
11501        // value in the `u32` accept-set" discipline extended onto the M2
11502        // supervisor-slot per-`:supervisor` restart-budget-count axis.
11503        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
11504            let s = SupervisorSpec {
11505                max_restarts,
11506                ..SupervisorSpec::default()
11507            };
11508            assert_eq!(
11509                s.max_restarts(),
11510                max_restarts,
11511                "SupervisorSpec::max_restarts must return :supervisor \
11512                 :max-restarts verbatim (got {}, expected {max_restarts})",
11513                s.max_restarts(),
11514            );
11515            assert_eq!(
11516                s.max_restarts(),
11517                s.max_restarts,
11518                "SupervisorSpec::max_restarts accessor and .max_restarts \
11519                 field access must byte-equal — the accessor is the \
11520                 substrate-primitive typed dispatch every downstream \
11521                 restart-budget-count consumer must route through",
11522            );
11523        }
11524    }
11525
11526    #[test]
11527    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
11528        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
11529        // zero-floor + upper-cap bracket must key off
11530        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
11531        // field access. Structurally: a `SupervisorSpec { max_restarts:
11532        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
11533        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
11534        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
11535        // (with the offending count carried verbatim from the accessor
11536        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
11537        // lower boundary of the accept-set) plus a `SupervisorSpec {
11538        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
11539        // boundary) must pass validate. The four together jointly pin the
11540        // accessor + validate-gate composition: any future silent detour
11541        // that had the accessor return a fresh `1` on the zero arm (a
11542        // `.max_restarts().max(1)` collapse) would silently absorb the
11543        // `ZeroMaxRestarts` refusal at the accessor boundary and the
11544        // validate gate would accept a struct-literal `SupervisorSpec {
11545        // max_restarts: 0, .. }` — the composition pin catches that at
11546        // caixa-core build time.
11547        //
11548        // Peer of the sibling M3
11549        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
11550        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
11551        // composition axis — same "the validate / shape-gate predicate
11552        // must route through the substrate-primitive typed dispatch"
11553        // discipline extended onto the peer M2 supervisor-slot
11554        // required-`u32` composition axis.
11555        let child = ChildSpec {
11556            caixa: "worker".into(),
11557            versao: "^0.1".into(),
11558            restart: RestartPolicy::Permanent,
11559        };
11560        // Zero-floor arm.
11561        let s = SupervisorSpec {
11562            max_restarts: 0,
11563            children: vec![child.clone()],
11564            ..SupervisorSpec::default()
11565        };
11566        assert_eq!(
11567            s.validate().unwrap_err(),
11568            SupervisorError::ZeroMaxRestarts,
11569            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
11570             — the accessor and the validate gate must route through the \
11571             same substrate-primitive typed dispatch on the zero-floor arm",
11572        );
11573        // Cap arm — the surfaced `max_restarts:` field must byte-equal
11574        // the accessor's return so a future rebrand on the accessor
11575        // lands in the diagnostic without a coordinated rewrite.
11576        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
11577        let s = SupervisorSpec {
11578            max_restarts: over_cap,
11579            children: vec![child.clone()],
11580            ..SupervisorSpec::default()
11581        };
11582        match s.validate().unwrap_err() {
11583            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
11584                assert_eq!(
11585                    max_restarts,
11586                    s.max_restarts(),
11587                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
11588                     SupervisorSpec::max_restarts() — the cap-arm refusal \
11589                     reads through the lifted accessor",
11590                );
11591                assert_eq!(
11592                    max_restarts, over_cap,
11593                    "MaxRestartsExceedsCap.max_restarts must carry the \
11594                     author-declared :supervisor :max-restarts value \
11595                     verbatim (got {max_restarts}, expected {over_cap})",
11596                );
11597            }
11598            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
11599        }
11600        // Lower + upper accept-set boundaries.
11601        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
11602            let s = SupervisorSpec {
11603                max_restarts,
11604                children: vec![child.clone()],
11605                ..SupervisorSpec::default()
11606            };
11607            assert!(
11608                s.validate().is_ok(),
11609                "validate must accept max_restarts == {max_restarts} \
11610                 (an accept-set boundary of \
11611                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
11612            );
11613        }
11614    }
11615
11616    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
11617    //
11618    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
11619    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
11620    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
11621    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
11622    // supervisor-slot per-`:supervisor` restart-intensity-denominator
11623    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
11624    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
11625    // per-`:supervisor` scalar-value axis. The three pins below cover
11626    // (1) the accessor's byte-equal projection against the raw field
11627    // access across every representative value in the `Option<Duration>`
11628    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
11629    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
11630    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
11631    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
11632    // `if let Some(w) = self.restart_window() { … }` bracket-arm
11633    // composition — the validate gate and the accessor must route through
11634    // the same substrate-primitive typed dispatch, so any future silent
11635    // detour that had the accessor perform a bounds-collapsing clamp
11636    // would fail here at caixa-core build time, and (3) the accessor's
11637    // by-copy idempotence pin — the returned `Option<Duration>` must
11638    // outlive `&self` and two successive calls must return byte-equal
11639    // values. Peer of the sibling M2
11640    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
11641    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
11642    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
11643    // (7073d0f) pin on the per-`:politicas :timeout` axis.
11644
11645    #[test]
11646    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
11647        // The canonical per-`:supervisor` restart-intensity-denominator
11648        // scalar pin: [`SupervisorSpec::restart_window`] must return the
11649        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
11650        // `Option<Duration>`, `Copy`-projected from the typed slot's own
11651        // `Option<Duration>` storage, byte-equal to the raw field access
11652        // across every representative value in the accept-set — `None`
11653        // (the "never reset — every restart across the supervisor's
11654        // lifetime counts against the sibling `:max-restarts` budget"
11655        // sentinel the field's own docstring names and the peer
11656        // `validate_accepts_none_restart_window` pin locks in on the
11657        // [`SupervisorSpec::validate`] entry-side),
11658        // `Some(Duration::from_millis(1))` (the structural minimum a
11659        // validated `:restart-window` may carry, the integer-millisecond
11660        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
11661        // everything sub-ms; `Duration::ZERO` is separately rejected by
11662        // [`SupervisorError::RestartWindowZero`]),
11663        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
11664        // surrounding [`SupervisorSpec::validate`] gate carves out on the
11665        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
11666        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
11667        // accessor doesn't perform a silent bounds-collapse into `None` on
11668        // the zero-Duration arm — validate rejects zero but the accessor
11669        // must ship the raw slot verbatim so a validate-time gate
11670        // regression surfaces at the emit boundary rather than being
11671        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
11672        // sentinel that pins the accessor doesn't perform a silent
11673        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
11674        // return path).
11675        //
11676        // Peer of the sibling M2
11677        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
11678        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
11679        // sibling M3
11680        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
11681        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
11682        // substrate-primitive accessor must byte-equal the raw field
11683        // access verbatim across every value in the `Option<Duration>`
11684        // accept-set" discipline extended onto the M2 supervisor-slot
11685        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
11686        // silent detour that re-derived the restart-window from a peer
11687        // axis (an accidental `.max_restarts.into()` collapse that read
11688        // the restart-budget-count as a duration — the two axes serve
11689        // different halves of the `MaxIntensity / Period` restart-
11690        // intensity ratio, and confusing them silently inverts the
11691        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
11692        // "zero means never reset" collapse (the canonical
11693        // `Option<Duration>` → `Duration` collapse footgun the
11694        // [`SupervisorError::RestartWindowZero`] validate arm guards on
11695        // the peer zero-floor axis; a zero period either trips on the
11696        // first failure or never trips depending on operator
11697        // interpretation, neither of which is the author's "never reset"
11698        // intent that `None` expresses structurally), or a per-arm
11699        // variant swap that landed on one consumer without the other.
11700        for restart_window in [
11701            None,
11702            Some(Duration::from_millis(1)),
11703            Some(SUPERVISOR_RESTART_WINDOW_MAX),
11704            Some(Duration::ZERO),
11705            Some(Duration::MAX),
11706        ] {
11707            let s = SupervisorSpec {
11708                restart_window,
11709                ..SupervisorSpec::default()
11710            };
11711            assert_eq!(
11712                s.restart_window(),
11713                restart_window,
11714                "SupervisorSpec::restart_window must return :supervisor \
11715                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
11716                s.restart_window(),
11717            );
11718            assert_eq!(
11719                s.restart_window(),
11720                s.restart_window,
11721                "SupervisorSpec::restart_window accessor and \
11722                 .restart_window field access must byte-equal — the \
11723                 accessor is the substrate-primitive typed dispatch every \
11724                 downstream restart-intensity-denominator consumer must \
11725                 route through",
11726            );
11727        }
11728    }
11729
11730    #[test]
11731    fn validate_restart_window_bracket_arm_routes_through_accessor() {
11732        // Composition pin: [`SupervisorSpec::validate`]'s
11733        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
11734        // zero-floor + integer-millisecond canonical-form + upper-cap
11735        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
11736        // the raw `.restart_window` field access. Structurally: a
11737        // `SupervisorSpec { restart_window: None, .. }` must pass the
11738        // arm gate structurally (the `if let Some(_)` shape returns
11739        // early on the `None` arm — the accessor and the validate gate
11740        // must agree on `None → skip the bracket cascade` so an authored
11741        // `:restart-window ()` structurally routes through the "never
11742        // reset" sentinel path), a `SupervisorSpec { restart_window:
11743        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
11744        // refusal exactly, a `SupervisorSpec { restart_window:
11745        // Some(Duration::from_micros(1500)), .. }` must surface the
11746        // `RestartWindowNotCanonical` refusal exactly (with the offending
11747        // duration carried verbatim from the accessor return), a
11748        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
11749        // + Duration::from_millis(1)), .. }` must surface the
11750        // `RestartWindowExceedsCap` refusal exactly (with the offending
11751        // duration carried verbatim from the accessor return), and a
11752        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
11753        // .. }` (the lower boundary of the accept-set) plus a
11754        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
11755        // .. }` (the upper boundary) must pass validate. The six together
11756        // jointly pin the accessor + validate-gate composition: any future
11757        // silent detour that had the accessor return a fresh `None` on any
11758        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
11759        // collapse) would silently absorb the `RestartWindowZero` refusal
11760        // at the accessor boundary and the validate gate would accept a
11761        // struct-literal `SupervisorSpec { restart_window:
11762        // Some(Duration::ZERO), .. }` — the composition pin catches that
11763        // at caixa-core build time.
11764        //
11765        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
11766        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
11767        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
11768        // accessor-composition pin on the per-`:politicas :timeout` axis —
11769        // same "the validate / shape-gate predicate must route through
11770        // the substrate-primitive typed dispatch" discipline extended
11771        // onto the peer M2 supervisor-slot optional-`Duration` axis.
11772        let child = ChildSpec {
11773            caixa: "worker".into(),
11774            versao: "^0.1".into(),
11775            restart: RestartPolicy::Permanent,
11776        };
11777        // None arm — must not surface any :restart-window-shaped refusal;
11778        // the `if let Some(_)` bracket returns early on `None` structurally.
11779        let s = SupervisorSpec {
11780            restart_window: None,
11781            children: vec![child.clone()],
11782            ..SupervisorSpec::default()
11783        };
11784        assert!(
11785            s.validate().is_ok(),
11786            "validate must accept restart_window: None (the never-reset \
11787             sentinel) — the `if let Some(_)` bracket returns early on \
11788             the None arm and the accessor must agree",
11789        );
11790        // Zero-floor arm.
11791        let s = SupervisorSpec {
11792            restart_window: Some(Duration::ZERO),
11793            children: vec![child.clone()],
11794            ..SupervisorSpec::default()
11795        };
11796        assert_eq!(
11797            s.validate().unwrap_err(),
11798            SupervisorError::RestartWindowZero,
11799            "validate must reject restart_window == Some(Duration::ZERO) \
11800             with RestartWindowZero — the accessor and the validate gate \
11801             must route through the same substrate-primitive typed \
11802             dispatch on the zero-floor arm",
11803        );
11804        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
11805        // byte-equal the accessor's return so a future rebrand on the
11806        // accessor lands in the diagnostic without a coordinated rewrite.
11807        let sub_ms = Duration::from_micros(1500);
11808        let s = SupervisorSpec {
11809            restart_window: Some(sub_ms),
11810            children: vec![child.clone()],
11811            ..SupervisorSpec::default()
11812        };
11813        match s.validate().unwrap_err() {
11814            SupervisorError::RestartWindowNotCanonical { window } => {
11815                assert_eq!(
11816                    Some(window),
11817                    s.restart_window(),
11818                    "RestartWindowNotCanonical.window must byte-equal \
11819                     SupervisorSpec::restart_window().unwrap() — the \
11820                     non-canonical-arm refusal reads through the lifted \
11821                     accessor",
11822                );
11823                assert_eq!(
11824                    window, sub_ms,
11825                    "RestartWindowNotCanonical.window must carry the \
11826                     author-declared :supervisor :restart-window value \
11827                     verbatim (got {window:?}, expected {sub_ms:?})",
11828                );
11829            }
11830            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
11831        }
11832        // Cap arm — the surfaced `window:` field must byte-equal the
11833        // accessor's return.
11834        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
11835        let s = SupervisorSpec {
11836            restart_window: Some(over_cap),
11837            children: vec![child.clone()],
11838            ..SupervisorSpec::default()
11839        };
11840        match s.validate().unwrap_err() {
11841            SupervisorError::RestartWindowExceedsCap { window } => {
11842                assert_eq!(
11843                    Some(window),
11844                    s.restart_window(),
11845                    "RestartWindowExceedsCap.window must byte-equal \
11846                     SupervisorSpec::restart_window().unwrap() — the \
11847                     cap-arm refusal reads through the lifted accessor",
11848                );
11849                assert_eq!(
11850                    window, over_cap,
11851                    "RestartWindowExceedsCap.window must carry the \
11852                     author-declared :supervisor :restart-window value \
11853                     verbatim (got {window:?}, expected {over_cap:?})",
11854                );
11855            }
11856            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
11857        }
11858        // Lower + upper accept-set boundaries.
11859        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
11860            let s = SupervisorSpec {
11861                restart_window: Some(restart_window),
11862                children: vec![child.clone()],
11863                ..SupervisorSpec::default()
11864            };
11865            assert!(
11866                s.validate().is_ok(),
11867                "validate must accept restart_window == Some({restart_window:?}) \
11868                 (an accept-set boundary of \
11869                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
11870            );
11871        }
11872    }
11873
11874    #[test]
11875    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
11876        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
11877        // `Option<Duration>` by copy — `Duration` is `Copy` (so
11878        // `Option<Duration>` is `Copy`) and the accessor must return by
11879        // value, not by reference. Peer of the sibling M2
11880        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
11881        // per-`:limits :wall-clock` axis and the sibling M3
11882        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
11883        // per-`:politicas :timeout` axis, extended onto the peer M2
11884        // supervisor-slot `Option<Duration>` copy-invariant shape — the
11885        // accessor's returned `Option<Duration>` must outlive `&self`
11886        // (multiple calls must return equal values from a dropped-`&self`
11887        // copy, since the returned Option carries no borrow), and calling
11888        // the accessor twice on the same SupervisorSpec must yield the
11889        // same `Option<Duration>` verbatim (idempotent, no side effects
11890        // on `&self`).
11891        //
11892        // Pins against a future silent detour that returned
11893        // `Option<&Duration>` (which would type-check but silently break
11894        // every downstream caller — the future wasm-operator's
11895        // per-supervisor restart-intensity counter consumes `Duration` by
11896        // value and `&Duration` would fold to a detached copy at the call
11897        // site), an accidental `Option::as_ref()` projection
11898        // (`self.restart_window.as_ref()` would also type-check but
11899        // return `Option<&Duration>`), or a one-arm-only accessor that
11900        // reads `Some(*w)` in the Some arm but reads a fresh
11901        // `Default::default()` (which would collapse to `Duration::ZERO`,
11902        // not `None`) in the None arm — a footgun the
11903        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
11904        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
11905        // requires `Period > 0` and `None` structurally expresses "never
11906        // reset" instead.
11907        for restart_window in [
11908            None,
11909            Some(Duration::from_millis(1)),
11910            Some(Duration::from_secs(60)),
11911            Some(SUPERVISOR_RESTART_WINDOW_MAX),
11912        ] {
11913            let s = SupervisorSpec {
11914                restart_window,
11915                ..SupervisorSpec::default()
11916            };
11917            let first = s.restart_window();
11918            let second = s.restart_window();
11919            assert_eq!(
11920                first, second,
11921                "SupervisorSpec::restart_window must be idempotent — two \
11922                 successive calls on the same &self must return the \
11923                 same Option<Duration>",
11924            );
11925            assert_eq!(
11926                first, restart_window,
11927                "SupervisorSpec::restart_window must return :supervisor \
11928                 :restart-window verbatim by copy — got {first:?}, \
11929                 expected {restart_window:?}",
11930            );
11931        }
11932    }
11933
11934    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
11935    //
11936    // The [`SupervisorSpec::children`] accessor lift is the seed of the
11937    // slice-return (`&[T]`) accessor discipline on the substrate — the four
11938    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
11939    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
11940    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
11941    // access at the time of this seed, and inherit this pin family's
11942    // discipline as future compounding runs migrate their consumers. The
11943    // three pins below cover (1) the accessor's byte-equal projection
11944    // against the raw field access across the empty / singleton / cohort
11945    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
11946    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
11947    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
11948    // consumer routing through the accessor on both arms, and (3) the
11949    // per-child validate loop's traversal reading the same slice-view the
11950    // accessor projects. Peer of the sibling M2
11951    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
11952    // two-consumer coherence pin on the per-`:supervisor`
11953    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
11954    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
11955
11956    #[test]
11957    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
11958        // The canonical per-`:supervisor` static-child-list scalar-shape
11959        // pin: [`SupervisorSpec::children`] must return the `:supervisor
11960        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
11961        // slice-view over the same backing buffer the raw
11962        // `self.children.as_slice()` field access borrows from, byte-
11963        // equal across every representative fixture in the accept-set —
11964        // the empty slice (the `SimpleOneForOne`-arm sentinel),
11965        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
11966        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
11967        // with the peer three restart-policy variants in play).
11968        //
11969        // Pins against a future silent detour that returned
11970        // `&Vec<ChildSpec>` (which would type-check but leak the
11971        // storage-side `Vec`'s grow/push/reserve surface no consumer of
11972        // the typed view reaches for), a fresh-allocated
11973        // `Vec<ChildSpec>` copy (which would type-check via a coercion
11974        // but silently break every downstream caller that relied on the
11975        // slice sharing the backing buffer's identity), or an
11976        // out-of-order or length-drifted projection (which would silently
11977        // split the per-child validate loop's traversal input from the
11978        // paired partition-dispatch `.is_empty()` probe's input).
11979        //
11980        // Peer of the sibling
11981        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
11982        // (eafb619) `Copy`-composite-enum byte-equal pin on the
11983        // per-`:supervisor` sibling-restart-strategy axis, extended onto
11984        // the per-`:supervisor` static-child-list `Vec`-carry axis.
11985        let fixtures: Vec<Vec<ChildSpec>> = vec![
11986            Vec::new(),
11987            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
11988            vec![
11989                child("worker", "^0.1", RestartPolicy::Permanent),
11990                child("cache-server", "^0.1", RestartPolicy::Transient),
11991            ],
11992            vec![
11993                child("worker", "^0.1", RestartPolicy::Permanent),
11994                child("cache-server", "^0.1", RestartPolicy::Transient),
11995                child("scratch-job", "^0.1", RestartPolicy::Temporary),
11996            ],
11997        ];
11998        for children in fixtures {
11999            let s = SupervisorSpec {
12000                children: children.clone(),
12001                ..SupervisorSpec::default()
12002            };
12003            assert_eq!(
12004                s.children(),
12005                children.as_slice(),
12006                "SupervisorSpec::children must return :supervisor \
12007                 :children verbatim (got {:?}, expected {:?})",
12008                s.children(),
12009                children.as_slice(),
12010            );
12011            assert_eq!(
12012                s.children(),
12013                s.children.as_slice(),
12014                "SupervisorSpec::children accessor and \
12015                 .children.as_slice() field access must byte-equal — \
12016                 the accessor is the substrate-primitive typed \
12017                 dispatch every downstream static-child-list consumer \
12018                 must route through",
12019            );
12020            assert_eq!(
12021                s.children().len(),
12022                s.children.len(),
12023                "SupervisorSpec::children().len() must byte-equal \
12024                 self.children.len() — a length-drift would silently \
12025                 split the paired partition-dispatch `.is_empty()` \
12026                 probe input from the per-child validate loop's \
12027                 traversal input",
12028            );
12029        }
12030    }
12031
12032    #[test]
12033    fn validate_reads_through_lifted_children_accessor() {
12034        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
12035        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
12036        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
12037        // when the accessor projects a non-empty slice under a
12038        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
12039        // `self.children().is_empty()` refusal probe (which must trip
12040        // [`SupervisorError::NoChildren`] when the accessor projects the
12041        // empty slice under any peer estrategia), and the per-child
12042        // validate loop's `for child in self.children()` traversal
12043        // (which must reach every entry in the same order the accessor
12044        // projects) must all key off the lifted accessor, so any future
12045        // rebrand on the typed slot's reader shape lands at exactly one
12046        // place. Pins the three-site coherence by exercising each
12047        // production consumer end-to-end: (1) the
12048        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
12049        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
12050        // refusal under the empty slice + non-`SimpleOneForOne`
12051        // estrategia across every peer variant, and (3) the per-child
12052        // duplicate-detection surface fires on the second entry of a
12053        // two-child cohort that shares a `:caixa` name (which requires
12054        // the loop to reach both entries — a first-entry-only projection
12055        // would silently pass since the dedup HashSet has room for the
12056        // first insert).
12057        //
12058        // Peer of the sibling M2
12059        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
12060        // two-consumer coherence pin on the per-`:supervisor`
12061        // sibling-restart-strategy axis, extended onto the
12062        // per-`:supervisor` static-child-list `Vec`-carry axis.
12063
12064        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
12065        // `SimpleOneForOne` estrategia must trip
12066        // `SimpleOneForOneWithStaticChildren`.
12067        let s = SupervisorSpec {
12068            estrategia: RestartStrategy::SimpleOneForOne,
12069            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
12070            ..SupervisorSpec::default()
12071        };
12072        assert_eq!(
12073            s.validate().unwrap_err(),
12074            SupervisorError::SimpleOneForOneWithStaticChildren,
12075            "SimpleOneForOne + non-empty children must trip \
12076             SimpleOneForOneWithStaticChildren — the accessor projects \
12077             a non-empty slice, and the SimpleOneForOne-arm refusal \
12078             probe reads through the lifted accessor",
12079        );
12080        assert!(
12081            !s.children().is_empty(),
12082            "the SimpleOneForOne-arm refusal input must be a non-empty \
12083             slice per the accessor's projection",
12084        );
12085
12086        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
12087        // under any peer estrategia must trip `NoChildren`.
12088        for estrategia in [
12089            RestartStrategy::OneForOne,
12090            RestartStrategy::OneForAll,
12091            RestartStrategy::RestForOne,
12092        ] {
12093            let s = SupervisorSpec {
12094                estrategia,
12095                children: Vec::new(),
12096                ..SupervisorSpec::default()
12097            };
12098            match s.validate().unwrap_err() {
12099                SupervisorError::NoChildren { estrategia: e } => {
12100                    assert_eq!(
12101                        e, estrategia,
12102                        "NoChildren.estrategia must carry the author-\
12103                         declared :supervisor :estrategia variant \
12104                         verbatim (got {e:?}, expected {estrategia:?})",
12105                    );
12106                }
12107                other => panic!(
12108                    "expected NoChildren, got {other:?} for \
12109                     estrategia={estrategia:?}"
12110                ),
12111            }
12112            assert!(
12113                s.children().is_empty(),
12114                "the non-SimpleOneForOne-arm refusal input must be the \
12115                 empty slice per the accessor's projection",
12116            );
12117        }
12118
12119        // (3) Per-child validate loop: a two-child cohort that shares a
12120        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
12121        // reach both entries through the accessor.
12122        let s = SupervisorSpec {
12123            estrategia: RestartStrategy::OneForOne,
12124            children: vec![
12125                child("worker", "^0.1", RestartPolicy::Permanent),
12126                child("worker", "^0.2", RestartPolicy::Transient),
12127            ],
12128            ..SupervisorSpec::default()
12129        };
12130        match s.validate().unwrap_err() {
12131            SupervisorError::DuplicateChildCaixa { caixa } => {
12132                assert_eq!(
12133                    caixa, "worker",
12134                    "DuplicateChildCaixa.caixa must carry the shared \
12135                     child `:caixa` name verbatim",
12136                );
12137            }
12138            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
12139        }
12140        assert_eq!(
12141            s.children().len(),
12142            2,
12143            "the per-child validate loop's traversal input must be a \
12144             two-element slice per the accessor's projection",
12145        );
12146    }
12147
12148    // Shared helper for the M2 per-`:children` per-slot-gate ≡
12149    // `validate` equivalence pins: builds an `OneForOne`-estrategia
12150    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
12151    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
12152    // bracket all pass cleanly so the sole failing surface is the
12153    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
12154    // pins the two-altitude equivalence on the paired probe.
12155    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
12156        let s = SupervisorSpec {
12157            estrategia: RestartStrategy::OneForOne,
12158            children,
12159            ..SupervisorSpec::default()
12160        };
12161        let via_gate = s.validate_children().unwrap_err();
12162        let via_validate = s.validate().unwrap_err();
12163        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
12164        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
12165        assert_eq!(
12166            via_gate, via_validate,
12167            "per-slot gate ≡ validate() must discriminate the same \
12168             refusal shape",
12169        );
12170    }
12171
12172    #[test]
12173    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
12174        // Fail-before-pass-after equivalence pin on the M2
12175        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
12176        // convergence — sibling of the M3 mesh-slot
12177        // `validate_membros_*` / `validate_contratos_*` /
12178        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
12179        // peer per-entry axes. Sweeps four of the five refusal shapes
12180        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
12181        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
12182        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
12183        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
12184        // duplicate-`:caixa` fan-out. Companion pin
12185        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
12186        // covers `ChildVersaoInvalid` (whose parser-owned reason string
12187        // needs pattern-matching, not equality) and the clean-pass
12188        // canonical fixture; together the two pins guarantee the
12189        // per-slot gate and `validate` discriminate the same set on
12190        // every per-child-covered input.
12191        assert_validate_children_matches_gate(
12192            vec![child("", "^0.1", RestartPolicy::Permanent)],
12193            &SupervisorError::EmptyChildName,
12194        );
12195        assert_validate_children_matches_gate(
12196            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
12197            &SupervisorError::ChildCaixaInvalid {
12198                caixa: "Worker".into(),
12199                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
12200            },
12201        );
12202        assert_validate_children_matches_gate(
12203            vec![child("worker", "", RestartPolicy::Permanent)],
12204            &SupervisorError::EmptyChildVersion {
12205                caixa: "worker".into(),
12206            },
12207        );
12208        assert_validate_children_matches_gate(
12209            vec![
12210                child("worker", "^0.1", RestartPolicy::Permanent),
12211                child("worker", "^0.2", RestartPolicy::Transient),
12212            ],
12213            &SupervisorError::DuplicateChildCaixa {
12214                caixa: "worker".into(),
12215            },
12216        );
12217    }
12218
12219    #[test]
12220    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
12221        // Second half of the two-altitude equivalence pin — covers the
12222        // one refusal shape whose reason string is parser-owned
12223        // (`ChildVersaoInvalid`, whose reason comes from the shared
12224        // [`crate::version::parse_requirement`] impl and may drift) and
12225        // the clean-pass canonical fixture. Sibling pin
12226        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
12227        // covers the four equality-comparable refusal shapes.
12228        let s_bad_versao = SupervisorSpec {
12229            estrategia: RestartStrategy::OneForOne,
12230            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
12231            ..SupervisorSpec::default()
12232        };
12233        let via_gate = s_bad_versao.validate_children().unwrap_err();
12234        let via_validate = s_bad_versao.validate().unwrap_err();
12235        match (&via_gate, &via_validate) {
12236            (
12237                SupervisorError::ChildVersaoInvalid {
12238                    caixa: cg,
12239                    versao: vg,
12240                    ..
12241                },
12242                SupervisorError::ChildVersaoInvalid {
12243                    caixa: cv,
12244                    versao: vv,
12245                    ..
12246                },
12247            ) => {
12248                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
12249                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
12250                assert_eq!(cv, "worker", "validate() :caixa carrier");
12251                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
12252            }
12253            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
12254        }
12255        assert_eq!(
12256            via_gate, via_validate,
12257            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
12258        );
12259
12260        let s_ok = SupervisorSpec {
12261            estrategia: RestartStrategy::OneForOne,
12262            children: vec![
12263                child("worker-a", "^0.1", RestartPolicy::Permanent),
12264                child("worker-b", "~0.2.3", RestartPolicy::Transient),
12265                child("collector", "*", RestartPolicy::Temporary),
12266            ],
12267            ..SupervisorSpec::default()
12268        };
12269        s_ok.validate_children()
12270            .expect("per-slot gate must accept the clean-pass fixture");
12271        s_ok.validate()
12272            .expect("validate() must accept the clean-pass fixture");
12273    }
12274
12275    #[test]
12276    fn validate_children_is_self_contained_on_children_slot() {
12277        // Self-containment pin: [`SupervisorSpec::validate_children`]
12278        // resolves the per-child cascade against `&self` alone, without
12279        // depending on the peer `:estrategia`/`:max-restarts`/
12280        // `:restart-window` gates having run first — same posture the M3
12281        // peer per-slot gates carry (`validate_membros`,
12282        // `validate_contratos`, `validate_entrada`, `validate_placement`,
12283        // routing through their own oracles rather than borrowing state
12284        // threaded down from `validate`). A future consumer that reaches
12285        // the per-slot gate directly on a spec whose peer slots would
12286        // fail `validate` still surfaces the per-child refusal, not the
12287        // peer refusal.
12288        //
12289        // Construct a spec whose `:max-restarts` is `0` (which would
12290        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
12291        // the partition-dispatch) and whose `:children` carries a
12292        // `DuplicateChildCaixa` shape: the per-slot gate called directly
12293        // must surface `DuplicateChildCaixa`, proving it does not depend
12294        // on the peer `:max-restarts` gate running first.
12295        let s = SupervisorSpec {
12296            estrategia: RestartStrategy::OneForOne,
12297            max_restarts: 0,
12298            restart_window: Some(Duration::from_secs(60)),
12299            children: vec![
12300                child("worker", "^0.1", RestartPolicy::Permanent),
12301                child("worker", "^0.2", RestartPolicy::Transient),
12302            ],
12303        };
12304        assert_eq!(
12305            s.validate_children().unwrap_err(),
12306            SupervisorError::DuplicateChildCaixa {
12307                caixa: "worker".into(),
12308            },
12309            "per-slot gate must resolve per-child refusal directly against \
12310             `&self` — a dependency on the peer `:max-restarts` gate \
12311             running first would surface ZeroMaxRestarts here instead",
12312        );
12313        // The peer gate is still the surface `validate` reaches — pin
12314        // the ordering to establish that `validate_children` truly runs
12315        // last in `validate`'s dispatch, so a direct call bypasses the
12316        // peer gates on any spec whose per-child cascade would fail.
12317        assert_eq!(
12318            s.validate().unwrap_err(),
12319            SupervisorError::ZeroMaxRestarts,
12320            "validate() must surface the peer `:max-restarts` gate before \
12321             reaching the per-child cascade — this pins the dispatch \
12322             ordering the per-slot gate's self-containment complements",
12323        );
12324    }
12325
12326    #[test]
12327    fn child_spec_restart_accessor_is_const_fn() {
12328        // The [`ChildSpec::restart`] per-`:children` restart-decision-
12329        // policy `Copy`-return scalar accessor is declared
12330        // `#[must_use] pub const fn` — matching the sibling M2
12331        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
12332        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
12333        // both converted in this commit), the sibling M2
12334        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
12335        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
12336        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
12337        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
12338        // `Copy`-return `pub const fn` scalar accessors on the sibling
12339        // M3 surface. Pin the `const`-eval posture here so a future
12340        // accidental downgrade to non-`const` (an added runtime helper
12341        // reachable only from a non-`const` context, an
12342        // `Option<RestartPolicy>`-shape migration on the per-child
12343        // restart-decision axis once heterogeneous per-cluster
12344        // restart-policy overlays land that would silently drop the
12345        // `const` qualifier, a manual hand-rolled shadow) trips at
12346        // caixa-core build time rather than surfacing as a downstream
12347        // `const`-context regression far from the declaration.
12348        //
12349        // Same shape as the sibling M3
12350        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
12351        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
12352        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
12353        // accessor axis — the load-bearing witness lives in the
12354        // module-scope `const fn` wrapper `restart_via_const_fn` below:
12355        // a body that calls [`ChildSpec::restart`] under a `const fn`
12356        // signature is well-formed only when the callee is itself
12357        // `const fn`, so any future accidental downgrade of
12358        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
12359        // build time (const-eval E0015 `cannot call non-const method`),
12360        // strictly stronger than a runtime `assert!(CONST)` and
12361        // side-stepping the destructor-in-const restriction that
12362        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
12363        // items on `ChildSpec`'s `String` carriers.
12364        //
12365        // The runtime body sweeps every closed-set [`RestartPolicy`]
12366        // arm and asserts the wrapped and direct dispatches agree.
12367        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
12368            c.restart()
12369        }
12370        for restart in [
12371            RestartPolicy::Permanent,
12372            RestartPolicy::Transient,
12373            RestartPolicy::Temporary,
12374        ] {
12375            let c = ChildSpec {
12376                caixa: "worker".into(),
12377                versao: "^0.1".into(),
12378                restart,
12379            };
12380            assert_eq!(
12381                restart_via_const_fn(&c),
12382                c.restart(),
12383                "const-fn-wrapped and direct dispatch on \
12384                 ChildSpec::restart must agree for {restart:?}",
12385            );
12386            assert_eq!(
12387                c.restart(),
12388                restart,
12389                "ChildSpec::restart must return the storage-side \
12390                 RestartPolicy verbatim for {restart:?} (a violation \
12391                 means the accessor stopped being a raw field-return \
12392                 copy)",
12393            );
12394        }
12395    }
12396
12397    #[test]
12398    fn supervisor_spec_estrategia_accessor_is_const_fn() {
12399        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
12400        // sibling-restart-strategy `Copy`-return scalar accessor is
12401        // declared `#[must_use] pub const fn` — matching the sibling M2
12402        // per-`:children` [`ChildSpec::restart`] (pinned by
12403        // [`child_spec_restart_accessor_is_const_fn`] above, both
12404        // converted in this commit), the sibling M2 per-`:supervisor`
12405        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
12406        // accessor already `pub const fn`, and mirroring the peer M3
12407        // mesh-slot per-`:placement`
12408        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
12409        // `pub const fn` scalar accessor whose method-name discipline
12410        // the [`SupervisorSpec::estrategia`] method was authored to
12411        // match. Pin the `const`-eval posture here so a future
12412        // accidental downgrade to non-`const` (an added runtime helper
12413        // reachable only from a non-`const` context, an
12414        // `Option<RestartStrategy>`-shape migration once the substrate
12415        // grows per-cluster strategy overlays that would silently drop
12416        // the `const` qualifier, a manual hand-rolled shadow) trips at
12417        // caixa-core build time rather than surfacing as a downstream
12418        // `const`-context regression far from the declaration.
12419        //
12420        // Same shape as the sibling
12421        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
12422        // load-bearing witness lives in the module-scope `const fn`
12423        // wrapper `estrategia_via_const_fn` below: a body that calls
12424        // [`SupervisorSpec::estrategia`] under a `const fn` signature
12425        // is well-formed only when the callee is itself `const fn`,
12426        // side-stepping the destructor-in-const restriction that would
12427        // otherwise block a direct
12428        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
12429        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
12430        // carriers.
12431        //
12432        // The runtime body sweeps every closed-set [`RestartStrategy`]
12433        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
12434        // direct dispatches agree.
12435        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
12436            s.estrategia()
12437        }
12438        for &estrategia in RestartStrategy::ALL {
12439            let s = SupervisorSpec {
12440                estrategia,
12441                max_restarts: 5,
12442                restart_window: Some(Duration::from_secs(60)),
12443                children: Vec::new(),
12444            };
12445            assert_eq!(
12446                estrategia_via_const_fn(&s),
12447                s.estrategia(),
12448                "const-fn-wrapped and direct dispatch on \
12449                 SupervisorSpec::estrategia must agree for {estrategia:?}",
12450            );
12451            assert_eq!(
12452                s.estrategia(),
12453                estrategia,
12454                "SupervisorSpec::estrategia must return the storage-side \
12455                 RestartStrategy verbatim for {estrategia:?} (a violation \
12456                 means the accessor stopped being a raw field-return \
12457                 copy)",
12458            );
12459        }
12460    }
12461
12462    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
12463    // macro definition (see the paired doc-block above the macro
12464    // definition) — every generated `<ctor>(caixa: &str) -> Self`
12465    // constructor folds the uniform `Self::<Variant> { caixa:
12466    // caixa.to_string() }` one-field struct-literal onto one substrate
12467    // primitive. The three per-variant equivalence pins below
12468    // (fail-before-pass-after by construction — a byte-mismatched macro
12469    // arm would trip its equivalence pin first) lock each generated
12470    // constructor to its struct-literal peer under `PartialEq`, so
12471    // every wire-up in [`SupervisorSpec::validate_children`] and
12472    // [`validate_no_self_supervision`] on that variant produces a
12473    // byte-equal `SupervisorError` to the pre-lift open-coded
12474    // struct-literal. The cross-axis pin that follows (non-default
12475    // caixa name) routes the sole constructor input axis through
12476    // `.to_string()`, so the fold does not silently collapse onto a
12477    // fixed name.
12478    //
12479    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
12480    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
12481    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
12482    // `missing_entry_ctor_matches_struct_literal_wrap` /
12483    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
12484    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
12485    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
12486    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
12487    // on the six sibling ctor families the recent trajectory closed
12488    // on the peer `LayoutError` / `AplicacaoError` envelopes.
12489
12490    #[test]
12491    fn empty_child_version_ctor_matches_struct_literal_wrap() {
12492        assert_eq!(
12493            SupervisorError::empty_child_version("worker"),
12494            SupervisorError::EmptyChildVersion {
12495                caixa: "worker".to_string(),
12496            },
12497            "generated empty_child_version ctor must produce byte-equal \
12498             SupervisorError to the open-coded struct-literal wrap on the \
12499             same &str fixture",
12500        );
12501    }
12502
12503    #[test]
12504    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
12505        assert_eq!(
12506            SupervisorError::duplicate_child_caixa("worker"),
12507            SupervisorError::DuplicateChildCaixa {
12508                caixa: "worker".to_string(),
12509            },
12510            "generated duplicate_child_caixa ctor must produce byte-equal \
12511             SupervisorError to the open-coded struct-literal wrap on the \
12512             same &str fixture",
12513        );
12514    }
12515
12516    #[test]
12517    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
12518        assert_eq!(
12519            SupervisorError::child_supervises_self("orquestra"),
12520            SupervisorError::ChildSupervisesSelf {
12521                caixa: "orquestra".to_string(),
12522            },
12523            "generated child_supervises_self ctor must produce byte-equal \
12524             SupervisorError to the open-coded struct-literal wrap on the \
12525             same &str fixture",
12526        );
12527    }
12528
12529    // Per-variant equivalence pins for the two lifted
12530    // [`SupervisorError::child_caixa_invalid`] /
12531    // [`SupervisorError::child_versao_invalid`] inherent constructors
12532    // (fail-before-pass-after by construction — a byte-mismatched ctor body
12533    // would trip its equivalence pin first). Each pins the ctor output to
12534    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
12535    // in [`SupervisorSpec::validate_children`] on the two variants
12536    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
12537    // struct-literal on the same scalar fixtures. Peers of the sibling
12538    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
12539    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
12540    // the peer `AplicacaoError` envelope's
12541    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
12542
12543    #[test]
12544    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
12545        let caixa = "Worker";
12546        let reason = "sample reason text";
12547        assert_eq!(
12548            SupervisorError::child_caixa_invalid(caixa, reason),
12549            SupervisorError::ChildCaixaInvalid {
12550                caixa: caixa.to_string(),
12551                reason: reason.to_string(),
12552            },
12553            "lifted child_caixa_invalid ctor must produce byte-equal \
12554             SupervisorError to the open-coded struct-literal wrap on the \
12555             same (&str, reason) fixture",
12556        );
12557    }
12558
12559    #[test]
12560    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
12561        let caixa = "worker";
12562        let versao = "not-a-req";
12563        let reason = "sample reason text";
12564        assert_eq!(
12565            SupervisorError::child_versao_invalid(caixa, versao, reason),
12566            SupervisorError::ChildVersaoInvalid {
12567                caixa: caixa.to_string(),
12568                versao: versao.to_string(),
12569                reason: reason.to_string(),
12570            },
12571            "lifted child_versao_invalid ctor must produce byte-equal \
12572             SupervisorError to the open-coded struct-literal wrap on the \
12573             same (&str, &str, reason) fixture",
12574        );
12575    }
12576
12577    #[test]
12578    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
12579        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
12580        // against a `&str`-literal vs. `format!(…)` reason input to pin
12581        // both constructors accept the `impl Into<String>` bound
12582        // uniformly, so neither wire-up site drifts under a per-arm
12583        // wrapper transformation on the caller-side `reason` axis. Peer
12584        // of the sibling
12585        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
12586        // sweep on the peer `AplicacaoError` envelope.
12587        let via_literal = "literal reason text";
12588        let via_format = format!("{} reason text", "literal");
12589        assert_eq!(
12590            SupervisorError::child_caixa_invalid("Worker", via_literal),
12591            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
12592        );
12593        assert_eq!(
12594            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
12595            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
12596        );
12597    }
12598
12599    #[test]
12600    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
12601        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
12602        // &str`) through a non-default fixture name against every
12603        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
12604        // so any wrapper-side lowercase / trim / truncate / re-order on
12605        // the `caixa.to_string()` sole-field construction surfaces
12606        // here rather than at a downstream diagnostic-shape mismatch.
12607        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
12608        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
12609        // through_to_string` / `contrato_target_ctors_route_edge_
12610        // triple_through_verbatim` / `contrato_empty_pair_ctors_
12611        // route_edge_pair_through_verbatim` cross-axis routing pins on
12612        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
12613        // here onto the `SupervisorError` `{ caixa: String }` envelope
12614        // so every substrate-primitive ctor family in caixa-core
12615        // guarantees the sole-field construction routes the caller's
12616        // `&str` through `.to_string()` verbatim.
12617        let name = "cache-v2";
12618        assert_eq!(
12619            SupervisorError::empty_child_version(name),
12620            SupervisorError::EmptyChildVersion {
12621                caixa: name.to_string(),
12622            },
12623        );
12624        assert_eq!(
12625            SupervisorError::duplicate_child_caixa(name),
12626            SupervisorError::DuplicateChildCaixa {
12627                caixa: name.to_string(),
12628            },
12629        );
12630        assert_eq!(
12631            SupervisorError::child_supervises_self(name),
12632            SupervisorError::ChildSupervisesSelf {
12633                caixa: name.to_string(),
12634            },
12635        );
12636    }
12637
12638    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
12639    //
12640    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
12641    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
12642    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
12643    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
12644    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
12645    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
12646    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
12647    // / silent constant-substitution on any one variant surfaces here rather
12648    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
12649    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
12650    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
12651    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
12652    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
12653    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
12654    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
12655    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
12656    #[test]
12657    fn no_children_ctor_matches_struct_literal_wrap() {
12658        let estrategia = RestartStrategy::OneForAll;
12659        assert_eq!(
12660            SupervisorError::no_children(estrategia),
12661            SupervisorError::NoChildren { estrategia },
12662            "generated no_children ctor must produce byte-equal \
12663             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
12664             on the same `Copy`-`RestartStrategy` fixture",
12665        );
12666    }
12667
12668    #[test]
12669    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
12670        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
12671        assert_eq!(
12672            SupervisorError::max_restarts_exceeds_cap(max_restarts),
12673            SupervisorError::MaxRestartsExceedsCap { max_restarts },
12674            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
12675             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
12676             struct-literal wrap on the same `Copy`-`u32` fixture",
12677        );
12678    }
12679
12680    #[test]
12681    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
12682        let window = Duration::from_micros(1_500);
12683        assert_eq!(
12684            SupervisorError::restart_window_not_canonical(window),
12685            SupervisorError::RestartWindowNotCanonical { window },
12686            "generated restart_window_not_canonical ctor must produce \
12687             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
12688             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
12689        );
12690    }
12691
12692    #[test]
12693    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
12694        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
12695        assert_eq!(
12696            SupervisorError::restart_window_exceeds_cap(window),
12697            SupervisorError::RestartWindowExceedsCap { window },
12698            "generated restart_window_exceeds_cap ctor must produce \
12699             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
12700             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
12701        );
12702    }
12703
12704    #[test]
12705    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
12706        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
12707        // constructor input axis through a non-default `Copy` fixture against
12708        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
12709        // side silent `.into()` / silent constant-substitution / silent field
12710        // re-name away from the canonical `estrategia | max_restarts | window`
12711        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
12712        // axis silently rerouted through some other `Copy` coercion, surfaces
12713        // here rather than at a downstream per-`:supervisor` diagnostic-shape
12714        // drift. Peer of the sibling
12715        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
12716        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
12717        // envelope's per-`:politicas` per-axis ctor family, extended here onto
12718        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
12719        // variant family folded onto a substrate primitive.
12720        //
12721        // Fixtures picked out of each variant's accept-set boundary rather
12722        // than the default value so a silent constant-substitution to a per-
12723        // variant sentinel surfaces here on the structural-equality assertion.
12724        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
12725        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
12726        // isn't the `SimpleOneForOne` arm the sibling
12727        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
12728        // `max_restarts` fixture picks an above-cap magnitude the cap arm
12729        // rejects; the two `Duration` fixtures pick the sub-millisecond and
12730        // above-cap ends of the `:restart-window` canonical-form + cap
12731        // bracket respectively.
12732        let estrategia = RestartStrategy::RestForOne;
12733        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
12734        let sub_ms = Duration::from_micros(1_500);
12735        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
12736        assert_eq!(
12737            SupervisorError::no_children(estrategia),
12738            SupervisorError::NoChildren { estrategia },
12739        );
12740        assert_eq!(
12741            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
12742            SupervisorError::MaxRestartsExceedsCap {
12743                max_restarts: above_cap_restarts,
12744            },
12745        );
12746        assert_eq!(
12747            SupervisorError::restart_window_not_canonical(sub_ms),
12748            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
12749        );
12750        assert_eq!(
12751            SupervisorError::restart_window_exceeds_cap(above_hour),
12752            SupervisorError::RestartWindowExceedsCap { window: above_hour },
12753        );
12754    }
12755
12756    #[test]
12757    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
12758        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
12759        // generated ctor `const fn` so a caller can pin a `SupervisorError`
12760        // at compile time — the same zero-runtime-work property the pre-lift
12761        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
12762        // its `Copy`-pass-through construction path (no `.to_string()` /
12763        // `.into()` allocation, no branching). If any future edit silently
12764        // drops the `const` qualifier from the macro body the per-arm `const`
12765        // bindings below fail to compile, which surfaces the regression at
12766        // the substrate-primitive definition rather than at some downstream
12767        // consumer that had come to rely on the `const`-constructibility.
12768        // Peer of the sibling
12769        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
12770        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
12771        // per-`:politicas` per-axis ctor family.
12772        const NO_CHILDREN: SupervisorError =
12773            SupervisorError::no_children(RestartStrategy::OneForAll);
12774        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
12775        const WINDOW_NC: SupervisorError =
12776            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
12777        const WINDOW_CAP: SupervisorError =
12778            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
12779        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
12780        assert!(matches!(
12781            MAX_RESTARTS_CAP,
12782            SupervisorError::MaxRestartsExceedsCap { .. }
12783        ));
12784        assert!(matches!(
12785            WINDOW_NC,
12786            SupervisorError::RestartWindowNotCanonical { .. }
12787        ));
12788        assert!(matches!(
12789            WINDOW_CAP,
12790            SupervisorError::RestartWindowExceedsCap { .. }
12791        ));
12792    }
12793}